From 0dbab25c9ef996a0b2869bece7863fa028252dbe Mon Sep 17 00:00:00 2001 From: viralpraxis Date: Sun, 10 Mar 2024 16:13:15 +0300 Subject: [PATCH] WIP --- .github/workflows/lint.yml | 20 + .github/workflows/test.yml | 28 + .gitignore | 58 +- .rspec | 3 + .rubocop.yml | 12 + CHANGELOG.md | 5 + CODE_OF_CONDUCT.md | 84 +++ Gemfile | 5 + Gemfile.lock | 91 +++ LICENSE => LICENSE.txt | 12 +- README.md | 115 +++ Rakefile | 10 + bin/console | 15 + bin/rake | 27 + bin/rubocop | 27 + bin/setup | 8 + lib/purist.rb | 32 + lib/purist/configuration.rb | 187 +++++ lib/purist/errors.rb | 17 + lib/purist/handler.rb | 25 + lib/purist/integrations/rspec.rb | 4 + lib/purist/integrations/rspec/be_impure.rb | 3 + lib/purist/integrations/rspec/be_pure.rb | 47 ++ lib/purist/integrations/rspec/matchers.rb | 16 + lib/purist/matcher.rb | 9 + lib/purist/trace_point_slice.rb | 15 + lib/purist/version.rb | 5 + purist.gemspec | 30 + spec/purist/configuration_spec.rb | 7 + spec/purist/handler_spec.rb | 16 + .../integrations/rspec/matchers_spec.rb | 68 ++ spec/purist/version_spec.rb | 5 + spec/purist_spec.rb | 686 ++++++++++++++++++ spec/spec_helper.rb | 28 + 34 files changed, 1663 insertions(+), 57 deletions(-) create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/test.yml create mode 100644 .rspec create mode 100644 .rubocop.yml create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 Gemfile create mode 100644 Gemfile.lock rename LICENSE => LICENSE.txt (87%) create mode 100644 README.md create mode 100644 Rakefile create mode 100755 bin/console create mode 100755 bin/rake create mode 100755 bin/rubocop create mode 100755 bin/setup create mode 100644 lib/purist.rb create mode 100644 lib/purist/configuration.rb create mode 100644 lib/purist/errors.rb create mode 100644 lib/purist/handler.rb create mode 100644 lib/purist/integrations/rspec.rb create mode 100644 lib/purist/integrations/rspec/be_impure.rb create mode 100644 lib/purist/integrations/rspec/be_pure.rb create mode 100644 lib/purist/integrations/rspec/matchers.rb create mode 100644 lib/purist/matcher.rb create mode 100644 lib/purist/trace_point_slice.rb create mode 100644 lib/purist/version.rb create mode 100644 purist.gemspec create mode 100644 spec/purist/configuration_spec.rb create mode 100644 spec/purist/handler_spec.rb create mode 100644 spec/purist/integrations/rspec/matchers_spec.rb create mode 100644 spec/purist/version_spec.rb create mode 100644 spec/purist_spec.rb create mode 100644 spec/spec_helper.rb diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..0cf9279 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,20 @@ +name: Lint + +on: [push, pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: 2.7.4 + bundler-cache: true + + - name: RuboCop + run: bin/rubocop --format github diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..4798c2f --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,28 @@ +name: Test + +on: [push] + +jobs: + test: + name: on ruby ${{matrix.ruby}} + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + ruby: ["2.7", "3.0", "3.1", "3.2", "3.3", head] + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{matrix.ruby}} + + - name: Install dependencies + run: bundle install --jobs 4 --retry 3 + + - name: RSpec + run: bin/rake spec diff --git a/.gitignore b/.gitignore index e3200e0..3ea8ff5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,56 +1,12 @@ -*.gem -*.rbc -/.config +/.bundle/ +/.yardoc +/_yardoc/ /coverage/ -/InstalledFiles +/doc/ /pkg/ /spec/reports/ -/spec/examples.txt -/test/tmp/ -/test/version_tmp/ /tmp/ +/.vscode -# Used by dotenv library to load environment variables. -# .env - -# Ignore Byebug command history file. -.byebug_history - -## Specific to RubyMotion: -.dat* -.repl_history -build/ -*.bridgesupport -build-iPhoneOS/ -build-iPhoneSimulator/ - -## Specific to RubyMotion (use of CocoaPods): -# -# We recommend against adding the Pods directory to your .gitignore. However -# you should judge for yourself, the pros and cons are mentioned at: -# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -# vendor/Pods/ - -## Documentation cache and generated files: -/.yardoc/ -/_yardoc/ -/doc/ -/rdoc/ - -## Environment normalization: -/.bundle/ -/vendor/bundle -/lib/bundler/man/ - -# for a library or gem, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# Gemfile.lock -# .ruby-version -# .ruby-gemset - -# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: -.rvmrc - -# Used by RuboCop. Remote config files pulled in from inherit_from directive. -# .rubocop-https?--* +# rspec failure tracking +.rspec_status diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..2ebfc4a --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,12 @@ +require: + - rubocop-rake + - rubocop-rspec + +AllCops: + NewCops: enable + +Style/Documentation: + Enabled: false + +RSpec/NestedGroups: + Enabled: false diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..97c5d05 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +## [Unreleased] + +## [1.0.0] - 2024-03-10 + +- Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..93171dd --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at iaroslav2k. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..7f4f5e9 --- /dev/null +++ b/Gemfile @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' + +gemspec diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..2d209fa --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,91 @@ +PATH + remote: . + specs: + purist (1.0.0) + +GEM + remote: https://rubygems.org/ + specs: + ast (2.4.2) + coderay (1.1.3) + diff-lcs (1.5.1) + docile (1.4.0) + json (2.7.1) + language_server-protocol (3.17.0.3) + method_source (1.0.0) + parallel (1.24.0) + parser (3.3.0.5) + ast (~> 2.4.1) + racc + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + racc (1.7.3) + rainbow (3.1.1) + rake (13.1.0) + regexp_parser (2.9.0) + rexml (3.2.6) + rspec (3.13.0) + rspec-core (~> 3.13.0) + rspec-expectations (~> 3.13.0) + rspec-mocks (~> 3.13.0) + rspec-core (3.13.0) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-its (1.3.0) + rspec-core (>= 3.0.0) + rspec-expectations (>= 3.0.0) + rspec-mocks (3.13.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-support (3.13.1) + rubocop (1.61.0) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.30.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.31.1) + parser (>= 3.3.0.4) + rubocop-capybara (2.20.0) + rubocop (~> 1.41) + rubocop-factory_bot (2.25.1) + rubocop (~> 1.41) + rubocop-rake (0.6.0) + rubocop (~> 1.0) + rubocop-rspec (2.27.1) + rubocop (~> 1.40) + rubocop-capybara (~> 2.17) + rubocop-factory_bot (~> 2.22) + ruby-progressbar (1.13.0) + simplecov (0.22.0) + docile (~> 1.1) + simplecov-html (~> 0.11) + simplecov_json_formatter (~> 0.1) + simplecov-html (0.12.3) + simplecov_json_formatter (0.1.4) + unicode-display_width (2.5.0) + +PLATFORMS + ruby + +DEPENDENCIES + pry + purist! + rake + rspec + rspec-its + rubocop + rubocop-rake + rubocop-rspec + simplecov + +BUNDLED WITH + 2.3.17 diff --git a/LICENSE b/LICENSE.txt similarity index 87% rename from LICENSE rename to LICENSE.txt index e7da54a..d239787 100644 --- a/LICENSE +++ b/LICENSE.txt @@ -1,6 +1,6 @@ -MIT License +The MIT License (MIT) -Copyright (c) 2024 Yaroslav +Copyright (c) 2024 viralpraxis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -9,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..84b62c5 --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +# Purst + +Purist is a tool designed to help detecting impure ruby code in runtime. + +Ruby's stdlib and corelibs include a bunch of impure methods, including + +1. randomization: `Kernel.rand`, `Random.rand`, `SecureRandom.hex` and so on + +2. IO-related methods like `Kernel.readline` or `IO.popen` + +3. specialized side-effects like `Kernel.fork` or `Kernel.syscall` + +Purist hooks into ruby's `tracepoint` API to detect any invocation of these methods. +You can see the full list of target methods in `configuration.rb` source file. + +## Installation + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add purist + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install purist + +## Usage + +To check if your code is pure, simply pass it into `Purist.trace` method: + +```ruby +Purist.trace { 3 * 3 } # 9 +``` + +If provided block is impure, an exception will be raised: + +```ruby +irb(main):001> Purist.trace { p "I'm impure" } +gems/purist/lib/purist/handler.rb:23:in `call': {:path=>"(irb)", :lineno=>1, :module_name=>Kernel, :method_name=>:p} (Purist::Errors::PurityViolationError) +``` + +You can retrieve exception details like this: + +```ruby +exception = Purist.trace { p 1 } rescue $! + +p exception.trace_point + +{ + :path => ".../zeitwerk-2.6.13/lib/zeitwerk/kernel.rb", + :lineno => 23, + :module_name => Kernel, + :method_name => :require, + :backtrace => [...] +} +``` + +### RSpec integration + +Purist comes with built-in `RSpec` integration. To enable it, add `require "purist/integrations/rspec"` to your +`spec_helper.rb` and manually include `Purist::Integrations::RSpec::Matchers`: + +```ruby +require "purist/integrations/rspec" + +... + +RSpec.configure do |config| + ... + config.include Purist::Integrations::RSpec::Matchers + ... +end +``` + +And not `be_pure` and `be_impure` matchers are available: + +``` +expect { Module.new }.to be_pure +expect { User.where(name: :john) }.to be_impure +``` + +### Caveats + +1. Passing `Purist.trace` check does not mean your function is totally pure, for instance + +```ruby +def foo(n) + if n > 0 # pure branch + n.succ + else # impure branch + p n + end +end + +Purist.trace { foo(3) } # 4 +``` + +2. Ruby stdlib/corelib is quite big, I'm pretty sure some impure functions are missing from the list. + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/viralpraxis/purist. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/viralpraxis/purist/blob/master/CODE_OF_CONDUCT.md). + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). + +## Code of Conduct + +Everyone interacting in the Purist project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/viralpraxis/purist/blob/master/CODE_OF_CONDUCT.md). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..64a3183 --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require 'bundler/gem_tasks' +require 'rubocop/rake_task' +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new(:spec) +RuboCop::RakeTask.new(:rubocop) + +task default: %i[spec rubocop] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..63bfff8 --- /dev/null +++ b/bin/console @@ -0,0 +1,15 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require 'bundler/setup' +require 'purist' + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +# (If you use this, don't forget to add pry to your Gemfile!) +# require "pry" +# Pry.start + +require 'irb' +IRB.start(__FILE__) diff --git a/bin/rake b/bin/rake new file mode 100755 index 0000000..5f615c2 --- /dev/null +++ b/bin/rake @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rake' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +bundle_binstub = File.expand_path('bundle', __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('rake', 'rake') diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 0000000..cc105e8 --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rubocop' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +bundle_binstub = File.expand_path('bundle', __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('rubocop', 'rubocop') diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/lib/purist.rb b/lib/purist.rb new file mode 100644 index 0000000..64a5c78 --- /dev/null +++ b/lib/purist.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require_relative 'purist/configuration' +require_relative 'purist/errors' +require_relative 'purist/handler' +require_relative 'purist/matcher' +require_relative 'purist/version' + +module Purist + TRACE_POINT_TYPES = %i[call c_call].freeze + TRACE_HANDLER = proc do |trace_point| + next unless Purist::Matcher.match?(configuration.trace_targets, trace_point) + + Purist.handler.call(trace_point) + end + + def self.trace(&block) + return unless block + + TracePoint + .new(*TRACE_POINT_TYPES, &TRACE_HANDLER) + .enable(&block) + end + + def self.handler + @handler ||= Purist::Handler.build(configuration.action_on_purity_violation) + end + + def self.configuration + @configuration ||= Purist::Configuration.instance + end +end diff --git a/lib/purist/configuration.rb b/lib/purist/configuration.rb new file mode 100644 index 0000000..966ac17 --- /dev/null +++ b/lib/purist/configuration.rb @@ -0,0 +1,187 @@ +# frozen_string_literal: true + +require 'singleton' + +module Purist + class Configuration # rubocop:disable Metrics/ClassLength + include Singleton + + Subject = Class.new do + def self.from_module(module_name:, method_names:, with_singleton_class: false) + targets = {} + + method_names.each do |method_name| + targets[[module_name, method_name]] = true + targets[[module_name.singleton_class, method_name]] = true if with_singleton_class + end + + targets + end + end + + STDLIB_RANDOM_CLASS = + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.0.0') + Random::Base + else + Random + end + + TRACE_TARGETS = { + **Subject.from_module( + module_name: Kernel, + with_singleton_class: true, + method_names: %i[ + abort + at_exit + exit + exit! + + pp + gets + open + p + print + printf + putc + puts + readline + readlines + select + + set_trace_func + trace_var + untrace_var + + ` + exec + fork + spawn + system + + load + require + require_relative + + rand + srand + + sleep + sprintf + syscall + trap + + autoload + warn + ] + ), + **Subject.from_module( + module_name: IO.singleton_class, + method_names: %i[ + new + for_fd + open + pipe + popen + select + + binread + read + readlines + + binwrite + write + + foreach + + copy_stream + try_convert + + sysopen + ] + ), + **Subject.from_module( + module_name: IO, + method_names: %i[ + getbyte + getc + gets + pread + read + read_nonblock + readbyte + readchar + readline + readlines + readpartial + + print + printf + putc + puts + pwrite + write + write_nonblock + + pos + pos= + ropen + rewind + seek + + each + each_byte + each_char + each_codepoint + + autoclose= + binmode + close + close_on_exec + close_read + close_write + set_encoding + set_encoding_by_bom + sync= + + fdatasync + flush + fsync + ungetbyte + ungetc + + advise + fcntl + ioctl + sysread + sysseek + syswrite + ] + ), + **Subject.from_module( + module_name: Random.singleton_class, + with_singleton_class: true, + method_names: %i[ + bytes + rand + srand + urandom + ] + ), + **Subject.from_module( + module_name: STDLIB_RANDOM_CLASS, + method_names: %i[ + bytes + rand + ] + ) + }.freeze + + def trace_targets + TRACE_TARGETS + end + + def action_on_purity_violation + :raise + end + end +end diff --git a/lib/purist/errors.rb b/lib/purist/errors.rb new file mode 100644 index 0000000..9985260 --- /dev/null +++ b/lib/purist/errors.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +module Purist + module Errors + class Error < StandardError; end + + class PurityViolationError < Error + attr_reader :trace_point + + def initialize(message = nil, trace_point:) + @trace_point = trace_point + + super(message || trace_point.reject { |key| key == :backtrace }.inspect) + end + end + end +end diff --git a/lib/purist/handler.rb b/lib/purist/handler.rb new file mode 100644 index 0000000..f6508eb --- /dev/null +++ b/lib/purist/handler.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +require_relative 'trace_point_slice' + +module Purist + module Handler + def self.build(mode) + case mode&.to_sym + when :raise then Raise.new + when nil then nil + else raise ArgumentError, "Unexpected mode `#{mode.inspect}`" + end + end + + class Base; end # rubocop:disable Lint/EmptyClass + + class Raise < Base + def call(trace_point) + raise Purist::Errors::PurityViolationError.new( + trace_point: TracePointSlice.call(trace_point) + ) + end + end + end +end diff --git a/lib/purist/integrations/rspec.rb b/lib/purist/integrations/rspec.rb new file mode 100644 index 0000000..f8b6ba9 --- /dev/null +++ b/lib/purist/integrations/rspec.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +require_relative 'rspec/matchers' +require 'rspec/matchers' diff --git a/lib/purist/integrations/rspec/be_impure.rb b/lib/purist/integrations/rspec/be_impure.rb new file mode 100644 index 0000000..ba7e4d4 --- /dev/null +++ b/lib/purist/integrations/rspec/be_impure.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +RSpec::Matchers.define_negated_matcher :be_impure, :be_pure diff --git a/lib/purist/integrations/rspec/be_pure.rb b/lib/purist/integrations/rspec/be_pure.rb new file mode 100644 index 0000000..f1328d4 --- /dev/null +++ b/lib/purist/integrations/rspec/be_pure.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +module Purist + module Integrations + module RSpec + class BePure + def supports_value_expectations? + false + end + + def supports_block_expectations? + true + end + + def matches?(block) + Purist.trace { block.call } + + true + rescue Purist::Errors::PurityViolationError => e + @purist_exception = e + + false + end + + def description + 'block to be pure' + end + + def description_when_negated + 'block to be impure' + end + + def failure_message + "expected #{description}, detected impure #{purist_exception.trace_point.inspect}" + end + + def failure_message_when_negated + "expected #{description_when_negated}, but no side-effects were detected" + end + + private + + attr_reader :purist_exception + end + end + end +end diff --git a/lib/purist/integrations/rspec/matchers.rb b/lib/purist/integrations/rspec/matchers.rb new file mode 100644 index 0000000..49fa35c --- /dev/null +++ b/lib/purist/integrations/rspec/matchers.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require_relative 'be_pure' +require_relative 'be_impure' + +module Purist + module Integrations + module RSpec + module Matchers + def be_pure + BePure.new + end + end + end + end +end diff --git a/lib/purist/matcher.rb b/lib/purist/matcher.rb new file mode 100644 index 0000000..a1410a3 --- /dev/null +++ b/lib/purist/matcher.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module Purist + class Matcher + def self.match?(specification, trace_point) + specification.key? [trace_point.defined_class, trace_point.callee_id] + end + end +end diff --git a/lib/purist/trace_point_slice.rb b/lib/purist/trace_point_slice.rb new file mode 100644 index 0000000..2b76dda --- /dev/null +++ b/lib/purist/trace_point_slice.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module Purist + class TracePointSlice + def self.call(trace_point) + { + path: trace_point.path, + lineno: trace_point.lineno, + module_name: trace_point.defined_class, + method_name: trace_point.callee_id, + backtrace: trace_point.binding.send(:caller) + } + end + end +end diff --git a/lib/purist/version.rb b/lib/purist/version.rb new file mode 100644 index 0000000..90dab00 --- /dev/null +++ b/lib/purist/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Purist + VERSION = '1.0.0' +end diff --git a/purist.gemspec b/purist.gemspec new file mode 100644 index 0000000..af7585a --- /dev/null +++ b/purist.gemspec @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require_relative 'lib/purist/version' + +Gem::Specification.new do |spec| + spec.name = 'purist' + spec.version = Purist::VERSION + spec.summary = 'Automatic runtime impure methods invocation detection' + spec.description = 'Automatic runtime impure methods invocation detection' + spec.authors = ['Yaroslav Kurbatov'] + spec.required_ruby_version = '>= 2.7.0' + spec.email = 'iaroslav2k@gmail.com' + spec.homepage = 'https://github.com/viralpraxis/purist' + spec.license = 'MIT' + + spec.metadata['homepage_uri'] = spec.homepage + spec.metadata['source_code_uri'] = spec.homepage + spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md" + spec.metadata['rubygems_mfa_required'] = 'true' + + spec.files = Dir.chdir(File.expand_path(__dir__)) do + `git ls-files -z lib`.split("\x0") + end + + spec.extra_rdoc_files = %w[README.md LICENSE.txt] + + %w[pry rake rspec rspec-its rubocop rubocop-rake rubocop-rspec simplecov].each do |gem| + spec.add_development_dependency gem + end +end diff --git a/spec/purist/configuration_spec.rb b/spec/purist/configuration_spec.rb new file mode 100644 index 0000000..5a7cbef --- /dev/null +++ b/spec/purist/configuration_spec.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +RSpec.describe Purist::Configuration do + describe '#action_on_purity_violation' do + it { expect(described_class.instance.action_on_purity_violation).to eq(:raise) } + end +end diff --git a/spec/purist/handler_spec.rb b/spec/purist/handler_spec.rb new file mode 100644 index 0000000..750ef3e --- /dev/null +++ b/spec/purist/handler_spec.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +RSpec.describe Purist::Handler do + describe '.build' do + def perform(mode) + described_class.build(mode) + end + + it { expect(perform(:raise)).to be_an_instance_of(described_class::Raise) } + it { expect(perform(nil)).to be_nil } + + specify do + expect { perform(:warn) }.to raise_error(ArgumentError, 'Unexpected mode `:warn`') + end + end +end diff --git a/spec/purist/integrations/rspec/matchers_spec.rb b/spec/purist/integrations/rspec/matchers_spec.rb new file mode 100644 index 0000000..054793d --- /dev/null +++ b/spec/purist/integrations/rspec/matchers_spec.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +RSpec.describe Purist::Integrations::RSpec::Matchers do + describe '#be_pure' do + context 'with pure block' do + it { expect { 1 + 1 }.to be_pure } + it { expect { Class.new }.to be_pure } + + # rubocop:disable RSpec/MultipleExpectations + specify do + expect do + expect { 1 + 1 }.not_to be_pure + end.to fail_with('expected block to be impure, but no side-effects were detected') + end + # rubocop:enable RSpec/MultipleExpectations + end + + context 'with impure block' do + it { expect { p 1 }.not_to be_pure } + it { expect { Kernel.puts 1 }.not_to be_pure } + + # rubocop:disable RSpec/MultipleExpectations + specify do + expect do + expect { p 1 }.to be_pure + end.to fail_with(/expected block to be pure, detected impure .+/) + end + # rubocop:enable RSpec/MultipleExpectations + end + + # rubocop:disable RSpec/MultipleExpectations + context 'with expectation on value' do + it 'raises exception' do + expect { expect(1).to be_pure } + .to raise_error(RSpec::Core::DeprecationError, /The implicit block expectation syntax is deprecated/) + end + end + # rubocop:enable RSpec/MultipleExpectations + end + + describe '#be_impure' do + context 'with pure block' do + it { expect { 1 + 1 }.not_to be_impure } + it { expect { Class.new }.not_to be_impure } + + # rubocop:disable RSpec/MultipleExpectations + specify do + expect do + expect { 1 + 1 }.to be_impure + end.to fail_with('expected block to be impure, but no side-effects were detected') + end + # rubocop:enable RSpec/MultipleExpectations + end + + context 'with impure block' do + it { expect { p 1 }.to be_impure } + it { expect { require 'securerandom' }.to be_impure } + + # rubocop:disable RSpec/MultipleExpectations + specify do + expect do + expect { p 1 }.not_to be_impure + end.to fail_with(/expected block to be pure, detected impure .+/) + end + # rubocop:enable RSpec/MultipleExpectations + end + end +end diff --git a/spec/purist/version_spec.rb b/spec/purist/version_spec.rb new file mode 100644 index 0000000..32a6ae9 --- /dev/null +++ b/spec/purist/version_spec.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +RSpec.describe Purist::VERSION do + it { is_expected.to be_a(String) } +end diff --git a/spec/purist_spec.rb b/spec/purist_spec.rb new file mode 100644 index 0000000..7859546 --- /dev/null +++ b/spec/purist_spec.rb @@ -0,0 +1,686 @@ +# frozen_string_literal: true + +require 'securerandom' + +require_relative '../lib/purist' + +RSpec.describe Purist do + describe '::TRACE_HANDLER' do + context 'with match' do + let(:trace_point) do + instance_double( + TracePoint, + event: :c_call, + path: 'some/path', + lineno: 42, + defined_class: Kernel, + callee_id: :p, + binding: [] + ) + end + + specify do + expect { described_class::TRACE_HANDLER[trace_point] } + .to raise_error(Purist::Errors::PurityViolationError) + end + end + + context 'without match' do + let(:trace_point) do + instance_double( + TracePoint, + event: :c_call, + path: 'some/path', + lineno: 42, + defined_class: Integer, + callee_id: :succ + ) + end + + specify do + expect { described_class::TRACE_HANDLER[trace_point] } + .not_to raise_error + end + end + end + + describe '.configuration' do + its(:configuration) { is_expected.to be_an_instance_of(Purist::Configuration) } + end + + describe '.trace' do + context 'with pure code' do + table = [ + { + name: 'simple arithmetics', + code: -> { 1.succ + 1 } + }, + { + name: 'module declaration', + code: -> {} + } + ] + + table.each do |entry| + context entry.fetch(:name) do + specify do + expect { described_class.trace { entry.fetch(:code)[] } } + .not_to raise_error + end + end + end + end + + context 'with impure code' do + table = { + Kernel: { + abort: [ + { + name: 'in implicit manner', + code: -> { abort } + }, + { + name: 'in explicit manner', + code: -> { Kernel.abort } + }, + { + name: 'via Object', + code: -> { Object.new.send(:abort) } + } + ], + at_exit: [ + { + name: 'in implicit manner', + code: -> { at_exit } + }, + { + name: 'in explicit manner', + code: -> { Kernel.at_exit } + }, + { + name: 'via Object', + code: -> { Object.new.send(:at_exit) } + } + ], + exit: [ + { + name: 'in implicit manner', + code: -> { exit } + }, + { + name: 'in explicit manner', + code: -> { Kernel.exit } + }, + { + name: 'via Object', + code: -> { Object.new.send(:exit) } + } + ], + exit!: [ + { + name: 'in implicit manner', + code: -> { exit! } + }, + { + name: 'in explicit manner', + code: -> { Kernel.exit! } + }, + { + name: 'via Object', + code: -> { Object.new.send(:exit!) } + } + ], + pp: [ + { + name: 'in implicit manner', + code: -> { pp :s } + }, + { + name: 'in explicit manner', + code: -> { Kernel.send(:pp, :s) } + }, + { + name: 'via Object', + code: -> { Object.new.send(:pp, :s) } + } + ], + gets: [ + { + name: 'in implicit manner', + code: -> { gets } + }, + { + name: 'in explicit manner', + code: -> { Kernel.gets } + }, + { + name: 'via Object', + code: -> { Object.new.send(:gets) } + } + ], + open: [ + { + name: 'in implicit manner', + code: -> { open 'bin/false' } + }, + { + name: 'in explicit manner', + code: -> { Kernel.open 'bin/false' } + }, + { + name: 'via Object', + code: -> { Object.new.send('open', 'bin/false') } + } + ], + p: [ + { + name: 'in implicit manner', + code: -> { p 1 } + }, + { + name: 'in explicit manner', + code: -> { Kernel.p 1 } + }, + { + name: 'via Object', + code: -> { Object.new.send('p', 1) } + } + ], + print: [ + { + name: 'in implicit manner', + code: -> { print } + }, + { + name: 'in explicit manner', + code: -> { Kernel.print } + }, + { + name: 'via Object', + code: -> { Object.new.send('print') } + } + ], + printf: [ + { + name: 'in implicit manner', + code: -> { printf } + }, + { + name: 'in explicit manner', + code: -> { Kernel.printf } + }, + { + name: 'via Object', + code: -> { Object.new.send('printf') } + } + ], + putc: [ + { + name: 'in implicit manner', + code: -> { putc } + }, + { + name: 'in explicit manner', + code: -> { Kernel.putc } + }, + { + name: 'via Object', + code: -> { Object.new.send('putc') } + } + ], + puts: [ + { + name: 'in implicit manner', + code: -> { puts } + }, + { + name: 'in explicit manner', + code: -> { Kernel.puts } + }, + { + name: 'via Object', + code: -> { Object.new.send('puts') } + } + ], + readline: [ + { + name: 'in implicit manner', + code: -> { readline } + }, + { + name: 'in explicit manner', + code: -> { Kernel.readline } + }, + { + name: 'via Object', + code: -> { Object.new.send('readline') } + } + ], + readlines: [ + { + name: 'in implicit manner', + code: -> { readlines } + }, + { + name: 'in explicit manner', + code: -> { Kernel.readlines } + }, + { + name: 'via Object', + code: -> { Object.new.send('readlines') } + } + ], + select: [ + { + name: 'in implicit manner', + code: -> { select } + }, + { + name: 'in explicit manner', + code: -> { Kernel.select } + }, + { + name: 'via Object', + code: -> { Object.new.send('select') } + } + ], + set_trace_func: [ + { + name: 'in implicit manner', + code: -> { set_trace_func } + }, + { + name: 'in explicit manner', + code: -> { Kernel.set_trace_func } + }, + { + name: 'via Object', + code: -> { Object.new.send('set_trace_func') } + } + ], + trace_var: [ + { + name: 'in implicit manner', + code: -> { trace_var } + }, + { + name: 'in explicit manner', + code: -> { Kernel.trace_var } + }, + { + name: 'via Object', + code: -> { Object.new.send('trace_var') } + } + ], + untrace_var: [ + { + name: 'in implicit manner', + code: -> { untrace_var } + }, + { + name: 'in explicit manner', + code: -> { Kernel.untrace_var } + }, + { + name: 'via Object', + code: -> { Object.new.send('untrace_var') } + } + ], + '``': [ + { + name: 'in implicit manner', + code: -> { `echo 1` } + }, + { + name: 'in explicit manner', + code: -> { Kernel.`'echo 1' } + }, + { + name: 'via Object', + code: -> { Object.new.send('`', 'echo 1') } + } + ], + exec: [ + { + name: 'in implicit manner', + code: -> { exec('/bin/bash') } + }, + { + name: 'in explicit manner', + code: -> { Kernel.exec('/bin/bash') } + }, + { + name: 'via Object', + code: -> { Object.new.send('exec', 'echo 1') } + } + ], + fork: [ + { + name: 'in implicit manner', + code: -> { exec('/bin/bash') } + }, + { + name: 'in explicit manner', + code: -> { Kernel.system('/bin/bash') } + }, + { + name: 'via Object', + code: -> { Object.new.send('`', 'echo 1') } + } + ], + spawn: [ + { + name: 'in implicit manner', + code: -> { spawn } + }, + { + name: 'in explicit manner', + code: -> { spawn } + }, + { + name: 'via Object', + code: -> { spawn } + } + ], + system: [ + { + name: 'in implicit manner', + code: -> { system('/bin/bash') } + }, + { + name: 'in explicit manner', + code: -> { Kernel.system('/bin/bash') } + }, + { + name: 'via Object', + code: -> { Object.new.send('system', 'echo 1') } + } + ], + # autoload: [ + # { + # name: "in implicit manner", + # code: -> { autoload(:B, "f") } + # }, + # { + # name: "in explicit manner", + # code: -> { autoload(:B, "f") } + # }, + # { + # name: "via Object", + # code: -> { autoload(:B, "f") } + # } + # ], + load: [ + { + name: 'in implicit manner', + code: -> { load } + }, + { + name: 'in explicit manner', + code: -> { Kernel.load } + }, + { + name: 'via Object', + code: -> { Object.new.send(:load) } + } + ], + require: [ + { + name: 'in implicit manner', + code: -> { require } + }, + { + name: 'in explicit manner', + code: -> { Kernel.require } + }, + { + name: 'via Object', + code: -> { Object.new.send(:require) } + } + ], + require_relative: [ + { + name: 'in implicit manner', + code: -> { require_relative 'f' } + }, + { + name: 'in explicit manner', + code: -> { Kernel.require_relative 'f' } + }, + { + name: 'via Object', + code: -> { Object.new.send(:require_relative, 'f') } + } + ], + rand: [ + { + name: 'in implicit manner', + code: -> { rand } + }, + { + name: 'in explicit manner', + code: -> { Kernel.rand } + }, + { + name: 'via Object', + code: -> { Object.new.send(:rand) } + } + ], + srand: [ + { + name: 'in implicit manner', + code: -> { srand } + }, + { + name: 'in explicit manner', + code: -> { Kernel.srand } + }, + { + name: 'via Object', + code: -> { Object.new.send(:srand) } + } + ], + sleep: [ + { + name: 'in implicit manner', + code: -> { sleep } + }, + { + name: 'in explicit manner', + code: -> { Kernel.sleep } + }, + { + name: 'via Object', + code: -> { Object.new.send(:sleep) } + } + ], + sprintf: [ + { + name: 'in implicit manner', + code: -> { sprintf } + }, + { + name: 'in explicit manner', + code: -> { Kernel.sprintf } + }, + { + name: 'via Object', + code: -> { Object.new.send(:sprintf) } + } + ], + syscall: [ + { + name: 'in implicit manner', + code: -> { syscall } + }, + { + name: 'in explicit manner', + code: -> { Kernel.syscall } + }, + { + name: 'via Object', + code: -> { Object.new.send(:syscall) } + } + ], + trap: [ + { + name: 'in implicit manner', + code: -> { trap } + }, + { + name: 'in explicit manner', + code: -> { Kernel.trap } + }, + { + name: 'via Object', + code: -> { Object.new.send(:trap) } + } + ], + warn: [ + { + name: 'in implicit manner', + code: -> { warn } + }, + { + name: 'in explicit manner', + code: -> { Kernel.warn } + }, + { + name: 'via Object', + code: -> { Object.new.send(:warn) } + } + ] + }, + IO: { + binread: [ + { + name: 'in implicit manner', + code: -> { IO.binread '/dev/null' } # rubocop:disable Security/IoMethods + } + ] + }, + Random: { + bytes: [ + { + name: 'in implicit manner', + code: -> { Random.bytes 1 } + }, + { + name: 'in explicit manner', + code: -> { Random.new.bytes 1 } + } + ], + rand: [ + { + name: 'in implicit manner', + code: -> { Random.rand } + }, + { + name: 'in explicit manner', + code: -> { Random.new.rand } + } + ], + srand: [ + { + name: 'in implicit manner', + code: -> { Random.srand } + }, + { + name: 'in explicit manner', + code: -> { Random.new.send(:srand) } + } + ], + urandom: [ + { + name: 'in implicit manner', + code: -> { Random.urandom } + } + ] + }, + SecureRandom: { + bytes: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.bytes 42 } + } + ], + gen_random: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.gen_random 1 } + } + ], + alphanumeric: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.alphanumeric } + } + ], + base64: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.base64 } + } + ], + choose: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:choose, (1..10), 2) } + } + ], + hex: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:hex) } + } + ], + rand: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:rand) } + } + ], + random_bytes: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:random_bytes) } + } + ], + random_number: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:random_number) } + } + ], + urlsafe_base64: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:urlsafe_base64) } + } + ], + uuid: [ + { + name: 'in implicit manner', + code: -> { SecureRandom.send(:uuid) } + } + ] + } + } + + table.each do |module_name, methods| + methods.each do |method_id, examples| + context "with `#{module_name}.#{method_id}` method" do + examples.each do |entry| + context entry.fetch(:name) do + specify do + expect { described_class.trace { entry.fetch(:code)[] } } + .to raise_error(described_class::Errors::PurityViolationError) + end + end + end + end + end + end + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..6b58b95 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require 'simplecov' +SimpleCov.start do + enable_coverage :branch + enable_coverage_for_eval +end + +require 'purist' +require 'purist/integrations/rspec' + +require 'rspec/matchers/fail_matchers' +require 'rspec/its' + +RSpec.configure do |config| + config.example_status_persistence_file_path = '.rspec_status' + + config.raise_errors_for_deprecations! + + config.disable_monkey_patching! + + config.include RSpec::Matchers::FailMatchers + config.include Purist::Integrations::RSpec::Matchers + + config.expect_with :rspec do |c| + c.syntax = :expect + end +end