diff --git a/.rubocop.yml b/.rubocop.yml index bd23d84..4aa0b2c 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,6 +1,16 @@ +inherit_from: .rubocop_todo.yml + +inherit_mode: + merge: + - Exclude + - Include + +inherit_gem: + rubocop-gusto: + - config/default.yml + plugins: - - rubocop-sorbet - - rubocop-performance + - rubocop-gusto AllCops: TargetRubyVersion: 3.3 @@ -10,7 +20,7 @@ AllCops: - bin/**/* - vendor/**/* -Sorbet/StrictSigil: +Gemspec/RequireMFA: Enabled: false Layout/ExtraSpacing: @@ -18,70 +28,77 @@ Layout/ExtraSpacing: Exclude: - danger-packwerk.gemspec +Layout/LineLength: + Enabled: false + Layout/SpaceAroundOperators: Enabled: true Exclude: - danger-packwerk.gemspec -Sorbet/ValidSigil: - Enabled: true - -Gemspec/RequireMFA: +Lint/UnusedMethodArgument: Enabled: false -Layout/LineLength: +Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false -Style/Documentation: +Metrics/ClassLength: Enabled: false -Style/SignalException: +Metrics/CyclomaticComplexity: Enabled: false -Style/MultilineBlockChain: +Metrics/MethodLength: Enabled: false -Metrics/MethodLength: +Metrics/ModuleLength: Enabled: false -Metrics/CyclomaticComplexity: +Metrics/ParameterLists: Enabled: false -Metrics/ModuleLength: +Metrics/PerceivedComplexity: Enabled: false -Metrics/ClassLength: +Naming/BlockForwarding: Enabled: false +RSpec/NotToNot: + Enabled: true + Sorbet/FalseSigil: Enabled: false -Lint/UnusedMethodArgument: +Sorbet/StrictSigil: Enabled: false -Metrics/AbcSize: - Enabled: false +Sorbet/ValidSigil: + Enabled: true -Style/GuardClause: +Style/ArgumentsForwarding: Enabled: false -Style/NumericPredicate: +Style/Documentation: Enabled: false -Metrics/PerceivedComplexity: +Style/GuardClause: Enabled: false -Metrics/ParameterLists: +Style/MultilineBlockChain: Enabled: false -Style/SuperArguments: +Style/NumericPredicate: Enabled: false -Style/ArgumentsForwarding: +Style/SignalException: Enabled: false -Naming/BlockForwarding: +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes + +Style/SuperArguments: Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..2b166c8 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,75 @@ +# This configuration was generated by +# `rubocop --auto-gen-config --exclude-limit 10000` +# on 2026-11-30 21:06:52 UTC using RuboCop version 1.92.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +Gusto/DescribedClassConstantReference: + Exclude: + - 'spec/query_packwerk/reference_spec.rb' + +# Offense count: 12 +Gusto/NoMetaprogramming: + Exclude: + - 'lib/query_packwerk/query_interface.rb' + - 'spec/query_packwerk/file_cache_spec.rb' + - 'spec/query_packwerk/pks_spec.rb' + - 'spec/query_packwerk/query_interface_spec.rb' + - 'spec/query_packwerk/reference_spec.rb' + +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +Gusto/RegexpBypass: + Exclude: + - 'lib/query_packwerk/constant_use.rb' + - 'lib/query_packwerk/pks.rb' + +# Offense count: 7 +# Configuration parameters: Prefixes, AllowedPatterns. +# Prefixes: when, with, without +RSpec/ContextWording: + Exclude: + - 'spec/query_packwerk/rule_rewriter_spec.rb' + - 'spec/support/pseudo_packs.rb' + - 'spec/support/referenced_packs.rb' + +# Offense count: 3 +RSpec/MultipleDescribes: + Exclude: + - 'spec/query_packwerk/package_spec.rb' + - 'spec/query_packwerk/violations_spec.rb' + - 'spec/query_packwerk_spec.rb' + +# Offense count: 2 +RSpec/RepeatedDescription: + Exclude: + - 'spec/query_packwerk/file_cache_spec.rb' + +# Offense count: 6 +RSpec/RepeatedExampleGroupDescription: + Exclude: + - 'spec/query_packwerk/package_spec.rb' + - 'spec/query_packwerk/violations_spec.rb' + - 'spec/query_packwerk_spec.rb' + +# Offense count: 6 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AutocorrectToRBS. +Sorbet/ForbidTUnsafe: + Exclude: + - 'lib/query_packwerk/constant_use.rb' + - 'lib/query_packwerk/constant_uses.rb' + - 'lib/query_packwerk/package.rb' + - 'lib/query_packwerk/query_interface.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle, Autocorrect. +# SupportedStyles: module_function, extend_self, forbidden +Style/ModuleFunction: + Exclude: + - 'lib/query_packwerk.rb' diff --git a/Gemfile b/Gemfile index 3924075..608e5c7 100644 --- a/Gemfile +++ b/Gemfile @@ -1,24 +1,25 @@ # frozen_string_literal: true -source 'https://rubygems.org' +source "https://rubygems.org" # Specify your gem's dependencies in query_packwerk.gemspec gemspec -gem 'irb' -gem 'pry' +gem "irb" +gem "pry" -gem 'packs-specification' +gem "packs-specification" -gem 'rake', '~> 13.4' -gem 'rspec', '~> 3.13' +gem "rake", "~> 13.4" +gem "rspec", "~> 3.13" -gem 'rubocop', '~> 1.92' -gem 'rubocop-performance', '~> 1.27' -gem 'rubocop-sorbet', '~> 0.17' +gem "rubocop", "~> 1.92" +gem "rubocop-gusto", require: false +gem "rubocop-performance", "~> 1.27" +gem "rubocop-sorbet", "~> 0.17" -gem 'sorbet' -gem 'tapioca' +gem "sorbet" +gem "tapioca" # Unreleased fix for parsing `...` params (Shopify/rbi#625), needed by tapioca's RBS rewriter on herb 0.11 -gem 'rbi', github: 'Shopify/rbi' +gem "rbi", github: "Shopify/rbi" diff --git a/Gemfile.lock b/Gemfile.lock index 93a8290..1f48329 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -52,6 +52,8 @@ GEM smart_properties bigdecimal (4.1.3) builder (3.3.0) + code_teams (1.3.1) + sorbet-runtime coderay (1.1.3) concurrent-ruby (1.3.8) connection_pool (3.0.2) @@ -178,10 +180,26 @@ GEM rubocop-ast (1.50.0) parser (>= 3.3.7.2) prism (~> 1.7) + rubocop-gusto (11.12.0) + code_teams + lint_roller + rubocop (>= 1.76) + rubocop-performance + rubocop-rake + rubocop-rspec + rubocop-sorbet (>= 0.13.0) + smart_todo + thor rubocop-performance (1.27.0) lint_roller (~> 1.1) rubocop (>= 1.89.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rake (0.7.1) + lint_roller (~> 1.1) + rubocop (>= 1.72.1) + rubocop-rspec (3.11.0) + lint_roller (~> 1.1) + rubocop (~> 1.92) rubocop-sorbet (0.17.2) rbi (~> 0.4, >= 0.4.3) rbs (>= 4.1.1) @@ -193,6 +211,8 @@ GEM rubydex (0.4.1-x86_64-linux) securerandom (0.4.1) smart_properties (1.17.0) + smart_todo (1.11.0) + prism (~> 1.0) sorbet (0.6.13593) sorbet-static (= 0.6.13593) sorbet-runtime (0.6.13593) @@ -252,6 +272,7 @@ DEPENDENCIES rbi! rspec (~> 3.13) rubocop (~> 1.92) + rubocop-gusto rubocop-performance (~> 1.27) rubocop-sorbet (~> 0.17) sorbet diff --git a/Rakefile b/Rakefile index 4964751..9a7fd8d 100644 --- a/Rakefile +++ b/Rakefile @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'bundler/gem_tasks' -require 'rspec/core/rake_task' +require "bundler/gem_tasks" +require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) -require 'rubocop/rake_task' +require "rubocop/rake_task" RuboCop::RakeTask.new -task default: %i[spec rubocop] +task default: %i(spec rubocop) diff --git a/exe/query_packwerk b/exe/query_packwerk index e22310d..1908737 100755 --- a/exe/query_packwerk +++ b/exe/query_packwerk @@ -1,7 +1,7 @@ #!/usr/bin/env ruby # frozen_string_literal: true -require 'query_packwerk' -require 'query_packwerk/cli' +require "query_packwerk" +require "query_packwerk/cli" QueryPackwerk::CLI.start diff --git a/lib/query_packwerk.rb b/lib/query_packwerk.rb index d94eade..12ba54c 100644 --- a/lib/query_packwerk.rb +++ b/lib/query_packwerk.rb @@ -1,10 +1,10 @@ # typed: strict # frozen_string_literal: true -require 'sorbet-runtime' -require 'herb' -require 'parse_packwerk' -require 'rubocop' +require "sorbet-runtime" +require "herb" +require "parse_packwerk" +require "rubocop" # QueryPackwerk is a tool for querying Packwerk violations. # @@ -14,21 +14,21 @@ # # See also: https://github.com/rubyatscale/parse_packwerk module QueryPackwerk - autoload :Console, 'query_packwerk/console' - autoload :ConsoleHelpers, 'query_packwerk/console_helpers' - autoload :QueryInterface, 'query_packwerk/query_interface' - autoload :ConstantUse, 'query_packwerk/constant_use' - autoload :ConstantUses, 'query_packwerk/constant_uses' - autoload :Violations, 'query_packwerk/violations' - autoload :Violation, 'query_packwerk/violation' - autoload :References, 'query_packwerk/references' - autoload :Reference, 'query_packwerk/reference' - autoload :Pks, 'query_packwerk/pks' - autoload :Packages, 'query_packwerk/packages' - autoload :Package, 'query_packwerk/package' - autoload :RuleRewriter, 'query_packwerk/rule_rewriter' - autoload :FileCache, 'query_packwerk/file_cache' - autoload :Version, 'query_packwerk/version' + autoload :Console, "query_packwerk/console" + autoload :ConsoleHelpers, "query_packwerk/console_helpers" + autoload :QueryInterface, "query_packwerk/query_interface" + autoload :ConstantUse, "query_packwerk/constant_use" + autoload :ConstantUses, "query_packwerk/constant_uses" + autoload :Violations, "query_packwerk/violations" + autoload :Violation, "query_packwerk/violation" + autoload :References, "query_packwerk/references" + autoload :Reference, "query_packwerk/reference" + autoload :Pks, "query_packwerk/pks" + autoload :Packages, "query_packwerk/packages" + autoload :Package, "query_packwerk/package" + autoload :RuleRewriter, "query_packwerk/rule_rewriter" + autoload :FileCache, "query_packwerk/file_cache" + autoload :Version, "query_packwerk/version" extend T::Sig @@ -62,7 +62,7 @@ def violation_sources_for(pack_name) # Get how often the violations occurred sig { params(pack_name: String, threshold: Integer).returns(T::Hash[String, T::Hash[String, Integer]]) } def violation_counts_for(pack_name, threshold: 0) - violations_for(pack_name).source_counts(threshold: threshold) + violations_for(pack_name).source_counts(threshold:) end # Get the 'shape' of all violations (how other packages access this package) @@ -74,13 +74,13 @@ def anonymous_violation_sources_for(pack_name) # Get how often each 'shape' of violation occurs (counts of how other packages access this package) sig { params(pack_name: String, threshold: Integer).returns(T::Hash[String, T::Hash[String, Integer]]) } def anonymous_violation_counts_for(pack_name, threshold: 0) - violations_for(pack_name).anonymous_source_counts(threshold: threshold) + violations_for(pack_name).anonymous_source_counts(threshold:) end # Get which packages consume code from this package (who depends on this package) sig { params(pack_name: String, threshold: Integer).returns(T::Hash[String, Integer]) } def consumers(pack_name, threshold: 0) - violations_for(pack_name).consumers(threshold: threshold) + violations_for(pack_name).consumers(threshold:) end # Get all references from other packages to this package's constants, whether diff --git a/lib/query_packwerk/cli.rb b/lib/query_packwerk/cli.rb index c8ced75..9624ba7 100644 --- a/lib/query_packwerk/cli.rb +++ b/lib/query_packwerk/cli.rb @@ -1,7 +1,7 @@ # typed: strict # frozen_string_literal: true -require 'thor' +require "thor" module QueryPackwerk # CLI for loading the QueryPackwerk console @@ -9,7 +9,7 @@ class CLI < Thor extend T::Sig # Thor maps --help to its help command only as the first argument, so commands check options[:help]. - class_option :help, type: :boolean, aliases: '-h', desc: 'Show this help message' + class_option :help, type: :boolean, aliases: "-h", desc: "Show this help message" check_unknown_options! default_command :console @@ -19,11 +19,11 @@ def self.exit_on_failure? true end - desc 'console [DIRECTORY]', 'Query packwerk in DIRECTORY via console' - long_desc 'Query packwerk in DIRECTORY via console. DIRECTORY defaults to the current directory.' + desc "console [DIRECTORY]", "Query packwerk in DIRECTORY via console" + long_desc "Query packwerk in DIRECTORY via console. DIRECTORY defaults to the current directory." sig { params(directory: String).void } def console(directory = Dir.pwd) - return help('console') if options[:help] + return help("console") if options[:help] raise Thor::Error, "Could not find directory #{directory.inspect}." unless File.directory?(directory) QueryPackwerk::Console.start(directory) diff --git a/lib/query_packwerk/console.rb b/lib/query_packwerk/console.rb index 0b4bd64..d1e8e6c 100644 --- a/lib/query_packwerk/console.rb +++ b/lib/query_packwerk/console.rb @@ -1,8 +1,8 @@ # typed: strict # frozen_string_literal: true -require 'irb' -require 'irb/completion' +require "irb" +require "irb/completion" module QueryPackwerk # Console for QueryPackwerk @@ -18,23 +18,23 @@ def self.start(directory = Dir.pwd) # https://github.com/cucumber/aruba/blob/main/lib/aruba/console.rb ARGV.clear - require 'irb' + require "irb" IRB.setup nil - IRB.conf[:IRB_NAME] = 'query_packwerk' + IRB.conf[:IRB_NAME] = "query_packwerk" IRB.conf[:PROMPT] = {} IRB.conf[:PROMPT][:QUERY_PACKWERK] = { - PROMPT_I: '%N:%03n:%i> ', - PROMPT_S: '%N:%03n:%i%l ', - PROMPT_C: '%N:%03n:%i* ', - RETURN: "# => %s\n" + PROMPT_I: "%N:%03n:%i> ", + PROMPT_S: "%N:%03n:%i%l ", + PROMPT_C: "%N:%03n:%i* ", + RETURN: "# => %s\n", } IRB.conf[:PROMPT_MODE] = :QUERY_PACKWERK IRB.conf[:RC] = false - require 'irb/completion' + require "irb/completion" IRB.conf[:READLINE] = true IRB.conf[:SAVE_HISTORY] = 1000 IRB.conf[:HISTORY_FILE] = "#{directory}/.query_packwerk_history" @@ -51,7 +51,7 @@ def self.start(directory = Dir.pwd) context_instance.welcome - trap('SIGINT') do + trap("SIGINT") do irb.signal_handle end diff --git a/lib/query_packwerk/console_helpers.rb b/lib/query_packwerk/console_helpers.rb index 164c243..9665cfc 100644 --- a/lib/query_packwerk/console_helpers.rb +++ b/lib/query_packwerk/console_helpers.rb @@ -8,7 +8,7 @@ module ConsoleHelpers sig { returns(String) } def inspect - 'query_packwerk console' + "query_packwerk console" end sig { returns(NilClass) } # returning nil is less ugly in the console. @@ -21,19 +21,19 @@ def welcome sig { params(type: T.nilable(T.any(String, Symbol))).returns(NilClass) } def help(type = nil) case type.to_s.downcase - when 'violation' + when "violation" help_violation - when 'violations' + when "violations" help_violations - when 'reference' + when "reference" help_reference - when 'references' + when "references" help_references - when 'package' + when "package" help_package - when 'packages' + when "packages" help_packages - when '', 'help' + when "", "help" help_help else puts "Unknown help topic: #{type}\n" diff --git a/lib/query_packwerk/constant_use.rb b/lib/query_packwerk/constant_use.rb index afc6b3f..d16e3de 100644 --- a/lib/query_packwerk/constant_use.rb +++ b/lib/query_packwerk/constant_use.rb @@ -13,27 +13,33 @@ class ConstantUse abstract! ALL_CAPS = /\A[A-Z_]+\z/ - RUNTIME_KEYS = %i[is_active_record is_constant].freeze + RUNTIME_KEYS = %i(is_active_record is_constant).freeze sig { abstract.returns(String) } - def class_name; end + def class_name + end sig { abstract.returns(T::Array[String]) } - def files; end + def files + end sig { abstract.returns(QueryPackwerk::Package) } - def producing_pack; end + def producing_pack + end sig { abstract.returns(QueryPackwerk::Package) } - def consuming_pack; end + def consuming_pack + end # The sources in one of the files, with the calls chained on each sig { abstract.params(file_name: String).returns(T::Array[RuboCop::AST::Node]) } - def full_sources_in(file_name); end + def full_sources_in(file_name) + end # The keys that where and pattern matching can ask for, with how to read each sig { abstract.returns(T::Hash[Symbol, T.proc.params(arg0: T.untyped).returns(T.untyped)]) } - def query_keys; end + def query_keys + end sig { params(file_cache: QueryPackwerk::FileCache).void } def initialize(file_cache:) @@ -45,7 +51,7 @@ def initialize(file_cache:) def load_cache!(headers: false) return true if @cache_loaded - @file_cache.load!(*T.unsafe(files), headers: headers) + @file_cache.load!(*T.unsafe(files), headers:) @cache_loaded = true end @@ -148,7 +154,7 @@ def sources_with_contexts(start_offset: 3, end_offset: 3) location = "#{file_name}:#{s.loc.line} (L#{start_pos}..#{end_pos})" context = lines[(start_pos - 1)...end_pos] - full_context = unindent((context || ['']).join) + full_context = unindent((context || [""]).join) [@file_cache.anonymize_arguments(s.source), "> #{location}\n\n#{full_context}"] end @@ -220,7 +226,7 @@ def runtime_keys(keys) value = @file_cache.set( :is_constant, key: class_name, - value: class_name.split('::').last&.match?(ALL_CAPS) + value: class_name.split("::").last&.match?(ALL_CAPS) ) runtime_values[:is_constant] = value @@ -235,7 +241,7 @@ def runtime_keys(keys) def unindent(string) # Multi-line match, this is intentional min_space = string.scan(/^\s*/).min_by(&:length) - string.gsub(/^#{min_space}/, '') + string.gsub(/^#{min_space}/, "") end end end diff --git a/lib/query_packwerk/constant_uses.rb b/lib/query_packwerk/constant_uses.rb index 19c7b15..c9891c9 100644 --- a/lib/query_packwerk/constant_uses.rb +++ b/lib/query_packwerk/constant_uses.rb @@ -1,7 +1,7 @@ # typed: strict # frozen_string_literal: true -require 'coderay' +require "coderay" module QueryPackwerk # The base of Violations and References, which are collections of ConstantUse @@ -41,7 +41,7 @@ def where(**query_params, &query_fn) sig { params(name: T.untyped).returns(T.untyped) } def qualify(name) case name - when String then name.start_with?('::') ? name : "::#{name}" + when String then name.start_with?("::") ? name : "::#{name}" when Array then name.map { |each_name| qualify(each_name) } else name end @@ -82,7 +82,7 @@ def load_cache! @original_collection.each(&:load_cache!) finish_time = Time.now - start_time - warn '', "AST cache loaded in #{finish_time}" + warn "", "AST cache loaded in #{finish_time}" @cache_loaded = true end @@ -192,14 +192,14 @@ def sources_with_contexts(start_offset: 3, end_offset: 3) sig { params(start_offset: Integer, end_offset: Integer).returns(String) } def sources_with_contexts_report(start_offset: 3, end_offset: 3) contexts = sources_with_contexts(start_offset:, end_offset:) - output = +'' + output = +"" contexts.each do |violated_constant, anonymized_sources| - heavy_underline = '=' * violated_constant.size + heavy_underline = "=" * violated_constant.size output << "#{violated_constant}\n#{heavy_underline}\n\n" anonymized_sources.each do |anonymized_source, full_contexts| - light_underline = '-' * anonymized_source.size + light_underline = "-" * anonymized_source.size output << "#{anonymized_source}\n#{light_underline}\n\n" full_contexts.each do |context| diff --git a/lib/query_packwerk/file_cache.rb b/lib/query_packwerk/file_cache.rb index e0f9394..83fb3c2 100644 --- a/lib/query_packwerk/file_cache.rb +++ b/lib/query_packwerk/file_cache.rb @@ -45,10 +45,10 @@ def load!(*file_names, headers: true) next if @file_ast_cache.key?(f) get_file_ast(f) - $stderr.print '.' + $stderr.print "." end - warn '', 'AST cache loaded' if headers + warn "", "AST cache loaded" if headers end sig { params(cache_name: Symbol, key: T.untyped, value: T.untyped).returns(T.untyped) } @@ -73,17 +73,13 @@ def get_file_ast(file_name) # The AST is also nil for source with no code, like a template that's only HTML. # `nil` stands in, as it has no constant or call that a reference's position could match. - source.ast || ast_from('nil') + source.ast || ast_from("nil") end end sig { params(file_name: String).returns(String) } def get_file(file_name) - @file_cache[file_name] ||= if (RUBY_FILE.match?(file_name) || ERB_FILE.match?(file_name)) && File.exist?(file_name) - File.read(file_name) - else - '' - end + @file_cache[file_name] ||= read_file(file_name) end # Get all occurrences of the violation's constant in a file @@ -94,7 +90,7 @@ def get_all_const_occurrences(file_name:, class_name:) return T.must(@file_const_cache[const_key]) if @file_const_cache.key?(const_key) absolute_const_node = ast_from(class_name) - relative_const_node = ast_from(class_name.delete_prefix('::')) + relative_const_node = ast_from(class_name.delete_prefix("::")) @file_const_cache[const_key] = get_file_ast(file_name).each_node.select do |node| # Not the `Foo` in `Foo::Bar`, which packwerk and pks count only as a use of `Foo::Bar` @@ -112,8 +108,8 @@ def get_full_sources(file_name:, class_name:) return T.must(@full_source_cache[const_key]) if @full_source_cache.key?(const_key) @full_source_cache[const_key] = get_all_const_occurrences( - file_name: file_name, - class_name: class_name + file_name:, + class_name: ).map do |node| get_full_receiver_chain(node) end @@ -143,8 +139,8 @@ def get_full_source_at(file_name:, line:, column:) sig { params(source: String).returns(String) } def anonymize_arguments(source) @anonymized_args_cache[source] ||= RuleRewriter - .rewrite(source) - .delete("\n").squeeze(' ').delete_prefix('::') + .rewrite(source) + .delete("\n").squeeze(" ").delete_prefix("::") end private @@ -155,6 +151,15 @@ def nodes_by_line(file_name) @line_cache[file_name] ||= get_file_ast(file_name).each_node(:const, :send).group_by { |node| node.loc.line } end + sig { params(file_name: String).returns(String) } + def read_file(file_name) + if (RUBY_FILE.match?(file_name) || ERB_FILE.match?(file_name)) && File.exist?(file_name) + File.read(file_name) + else + "" + end + end + # Blanks out everything in an ERB template except its Ruby code, so line numbers still match the template sig { params(file_name: String).returns(String) } def ruby_source(file_name) diff --git a/lib/query_packwerk/package.rb b/lib/query_packwerk/package.rb index 5b20d09..16cb1a2 100644 --- a/lib/query_packwerk/package.rb +++ b/lib/query_packwerk/package.rb @@ -55,7 +55,7 @@ def dependency_names sig { returns(String) } def owner - config['owner'] || Packages::UNOWNED + config["owner"] || Packages::UNOWNED end sig { returns(Pathname) } @@ -70,7 +70,7 @@ def directory def todos QueryPackwerk::Violations.where(consuming_pack: name) end - alias outgoing_violations todos + alias_method :outgoing_violations, :todos # Returns violations where this package is the producer (i.e., other packages # depend on this package). These are violations where other packages are @@ -79,7 +79,7 @@ def todos def violations QueryPackwerk::Violations.where(producing_pack: name) end - alias incoming_violations violations + alias_method :incoming_violations, :violations # Returns references from other packages to this package's constants, # whether or not they break the packages' rules. These come from pks. @@ -125,13 +125,13 @@ def parent_name end def deconstruct_keys(keys) all_values = { - name: name, - owner: owner, + name:, + owner:, owned: owner != Packages::UNOWNED, dependencies: dependency_names, # Used for future implementations of NestedPacks - parent_name: parent_name + parent_name:, } keys.nil? ? all_values : all_values.slice(*T.unsafe(keys)) diff --git a/lib/query_packwerk/packages.rb b/lib/query_packwerk/packages.rb index 7f9299a..87e52ce 100644 --- a/lib/query_packwerk/packages.rb +++ b/lib/query_packwerk/packages.rb @@ -12,7 +12,7 @@ class Packages Elem = type_member { { fixed: QueryPackwerk::Package } } - UNOWNED = 'Unowned' + UNOWNED = "Unowned" include Enumerable include QueryInterface diff --git a/lib/query_packwerk/pks.rb b/lib/query_packwerk/pks.rb index 41c8ebb..6db7c99 100644 --- a/lib/query_packwerk/pks.rb +++ b/lib/query_packwerk/pks.rb @@ -1,8 +1,8 @@ # typed: strict # frozen_string_literal: true -require 'json' -require 'open3' +require "json" +require "open3" module QueryPackwerk # Runs pks (https://github.com/rubyatscale/pks), which lists every reference @@ -14,8 +14,8 @@ module Pks class Error < StandardError; end # The first version with `list-references` - MINIMUM_VERSION = Gem::Version.new('0.7.0') - INSTALLATION_URL = 'https://github.com/rubyatscale/pks/blob/main/INSTALLATION.md' + MINIMUM_VERSION = Gem::Version.new("0.7.0") + INSTALLATION_URL = "https://github.com/rubyatscale/pks/blob/main/INSTALLATION.md" class << self extend T::Sig @@ -25,13 +25,13 @@ class << self sig { returns(T::Array[T::Hash[String, T.untyped]]) } def list_references pks = executable - stdout, stderr, status = Open3.capture3(pks, 'list-references') + stdout, stderr, status = Open3.capture3(pks, "list-references") raise Error, "`#{pks} list-references` failed:\n#{stderr}" unless status.success? # Warnings, as about a file that pks can't parse $stderr.print(stderr) # pks prints UTF-8, whatever the locale. Freezing shares the strings of each file and constant. - JSON.parse(stdout.force_encoding(Encoding::UTF_8), freeze: true).fetch('references') + JSON.parse(stdout.force_encoding(Encoding::UTF_8), freeze: true).fetch("references") end # bin/pks, as in an app that pins a version of pks, or else pks on the PATH @@ -39,10 +39,10 @@ def list_references def executable # A DotSlash file saved from a release isn't executable at first. Running # pks on the PATH instead would ignore the version the app pins. - raise Error, "bin/pks isn't executable. To run it, `chmod +x bin/pks`" if File.file?('bin/pks') && !File.executable?('bin/pks') + raise Error, "bin/pks isn't executable. To run it, `chmod +x bin/pks`" if File.file?("bin/pks") && !File.executable?("bin/pks") - candidates = ['bin', *ENV.fetch('PATH', '').split(File::PATH_SEPARATOR)].map do |directory| - File.expand_path('pks', directory) + candidates = ["bin", *ENV.fetch("PATH", "").split(File::PATH_SEPARATOR)].map do |directory| + File.expand_path("pks", directory) end executable = candidates.find { |candidate| File.file?(candidate) && File.executable?(candidate) } unless executable @@ -60,7 +60,7 @@ def executable sig { params(executable: String).void } def check_version(executable) # Only stdout, as a wrapper may warn on stderr first - stdout, stderr, status = Open3.capture3(executable, '--version') + stdout, stderr, status = Open3.capture3(executable, "--version") version = stdout[/^pks (\S+)/, 1] raise Error, "Could not get the version of #{executable}:\n#{stdout}#{stderr}" unless status.success? && version && Gem::Version.correct?(version) diff --git a/lib/query_packwerk/query_interface.rb b/lib/query_packwerk/query_interface.rb index 0853267..adf5a62 100644 --- a/lib/query_packwerk/query_interface.rb +++ b/lib/query_packwerk/query_interface.rb @@ -47,7 +47,7 @@ def size original_collection.size end - alias length size + alias_method :length, :size # Not an alias of size, so that an item or a block counts what it matches, as in Enumerable sig do @@ -207,7 +207,7 @@ def deep_merge_counts(collection, threshold: 0, &_blk) new_nested_counts[key].merge!(values) { |_k, a, b| a + b } end - threshold_drop(nested_counts, threshold: threshold) + threshold_drop(nested_counts, threshold:) end sig do @@ -267,7 +267,7 @@ def deep_merge_hash_groups(collection, &_blk) end def threshold_drop(hash, threshold: 0) hash - .transform_values { |vs| threshold_filter_sort(vs, threshold: threshold) } + .transform_values { |vs| threshold_filter_sort(vs, threshold:) } .reject { |_k, vs| vs.empty? } end diff --git a/lib/query_packwerk/reference.rb b/lib/query_packwerk/reference.rb index 1767c1b..5e46a63 100644 --- a/lib/query_packwerk/reference.rb +++ b/lib/query_packwerk/reference.rb @@ -80,7 +80,7 @@ def initialize( def class_name @constant_name end - alias constant_name class_name + alias_method :constant_name, :class_name sig { override.returns(T::Array[String]) } def files @@ -117,37 +117,37 @@ def location def full_sources_in(file_name) line = @line column = @column - return @file_cache.get_full_sources(file_name: file_name, class_name: class_name) unless line && column + return @file_cache.get_full_sources(file_name:, class_name:) unless line && column - [@file_cache.get_full_source_at(file_name: file_name, line: line, column: column)].compact + [@file_cache.get_full_source_at(file_name:, line:, column:)].compact end QUERY_KEYS = T.let( { constant_name: lambda(&:class_name), - pack_name: ->(reference) { reference.producing_pack.name }, + pack_name: -> (reference) { reference.producing_pack.name }, file: lambda(&:file), # Which of the packs' rules the reference breaks, if any allowed: lambda(&:allowed?), violation_types: lambda(&:violation_types), - privacy: ->(reference) { reference.violation_types.include?('privacy') }, - dependency: ->(reference) { reference.violation_types.include?('dependency') }, + privacy: -> (reference) { reference.violation_types.include?("privacy") }, + dependency: -> (reference) { reference.violation_types.include?("dependency") }, # Which of those no package_todo.yml records - unrecorded: ->(reference) { reference.unrecorded_violation_types.any? }, + unrecorded: -> (reference) { reference.unrecorded_violation_types.any? }, unrecorded_violation_types: lambda(&:unrecorded_violation_types), # Which pack defines the constant, and which pack's code uses it - consuming_pack: ->(reference) { reference.consuming_pack.name }, - producing_pack: ->(reference) { reference.producing_pack.name }, + consuming_pack: -> (reference) { reference.consuming_pack.name }, + producing_pack: -> (reference) { reference.producing_pack.name }, - producing_owner: ->(reference) { reference.producing_pack.owner }, - consuming_owner: ->(reference) { reference.consuming_pack.owner }, + producing_owner: -> (reference) { reference.producing_pack.owner }, + consuming_owner: -> (reference) { reference.consuming_pack.owner }, # As for violations, "owner" is the producing pack's - owner: ->(reference) { reference.producing_pack.owner }, - owned: ->(reference) { reference.producing_pack.owner != Packages::UNOWNED } + owner: -> (reference) { reference.producing_pack.owner }, + owned: -> (reference) { reference.producing_pack.owner != Packages::UNOWNED }, }.freeze, T::Hash[Symbol, T.proc.params(arg0: QueryPackwerk::Reference).returns(T.untyped)] ) @@ -159,7 +159,7 @@ def query_keys sig { returns(String) } def inspect - rules = allowed? ? 'allowed' : violation_types.join(', ') + rules = allowed? ? "allowed" : violation_types.join(", ") "#<#{self.class.name} #{consuming_pack.name} -> #{class_name} (#{rules}) at #{location}>" end end diff --git a/lib/query_packwerk/references.rb b/lib/query_packwerk/references.rb index 89cad3a..f103ef7 100644 --- a/lib/query_packwerk/references.rb +++ b/lib/query_packwerk/references.rb @@ -24,28 +24,28 @@ def all file_cache = QueryPackwerk::FileCache.new packages = T.let({}, T::Hash[String, QueryPackwerk::Package]) - pack = ->(name) { packages[name] ||= package(name) } + pack = -> (name) { packages[name] ||= package(name) } references = Pks.list_references.map do |reference| QueryPackwerk::Reference.new( - constant_name: reference.fetch('constant_name'), - file: reference.fetch('file'), - line: reference.fetch('line'), - column: reference.fetch('column'), - producing_pack: pack.call(reference.fetch('defining_pack_name')), - consuming_pack: pack.call(reference.fetch('referencing_pack_name')), - violations: reference.fetch('violations').map do |violation| + constant_name: reference.fetch("constant_name"), + file: reference.fetch("file"), + line: reference.fetch("line"), + column: reference.fetch("column"), + producing_pack: pack.call(reference.fetch("defining_pack_name")), + consuming_pack: pack.call(reference.fetch("referencing_pack_name")), + violations: reference.fetch("violations").map do |violation| QueryPackwerk::Reference::Violation.new( - type: violation.fetch('violation_type'), - strict: violation.fetch('strict'), - recorded: violation.fetch('recorded') + type: violation.fetch("violation_type"), + strict: violation.fetch("strict"), + recorded: violation.fetch("recorded") ) end, - file_cache: file_cache + file_cache: ) end - @all = QueryPackwerk::References.new(references, file_cache: file_cache) + @all = QueryPackwerk::References.new(references, file_cache:) end # Wrap the interface `where` with this type @@ -75,7 +75,7 @@ def package(name) original_package = ParsePackwerk.find(name) || (ParsePackwerk::Package.from(yml) if yml.file?) raise Pks::Error, "pks lists references from or to #{name}, which has no package.yml" unless original_package - QueryPackwerk::Package.new(original_package: original_package) + QueryPackwerk::Package.new(original_package:) end end end diff --git a/lib/query_packwerk/rule_rewriter.rb b/lib/query_packwerk/rule_rewriter.rb index 380a233..d19acb9 100644 --- a/lib/query_packwerk/rule_rewriter.rb +++ b/lib/query_packwerk/rule_rewriter.rb @@ -7,10 +7,10 @@ module QueryPackwerk # particularly for anonymizing method arguments and source patterns # to facilitate pattern-based violation analysis. class RuleRewriter - autoload :BaseRule, 'query_packwerk/rule_rewriter/base_rule' - autoload :RuleSetRewriter, 'query_packwerk/rule_rewriter/rule_set_rewriter' - autoload :AnonymizeArgumentsRule, 'query_packwerk/rule_rewriter/anonymize_arguments_rule' - autoload :AnonymizeKeywordArgumentsRule, 'query_packwerk/rule_rewriter/anonymize_keyword_arguments_rule' + autoload :BaseRule, "query_packwerk/rule_rewriter/base_rule" + autoload :RuleSetRewriter, "query_packwerk/rule_rewriter/rule_set_rewriter" + autoload :AnonymizeArgumentsRule, "query_packwerk/rule_rewriter/anonymize_arguments_rule" + autoload :AnonymizeKeywordArgumentsRule, "query_packwerk/rule_rewriter/anonymize_keyword_arguments_rule" extend T::Sig diff --git a/lib/query_packwerk/rule_rewriter/anonymize_arguments_rule.rb b/lib/query_packwerk/rule_rewriter/anonymize_arguments_rule.rb index 6216c46..e355578 100644 --- a/lib/query_packwerk/rule_rewriter/anonymize_arguments_rule.rb +++ b/lib/query_packwerk/rule_rewriter/anonymize_arguments_rule.rb @@ -7,18 +7,18 @@ class AnonymizeArgumentsRule < BaseRule extend T::Sig # Arguments prefixed with a sigil like `*arg` and `&fn` - SIGIL_ARGS = %i[splat block_pass].freeze + SIGIL_ARGS = %i(splat block_pass).freeze sig { override.params(node: RuboCop::AST::Node).void } def on_send(node) return unless node.arguments? node.arguments.reject(&:hash_type?).each do |arg| - arg_node = if SIGIL_ARGS.include?(arg.type) - arg.children.first - else - arg - end + if SIGIL_ARGS.include?(arg.type) + arg_node = arg.children.first + else + arg_node = arg + end # Just in case we get strangely shaped nodes next unless arg_node.respond_to?(:loc) diff --git a/lib/query_packwerk/rule_rewriter/anonymize_keyword_arguments_rule.rb b/lib/query_packwerk/rule_rewriter/anonymize_keyword_arguments_rule.rb index 585b4cb..a1d6496 100644 --- a/lib/query_packwerk/rule_rewriter/anonymize_keyword_arguments_rule.rb +++ b/lib/query_packwerk/rule_rewriter/anonymize_keyword_arguments_rule.rb @@ -12,11 +12,12 @@ def on_send(node) node.arguments.select(&:hash_type?).each do |hash_node| hash_node.children.each do |pair| - _keyword_node, value_node = if pair.kwsplat_type? - [nil, pair.children.first] - else - pair.children - end + if pair.kwsplat_type? + _keyword_node = nil + value_node = pair.children.first + else + _keyword_node, value_node = pair.children + end # Just in case we get strangely shaped nodes next unless value_node.respond_to?(:loc) diff --git a/lib/query_packwerk/rule_rewriter/base_rule.rb b/lib/query_packwerk/rule_rewriter/base_rule.rb index dcb9998..4621f7f 100644 --- a/lib/query_packwerk/rule_rewriter/base_rule.rb +++ b/lib/query_packwerk/rule_rewriter/base_rule.rb @@ -12,7 +12,7 @@ class BaseRule < Parser::AST::Processor include RuboCop::AST::Traversal - ANONYMIZED = '_' + ANONYMIZED = "_" sig { params(rewriter: Parser::Source::TreeRewriter).void } def initialize(rewriter) diff --git a/lib/query_packwerk/rule_rewriter/rule_set_rewriter.rb b/lib/query_packwerk/rule_rewriter/rule_set_rewriter.rb index c610b73..29d4542 100644 --- a/lib/query_packwerk/rule_rewriter/rule_set_rewriter.rb +++ b/lib/query_packwerk/rule_rewriter/rule_set_rewriter.rb @@ -21,7 +21,7 @@ class RuleSetRewriter RULES = [ RuleRewriter::AnonymizeKeywordArgumentsRule, - RuleRewriter::AnonymizeArgumentsRule + RuleRewriter::AnonymizeArgumentsRule, ].freeze def initialize(string, rules: RULES) @@ -42,10 +42,10 @@ def process @rewriter .process - .delete("\n").squeeze(' ') # ...and multiple spaces, probably indents from above - .gsub('( ', '(') # Remove paren spacing after previous - .gsub(' )', ')') # Remove paren spacing after previous - .gsub('. ', '.') # Remove suffix-dot spacing + .delete("\n").squeeze(" ") # ...and multiple spaces, probably indents from above + .gsub("( ", "(") # Remove paren spacing after previous + .gsub(" )", ")") # Remove paren spacing after previous + .gsub(". ", ".") # Remove suffix-dot spacing end private diff --git a/lib/query_packwerk/version.rb b/lib/query_packwerk/version.rb index f99d9f8..359309c 100644 --- a/lib/query_packwerk/version.rb +++ b/lib/query_packwerk/version.rb @@ -2,5 +2,5 @@ # frozen_string_literal: true module QueryPackwerk - VERSION = '0.1.26' + VERSION = "0.1.26" end diff --git a/lib/query_packwerk/violation.rb b/lib/query_packwerk/violation.rb index 9d2735d..37dda5f 100644 --- a/lib/query_packwerk/violation.rb +++ b/lib/query_packwerk/violation.rb @@ -63,7 +63,7 @@ def files # so its sources are wherever a file names the constant sig { override.params(file_name: String).returns(T::Array[RuboCop::AST::Node]) } def full_sources_in(file_name) - @file_cache.get_full_sources(file_name: file_name, class_name: class_name) + @file_cache.get_full_sources(file_name:, class_name:) end QUERY_KEYS = T.let( @@ -73,22 +73,22 @@ def full_sources_in(file_name) # Type related properties, including convenience boolean handlers type: lambda(&:type), - privacy: ->(violation) { violation.type == 'privacy' }, - dependency: ->(violation) { violation.type == 'dependency' }, + privacy: -> (violation) { violation.type == "privacy" }, + dependency: -> (violation) { violation.type == "dependency" }, # Reaching into which pack produced the violated constant, and # which consumes the violated constant. - consuming_pack: ->(violation) { violation.consuming_pack.name }, - producing_pack: ->(violation) { violation.producing_pack.name }, + consuming_pack: -> (violation) { violation.consuming_pack.name }, + producing_pack: -> (violation) { violation.producing_pack.name }, # Same, except for owners - producing_owner: ->(violation) { violation.producing_pack.owner }, - consuming_owner: ->(violation) { violation.consuming_pack.owner }, + producing_owner: -> (violation) { violation.producing_pack.owner }, + consuming_owner: -> (violation) { violation.consuming_pack.owner }, # So why is this "owner" implying producer? Because the # owner field of the violation is producer-oriented. - owner: ->(violation) { violation.producing_pack.owner }, - owned: ->(violation) { violation.producing_pack.owner != Packages::UNOWNED } + owner: -> (violation) { violation.producing_pack.owner }, + owned: -> (violation) { violation.producing_pack.owner != Packages::UNOWNED }, }.freeze, T::Hash[Symbol, T.proc.params(arg0: QueryPackwerk::Violation).returns(T.untyped)] ) diff --git a/query_packwerk.gemspec b/query_packwerk.gemspec index 626c3cf..cf7da4c 100644 --- a/query_packwerk.gemspec +++ b/query_packwerk.gemspec @@ -1,43 +1,43 @@ # frozen_string_literal: true -require_relative 'lib/query_packwerk/version' +require_relative "lib/query_packwerk/version" Gem::Specification.new do |spec| - spec.name = 'query_packwerk' + spec.name = "query_packwerk" spec.version = QueryPackwerk::VERSION - spec.authors = ['Gusto Engineering'] - spec.email = ['dev@gusto.com'] + spec.authors = ["Gusto Engineering"] + spec.email = ["dev@gusto.com"] - spec.summary = 'Query Packwerk' - spec.description = 'Query Packwerk violations and dependencies.' - spec.homepage = 'https://github.com/rubyatscale/query_packwerk' - spec.license = 'MIT' - spec.required_ruby_version = '>= 3.3' + spec.summary = "Query Packwerk" + spec.description = "Query Packwerk violations and dependencies." + spec.homepage = "https://github.com/rubyatscale/query_packwerk" + spec.license = "MIT" + spec.required_ruby_version = ">= 3.3" - spec.metadata['allowed_push_host'] = 'https://rubygems.org' + spec.metadata["allowed_push_host"] = "https://rubygems.org" - spec.metadata['homepage_uri'] = spec.homepage - spec.metadata['source_code_uri'] = 'https://github.com/rubyatscale/query_packwerk' - spec.metadata['changelog_uri'] = 'https://github.com/rubyatscale/query_packwerk/blob/main/CHANGELOG.md' + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/rubyatscale/query_packwerk" + spec.metadata["changelog_uri"] = "https://github.com/rubyatscale/query_packwerk/blob/main/CHANGELOG.md" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. gemspec = File.basename(__FILE__) - spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| + spec.files = IO.popen(%w(git ls-files -z), chdir: __dir__, err: IO::NULL) do |ls| ls.readlines("\x0", chomp: true).reject do |f| (f == gemspec) || - f.start_with?(*%w[bin/ sorbet/ test/ spec/ features/ examples/ mise.toml .git .github appveyor Gemfile Rakefile]) + f.start_with?(*%w(bin/ sorbet/ test/ spec/ features/ examples/ mise.toml .git .github appveyor Gemfile Rakefile)) end end - spec.bindir = 'exe' - spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } - spec.require_paths = ['lib'] + spec.bindir = "exe" + spec.executables = spec.files.grep(%r(\Aexe/)) { |f| File.basename(f) } + spec.require_paths = ["lib"] - spec.add_dependency 'coderay' - spec.add_dependency 'herb', '>= 0.9' - spec.add_dependency 'packwerk' - spec.add_dependency 'parse_packwerk' - spec.add_dependency 'rubocop' - spec.add_dependency 'sorbet-runtime' - spec.add_dependency 'thor' + spec.add_dependency "coderay" + spec.add_dependency "herb", ">= 0.9" + spec.add_dependency "packwerk" + spec.add_dependency "parse_packwerk" + spec.add_dependency "rubocop" + spec.add_dependency "sorbet-runtime" + spec.add_dependency "thor" end diff --git a/spec/query_packwerk/cli_spec.rb b/spec/query_packwerk/cli_spec.rb index b8a2cc8..001c2d1 100644 --- a/spec/query_packwerk/cli_spec.rb +++ b/spec/query_packwerk/cli_spec.rb @@ -1,8 +1,8 @@ # typed: false # frozen_string_literal: true -require 'tmpdir' -require 'query_packwerk/cli' +require "tmpdir" +require "query_packwerk/cli" # An uncaught SystemExit aborts the rspec run; raise_error rescues it into a failure. RSpec::Matchers.define_negated_matcher :not_raise_error, :raise_error @@ -12,41 +12,41 @@ allow(QueryPackwerk::Console).to receive(:start) end - describe 'console' do - it 'is the default command' do + describe "console" do + it "is the default command" do described_class.start([]) expect(QueryPackwerk::Console).to have_received(:start).with(Dir.pwd) end - it 'starts the console in the current directory by default' do - described_class.start(%w[console]) + it "starts the console in the current directory by default" do + described_class.start(%w(console)) expect(QueryPackwerk::Console).to have_received(:start).with(Dir.pwd) end - it 'starts the console in the given directory' do + it "starts the console in the given directory" do Dir.mktmpdir do |directory| - described_class.start(['console', directory]) + described_class.start(["console", directory]) expect(QueryPackwerk::Console).to have_received(:start).with(directory) end end - it 'exits with an error when the directory does not exist' do - expect { described_class.start(%w[console does/not/exist]) } + it "exits with an error when the directory does not exist" do + expect { described_class.start(%w(console does/not/exist)) } .to output(%(Could not find directory "does/not/exist".\n)).to_stderr .and raise_error(SystemExit) { |error| expect(error.status).to eq(1) } expect(QueryPackwerk::Console).not_to have_received(:start) end - it 'exits with an error when the path is a file' do + it "exits with an error when the path is a file" do Dir.mktmpdir do |directory| - file = File.join(directory, 'package.yml') - File.write(file, '') + file = File.join(directory, "package.yml") + File.write(file, "") - expect { described_class.start(['console', file]) } + expect { described_class.start(["console", file]) } .to output(%(Could not find directory #{file.inspect}.\n)).to_stderr .and raise_error(SystemExit) { |error| expect(error.status).to eq(1) } end @@ -54,18 +54,18 @@ expect(QueryPackwerk::Console).not_to have_received(:start) end - it 'exits with an error when given an unknown option' do - expect { described_class.start(%w[console --foo]) } + it "exits with an error when given an unknown option" do + expect { described_class.start(%w(console --foo)) } .to output(/Unknown switches "--foo"/).to_stderr .and raise_error(SystemExit) { |error| expect(error.status).to eq(1) } expect(QueryPackwerk::Console).not_to have_received(:start) end - %w[--help -h].each do |flag| + %w(--help -h).each do |flag| it "prints usage for #{flag} instead of starting the console" do # Thor wraps long_desc to the terminal width, hence \s+ between words. - expect { described_class.start(['console', flag]) } + expect { described_class.start(["console", flag]) } .to output(/\AUsage:\n \S+ console \[DIRECTORY\]\n.*DIRECTORY\s+defaults\s+to\s+the\s+current\s+directory/m).to_stdout .and not_raise_error @@ -73,8 +73,8 @@ end end - it 'prints usage for --help even when the directory does not exist' do - expect { described_class.start(%w[console --help does/not/exist]) } + it "prints usage for --help even when the directory does not exist" do + expect { described_class.start(%w(console --help does/not/exist)) } .to output(/\AUsage:/).to_stdout .and not_raise_error diff --git a/spec/query_packwerk/file_cache_spec.rb b/spec/query_packwerk/file_cache_spec.rb index a20ea5c..4d161ba 100644 --- a/spec/query_packwerk/file_cache_spec.rb +++ b/spec/query_packwerk/file_cache_spec.rb @@ -4,23 +4,23 @@ RSpec.describe QueryPackwerk::FileCache do subject(:file_cache) { described_class.new } - define_method(:sources_in) do |file_name, class_name: '::Billing::Invoice'| + define_method(:sources_in) do |file_name, class_name: "::Billing::Invoice"| file_cache - .get_full_sources(file_name: file_name, class_name: class_name) + .get_full_sources(file_name:, class_name:) .map { |node| [node.loc.line, node.source] } end - describe '#load!' do - it 'prints a dot for each file it parses, and none for a file it has' do - write_file('app/models/account.rb', "class Account < ApplicationRecord\nend\n") + describe "#load!" do + it "prints a dot for each file it parses, and none for a file it has" do + write_file("app/models/account.rb", "class Account < ApplicationRecord\nend\n") - expect { file_cache.load!('app/models/account.rb', 'app/models/account.rb', headers: false) }.to output('.').to_stderr + expect { file_cache.load!("app/models/account.rb", "app/models/account.rb", headers: false) }.to output(".").to_stderr end end - describe '#get_full_sources' do - it 'finds references in the Ruby code of an ERB template, on their template lines' do - write_file('app/views/invoices/show.html.erb', <<~ERB) + describe "#get_full_sources" do + it "finds references in the Ruby code of an ERB template, on their template lines" do + write_file("app/views/invoices/show.html.erb", <<~ERB)
Escaped: <%%= Billing::Invoice %>
@@ -33,53 +33,53 @@<%= Billing::Invoice %>
\n") + it "finds a reference that is the only code in a template" do + write_file("app/views/invoices/_name.html.erb", "<%= Billing::Invoice %>
\n") - expect(sources_in('app/views/invoices/_name.html.erb')).to eq([[1, 'Billing::Invoice']]) + expect(sources_in("app/views/invoices/_name.html.erb")).to eq([[1, "Billing::Invoice"]]) end - it 'finds nothing, without a warning, in an ERB template without Ruby code' do - write_file('app/views/pages/about.html.erb', "About
\n") + it "finds nothing, without a warning, in an ERB template without Ruby code" do + write_file("app/views/pages/about.html.erb", "About
\n") - expect { sources_in('app/views/pages/about.html.erb') }.not_to output.to_stderr - expect(sources_in('app/views/pages/about.html.erb')).to eq([]) + expect { sources_in("app/views/pages/about.html.erb") }.not_to output.to_stderr + expect(sources_in("app/views/pages/about.html.erb")).to eq([]) end - it 'finds nothing, without a warning, in a Ruby file with only comments' do - write_file('app/models/invoice.rb', "# frozen_string_literal: true\n") + it "finds nothing, without a warning, in a Ruby file with only comments" do + write_file("app/models/invoice.rb", "# frozen_string_literal: true\n") - expect { sources_in('app/models/invoice.rb') }.not_to output.to_stderr - expect(sources_in('app/models/invoice.rb')).to eq([]) + expect { sources_in("app/models/invoice.rb") }.not_to output.to_stderr + expect(sources_in("app/models/invoice.rb")).to eq([]) end - %w[app/models/invoice.rb app/views/invoices/show.html.erb].each do |file_name| + %w(app/models/invoice.rb app/views/invoices/show.html.erb).each do |file_name| it "finds nothing, without a warning, when #{file_name} does not exist" do expect { sources_in(file_name) }.not_to output.to_stderr expect(sources_in(file_name)).to eq([]) end end - it 'warns, once, that it found nothing in a file it could not parse' do - write_file('app/views/invoices/show.html.erb', <<~ERB) + it "warns, once, that it found nothing in a file it could not parse" do + write_file("app/views/invoices/show.html.erb", <<~ERB) <% if Billing::Invoice.overdue?(@account) %>Overdue
<% end %> @@ -87,31 +87,31 @@ ERB expect do - sources_in('app/views/invoices/show.html.erb') - sources_in('app/views/invoices/show.html.erb', class_name: '::Billing::Payment') + sources_in("app/views/invoices/show.html.erb") + sources_in("app/views/invoices/show.html.erb", class_name: "::Billing::Payment") end.to output(%r{\ACould not parse app/views/invoices/show\.html\.erb:4 \(.+\), so its sources are not included\n\z}) .to_stderr - expect(sources_in('app/views/invoices/show.html.erb')).to eq([]) + expect(sources_in("app/views/invoices/show.html.erb")).to eq([]) end - %w[ + %w( lib/tasks/billing.rake app/views/invoices/show.xml.builder billing.gemspec config.ru Gemfile Rakefile - ].each do |file_name| + ).each do |file_name| it "finds references in #{file_name}" do write_file(file_name, "Billing::Invoice.find(1)\n") - expect(sources_in(file_name)).to eq([[1, 'Billing::Invoice.find(1)']]) + expect(sources_in(file_name)).to eq([[1, "Billing::Invoice.find(1)"]]) end end - it 'finds nothing in a file that packwerk does not parse' do - write_file('Gemfile.lock', "Billing::Invoice.find(1)\n") + it "finds nothing in a file that packwerk does not parse" do + write_file("Gemfile.lock", "Billing::Invoice.find(1)\n") - expect(sources_in('Gemfile.lock')).to eq([]) + expect(sources_in("Gemfile.lock")).to eq([]) end - it 'gets the calls on each use of the constant, rather than on an equal use around it' do - write_file('app/models/account.rb', <<~RUBY) + it "gets the calls on each use of the constant, rather than on an equal use around it" do + write_file("app/models/account.rb", <<~RUBY) class Account < ApplicationRecord def merge = Billing::Invoice.merge(Billing::Invoice) @@ -119,18 +119,18 @@ def latest = Billing::Invoice.latest.then { Billing::Invoice.latest } end RUBY - expect(sources_in('app/models/account.rb')).to eq( + expect(sources_in("app/models/account.rb")).to eq( [ - [2, 'Billing::Invoice.merge(Billing::Invoice)'], - [2, 'Billing::Invoice'], - [4, 'Billing::Invoice.latest.then'], - [4, 'Billing::Invoice.latest'] + [2, "Billing::Invoice.merge(Billing::Invoice)"], + [2, "Billing::Invoice"], + [4, "Billing::Invoice.latest.then"], + [4, "Billing::Invoice.latest"], ] ) end - it 'finds no use of a constant where it is only the namespace of another' do - write_file('app/models/account.rb', <<~RUBY) + it "finds no use of a constant where it is only the namespace of another" do + write_file("app/models/account.rb", <<~RUBY) class Account < ApplicationRecord def billing = Billing.for(self) @@ -138,17 +138,17 @@ def invoice = Billing::Invoice.for(self) end RUBY - expect(sources_in('app/models/account.rb', class_name: '::Billing')).to eq([[2, 'Billing.for(self)']]) + expect(sources_in("app/models/account.rb", class_name: "::Billing")).to eq([[2, "Billing.for(self)"]]) end end - describe '#get_full_source_at' do + describe "#get_full_source_at" do define_method(:source_at) do |line, column| - file_cache.get_full_source_at(file_name: 'app/models/account.rb', line: line, column: column)&.source + file_cache.get_full_source_at(file_name: "app/models/account.rb", line:, column:)&.source end before do - write_file('app/models/account.rb', <<~RUBY) + write_file("app/models/account.rb", <<~RUBY) class Account < ApplicationRecord has_many :invoices, dependent: :destroy @@ -159,16 +159,16 @@ def summary = "Échéance ⏰ \#{Billing::Invoice.due_for(self).count}" RUBY end - it 'finds the outermost constant that starts there, with the calls chained on it' do - expect(source_at(4, 22)).to eq('Billing::Invoice::Line.overdue_for(self)') + it "finds the outermost constant that starts there, with the calls chained on it" do + expect(source_at(4, 22)).to eq("Billing::Invoice::Line.overdue_for(self)") end - it 'counts the column in bytes, as pks does' do - expect(source_at(6, 34)).to eq('Billing::Invoice.due_for(self).count') + it "counts the column in bytes, as pks does" do + expect(source_at(6, 34)).to eq("Billing::Invoice.due_for(self).count") end - it 'finds a constant that no call is chained on, as an argument or a superclass' do - write_file('app/models/account.rb', <<~RUBY) + it "finds a constant that no call is chained on, as an argument or a superclass" do + write_file("app/models/account.rb", <<~RUBY) class Account < ApplicationRecord def latest_number = Billing::Invoice.last&.number @@ -176,31 +176,31 @@ def invoice?(record) = record.is_a?(Billing::Invoice) end RUBY - expect(source_at(1, 16)).to eq('ApplicationRecord') - expect(source_at(2, 22)).to eq('Billing::Invoice.last&.number') - expect(source_at(4, 38)).to eq('Billing::Invoice') + expect(source_at(1, 16)).to eq("ApplicationRecord") + expect(source_at(2, 22)).to eq("Billing::Invoice.last&.number") + expect(source_at(4, 38)).to eq("Billing::Invoice") end - it 'finds the call when no constant starts there, as for an association' do - expect(source_at(2, 2)).to eq('has_many :invoices, dependent: :destroy') + it "finds the call when no constant starts there, as for an association" do + expect(source_at(2, 2)).to eq("has_many :invoices, dependent: :destroy") end - it 'finds nothing when nothing starts there' do + it "finds nothing when nothing starts there" do expect(source_at(4, 23)).to be_nil end - it 'finds the calls on the constant there, rather than on an equal one around it' do - write_file('app/models/account.rb', "def merge = Billing::Invoice.merge(Billing::Invoice)\n") + it "finds the calls on the constant there, rather than on an equal one around it" do + write_file("app/models/account.rb", "def merge = Billing::Invoice.merge(Billing::Invoice)\n") - expect(source_at(1, 35)).to eq('Billing::Invoice') + expect(source_at(1, 35)).to eq("Billing::Invoice") end - it 'finds nothing in a file that does not exist or does not parse' do - write_file('app/models/broken.rb', "Billing::Invoice.find(\n") + it "finds nothing in a file that does not exist or does not parse" do + write_file("app/models/broken.rb", "Billing::Invoice.find(\n") - expect(file_cache.get_full_source_at(file_name: 'app/models/missing.rb', line: 1, column: 0)).to be_nil - expect { expect(file_cache.get_full_source_at(file_name: 'app/models/broken.rb', line: 1, column: 0)).to be_nil } - .to output(%r{\ACould not parse app/models/broken\.rb}).to_stderr + expect(file_cache.get_full_source_at(file_name: "app/models/missing.rb", line: 1, column: 0)).to be_nil + expect { expect(file_cache.get_full_source_at(file_name: "app/models/broken.rb", line: 1, column: 0)).to be_nil } + .to output(%r(\ACould not parse app/models/broken\.rb)).to_stderr end end end diff --git a/spec/query_packwerk/package_spec.rb b/spec/query_packwerk/package_spec.rb index d6f41d8..4f46ee0 100644 --- a/spec/query_packwerk/package_spec.rb +++ b/spec/query_packwerk/package_spec.rb @@ -2,155 +2,155 @@ # frozen_string_literal: true RSpec.describe QueryPackwerk::Package do - include_context 'pseudo packs' + include_context "pseudo packs" let(:package) { QueryPackwerk.package(package_name) } - describe '#name' do - it 'returns the package name' do + describe "#name" do + it "returns the package name" do expect(package.name).to eq(package_name) end end - describe '#enforce_dependencies' do - it 'returns whether dependencies are enforced' do + describe "#enforce_dependencies" do + it "returns whether dependencies are enforced" do expect(package.enforce_dependencies).to be true end end - describe '#enforce_privacy' do - it 'returns whether privacy is enforced' do + describe "#enforce_privacy" do + it "returns whether privacy is enforced" do expect(package.enforce_privacy).to be true end end - describe '#metadata' do - it 'returns the package metadata' do + describe "#metadata" do + it "returns the package metadata" do expect(package.metadata).to be_a(Hash) end end - describe '#dependencies' do - it 'returns the package dependencies as a Packages collection' do + describe "#dependencies" do + it "returns the package dependencies as a Packages collection" do expect(package.dependencies).to be_a(QueryPackwerk::Packages) end end - describe '#dependency_names' do - it 'returns an array of dependency names' do + describe "#dependency_names" do + it "returns an array of dependency names" do expect(package.dependency_names).to be_an(Array) end end - describe '#owner' do - it 'returns the owner or unowned constant' do + describe "#owner" do + it "returns the owner or unowned constant" do expect(package.owner).to eq(QueryPackwerk::Packages::UNOWNED) end end - describe '#directory' do - it 'returns a Pathname representing the package directory' do + describe "#directory" do + it "returns a Pathname representing the package directory" do expect(package.directory).to be_a(Pathname) expect(package.directory.to_s).to eq(package_name) end end - describe '#todos' do - it 'returns violations for the package' do + describe "#todos" do + it "returns violations for the package" do todos = package.todos expect(todos).to be_a(QueryPackwerk::Violations) expect(todos.size).to eq(raw_violations.size) end end - describe '#outgoing_violations' do - it 'is an alias for #todos' do + describe "#outgoing_violations" do + it "is an alias for #todos" do # Both methods should return equivalent objects but might not be equal with `==` expect(package.todos.to_a).to match_array(package.outgoing_violations.to_a) end end - describe '#violations' do - it 'returns violations where this package is the producing pack' do + describe "#violations" do + it "returns violations where this package is the producing pack" do violations = package.violations expect(violations).to be_a(QueryPackwerk::Violations) end end - describe '#incoming_violations' do - it 'is an alias for #violations' do + describe "#incoming_violations" do + it "is an alias for #violations" do # Both methods should return equivalent objects but might not be equal with `==` expect(package.incoming_violations.to_a).to match_array(package.violations.to_a) end end - describe '#consumers' do - it 'returns packages that have violations against this package' do + describe "#consumers" do + it "returns packages that have violations against this package" do expect(package.consumers).to be_a(QueryPackwerk::Packages) end end - describe '#consumer_names' do - it 'returns an array of consumer package names' do + describe "#consumer_names" do + it "returns an array of consumer package names" do expect(package.consumer_names).to be_an(Array) end end - describe '#consumer_counts' do - it 'returns a hash of consumer package names to violation counts' do + describe "#consumer_counts" do + it "returns a hash of consumer package names to violation counts" do expect(package.consumer_counts).to be_a(Hash) end end - describe '#parent_name' do - it 'returns the parent directory name' do - expect(package.parent_name).to eq('packs') + describe "#parent_name" do + it "returns the parent directory name" do + expect(package.parent_name).to eq("packs") end end - describe '#deconstruct_keys' do - it 'returns a hash of values for pattern matching' do - result = package.deconstruct_keys(%i[name owner dependencies]) + describe "#deconstruct_keys" do + it "returns a hash of values for pattern matching" do + result = package.deconstruct_keys(%i(name owner dependencies)) expect(result).to be_a(Hash) expect(result.keys).to include(:name, :owner, :dependencies) expect(result[:name]).to eq(package_name) end - it 'returns all values when keys is nil' do + it "returns all values when keys is nil" do result = package.deconstruct_keys(nil) expect(result).to be_a(Hash) expect(result.keys).to include(:name, :owner, :dependencies, :owned, :parent_name) end end - describe '#inspect' do - it 'returns a string representation of the package' do + describe "#inspect" do + it "returns a string representation of the package" do expect(package.inspect).to eq("#<%= HoneyProductionNectar.as_of_now.find_by(apiary_id: @apiary.id).volume %>
\n" + "<%= HoneyProductionNectar.as_of_now.find_by(apiary_id: @apiary.id).volume %>
\n", ] ) end diff --git a/spec/query_packwerk/references_spec.rb b/spec/query_packwerk/references_spec.rb index 96db39c..efffd42 100644 --- a/spec/query_packwerk/references_spec.rb +++ b/spec/query_packwerk/references_spec.rb @@ -2,32 +2,32 @@ # frozen_string_literal: true RSpec.describe QueryPackwerk::References do - include_context 'listed references' + include_context "listed references" - describe '.all' do - it 'has each reference that pks lists' do + describe ".all" do + it "has each reference that pks lists" do expect(described_class.all.map(&:location)).to eq( [ - 'app/services/apiary_summary.rb:2', - 'packs/apiary_reports/app/services/apiary_report.rb:2', - 'packs/apiary_reports/app/services/apiary_report.rb:4', - 'packs/hive_dashboard/app/models/hive.rb:2', - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:4', - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:8', - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12', - 'packs/hive_dashboard/app/services/report_link.rb:2', - 'packs/hive_dashboard/app/views/apiaries/show.html.erb' + "app/services/apiary_summary.rb:2", + "packs/apiary_reports/app/services/apiary_report.rb:2", + "packs/apiary_reports/app/services/apiary_report.rb:4", + "packs/hive_dashboard/app/models/hive.rb:2", + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:4", + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:8", + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12", + "packs/hive_dashboard/app/services/report_link.rb:2", + "packs/hive_dashboard/app/views/apiaries/show.html.erb", ] ) end - it 'runs pks once' do + it "runs pks once" do 2.times { described_class.all } expect(QueryPackwerk::Pks).to have_received(:list_references).once end - it 'runs pks again after a reload' do + it "runs pks again after a reload" do described_class.all described_class.reload! described_class.all @@ -35,98 +35,98 @@ expect(QueryPackwerk::Pks).to have_received(:list_references).twice end - it 'says when pks lists a pack that has no package.yml' do - listed_references.first['referencing_pack_name'] = 'packs/gone' + it "says when pks lists a pack that has no package.yml" do + listed_references.first["referencing_pack_name"] = "packs/gone" expect { described_class.all }.to raise_error( QueryPackwerk::Pks::Error, - 'pks lists references from or to packs/gone, which has no package.yml' + "pks lists references from or to packs/gone, which has no package.yml" ) end - it 'finds a pack that a symlink points to, which ParsePackwerk does not' do + it "finds a pack that a symlink points to, which ParsePackwerk does not" do Dir.mktmpdir do |shared_pack| - File.write(File.join(shared_pack, 'package.yml'), "enforce_dependencies: true\n") - File.symlink(shared_pack, 'packs/wax_reports') - listed_references.first['referencing_pack_name'] = 'packs/wax_reports' + File.write(File.join(shared_pack, "package.yml"), "enforce_dependencies: true\n") + File.symlink(shared_pack, "packs/wax_reports") + listed_references.first["referencing_pack_name"] = "packs/wax_reports" - expect(ParsePackwerk.find('packs/wax_reports')).to be_nil - expect(described_class.all.first.consuming_pack.name).to eq('packs/wax_reports') + expect(ParsePackwerk.find("packs/wax_reports")).to be_nil + expect(described_class.all.first.consuming_pack.name).to eq("packs/wax_reports") end end end - describe '.where' do - it 'finds the references that break no rule' do + describe ".where" do + it "finds the references that break no rule" do expect(described_class.where(allowed: true).map(&:location)).to eq( [ - 'app/services/apiary_summary.rb:2', - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12' + "app/services/apiary_summary.rb:2", + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12", ] ) end - it 'finds the references that break a rule' do - expect(described_class.where(violation_types: 'dependency').map(&:location)).to eq( + it "finds the references that break a rule" do + expect(described_class.where(violation_types: "dependency").map(&:location)).to eq( [ - 'packs/apiary_reports/app/services/apiary_report.rb:2', - 'packs/apiary_reports/app/services/apiary_report.rb:4', - 'packs/hive_dashboard/app/services/report_link.rb:2' + "packs/apiary_reports/app/services/apiary_report.rb:2", + "packs/apiary_reports/app/services/apiary_report.rb:4", + "packs/hive_dashboard/app/services/report_link.rb:2", ] ) end - it 'finds the references that break a rule no package_todo.yml records' do + it "finds the references that break a rule no package_todo.yml records" do expect(described_class.where(unrecorded: true).map(&:location)).to eq( [ - 'packs/apiary_reports/app/services/apiary_report.rb:2', - 'packs/apiary_reports/app/services/apiary_report.rb:4', - 'packs/hive_dashboard/app/models/hive.rb:2', - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:8', - 'packs/hive_dashboard/app/services/report_link.rb:2' + "packs/apiary_reports/app/services/apiary_report.rb:2", + "packs/apiary_reports/app/services/apiary_report.rb:4", + "packs/hive_dashboard/app/models/hive.rb:2", + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:8", + "packs/hive_dashboard/app/services/report_link.rb:2", ] ) - expect(described_class.where(unrecorded_violation_types: 'dependency').map(&:location)).to eq( - ['packs/hive_dashboard/app/services/report_link.rb:2'] + expect(described_class.where(unrecorded_violation_types: "dependency").map(&:location)).to eq( + ["packs/hive_dashboard/app/services/report_link.rb:2"] ) end - it 'finds the references to a pack without an owner' do - expect(described_class.where(owned: false).map(&:constant_name)).to eq(['::ApiaryReportCard']) + it "finds the references to a pack without an owner" do + expect(described_class.where(owned: false).map(&:constant_name)).to eq(["::ApiaryReportCard"]) end - it 'finds the references to constants named with or without their leading ::' do - expect(described_class.where(constant_name: %w[Beekeeping::Nectars ::ApiaryReportCard]).map(&:location)).to eq( + it "finds the references to constants named with or without their leading ::" do + expect(described_class.where(constant_name: %w(Beekeeping::Nectars ::ApiaryReportCard)).map(&:location)).to eq( [ - 'app/services/apiary_summary.rb:2', - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12', - 'packs/hive_dashboard/app/services/report_link.rb:2' + "app/services/apiary_summary.rb:2", + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12", + "packs/hive_dashboard/app/services/report_link.rb:2", ] ) end - it 'finds the references from a pack' do - expect(described_class.where(consuming_pack: '.').map(&:constant_name)).to eq(['::Beekeeping::Nectars']) + it "finds the references from a pack" do + expect(described_class.where(consuming_pack: ".").map(&:constant_name)).to eq(["::Beekeeping::Nectars"]) end - it 'finds nothing when pks lists no references' do + it "finds nothing when pks lists no references" do listed_references.clear - expect(described_class.where(producing_pack: 'packs/honey_production')).to be_empty + expect(described_class.where(producing_pack: "packs/honey_production")).to be_empty end - it 'keeps the files that all parses, so each query parses a file only once' do + it "keeps the files that all parses, so each query parses a file only once" do all = described_class.all expect(described_class.where(allowed: true).file_cache).to equal(all.file_cache) - expect(all.including_files('app/**').file_cache).to equal(all.file_cache) - expect(all.excluding_files('app/**').file_cache).to equal(all.file_cache) + expect(all.including_files("app/**").file_cache).to equal(all.file_cache) + expect(all.excluding_files("app/**").file_cache).to equal(all.file_cache) end end - describe '#load_sources!' do - it 'prints a dot for each file it parses, rather than for each reference' do - references = described_class.where(producing_pack: 'packs/honey_production') + describe "#load_sources!" do + it "prints a dot for each file it parses, rather than for each reference" do + references = described_class.where(producing_pack: "packs/honey_production") expect { references.load_sources! }.to output( /\APrepopulating AST cache with 5 files: \n\.{5}\nAST cache loaded in \S+\nPrepopulating sources cache with 8 references\nLoaded 9 full sources in \S+\n\z/ @@ -134,87 +134,87 @@ end end - describe '#file_count' do - it 'counts each file once, however many references are in it' do + describe "#file_count" do + it "counts each file once, however many references are in it" do expect(described_class.all.file_count).to eq(6) end end - describe '#sources_with_locations' do - it 'gets the sources of each constant, where pks finds them' do + describe "#sources_with_locations" do + it "gets the sources of each constant, where pks finds them" do expect(described_class.all.sources_with_locations).to eq( { - '::Beekeeping::Nectars' => [ - ['app/services/apiary_summary.rb:2', 'Beekeeping::Nectars.status_for(apiary_id: 1)'], - ['packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12', 'Nectars.status_for(apiary_id: 1)'] + "::Beekeeping::Nectars" => [ + ["app/services/apiary_summary.rb:2", "Beekeeping::Nectars.status_for(apiary_id: 1)"], + ["packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:12", "Nectars.status_for(apiary_id: 1)"], ], - '::HoneyProductionNectar' => [ - ['packs/apiary_reports/app/services/apiary_report.rb:2', 'HoneyProductionNectar.count'], - ['packs/apiary_reports/app/services/apiary_report.rb:4', 'HoneyProductionNectar.model_name.human'], - ['packs/hive_dashboard/app/models/hive.rb:2', 'has_many :honey_production_nectars, dependent: :destroy'], - ['packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:4', '::HoneyProductionNectar.as_of_now.find_by(apiary_id: 1)'], - ['packs/hive_dashboard/app/views/apiaries/show.html.erb:1', 'HoneyProductionNectar.as_of_now.exists?(apiary_id: @apiary.id)'], - ['packs/hive_dashboard/app/views/apiaries/show.html.erb:2', 'HoneyProductionNectar.as_of_now.find_by(apiary_id: @apiary.id).volume'] + "::HoneyProductionNectar" => [ + ["packs/apiary_reports/app/services/apiary_report.rb:2", "HoneyProductionNectar.count"], + ["packs/apiary_reports/app/services/apiary_report.rb:4", "HoneyProductionNectar.model_name.human"], + ["packs/hive_dashboard/app/models/hive.rb:2", "has_many :honey_production_nectars, dependent: :destroy"], + ["packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:4", "::HoneyProductionNectar.as_of_now.find_by(apiary_id: 1)"], + ["packs/hive_dashboard/app/views/apiaries/show.html.erb:1", "HoneyProductionNectar.as_of_now.exists?(apiary_id: @apiary.id)"], + ["packs/hive_dashboard/app/views/apiaries/show.html.erb:2", "HoneyProductionNectar.as_of_now.find_by(apiary_id: @apiary.id).volume"], ], - '::Beekeeping::NectarSource' => [ - ['packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:8', 'NectarSource.where(apiary_id: 1).pluck(:name)'] + "::Beekeeping::NectarSource" => [ + ["packs/hive_dashboard/app/services/beekeeping/apiary_status.rb:8", "NectarSource.where(apiary_id: 1).pluck(:name)"], + ], + "::ApiaryReportCard" => [ + ["packs/hive_dashboard/app/services/report_link.rb:2", "ApiaryReportCard.new"], ], - '::ApiaryReportCard' => [ - ['packs/hive_dashboard/app/services/report_link.rb:2', 'ApiaryReportCard.new'] - ] } ) end end - describe '#anonymous_source_counts' do + describe "#anonymous_source_counts" do it "shows how a pack's constants are used where the rules allow it" do - allowed = described_class.where(producing_pack: 'packs/honey_production', allowed: true) + allowed = described_class.where(producing_pack: "packs/honey_production", allowed: true) expect(allowed.anonymous_source_counts).to eq( - '::Beekeeping::Nectars' => { - 'Beekeeping::Nectars.status_for(apiary_id: _)' => 1, - 'Nectars.status_for(apiary_id: _)' => 1 + "::Beekeeping::Nectars" => { + "Beekeeping::Nectars.status_for(apiary_id: _)" => 1, + "Nectars.status_for(apiary_id: _)" => 1, } ) end end - describe '#consumers' do - it 'counts the references from each pack' do - expect(described_class.all.consumers).to eq('packs/hive_dashboard' => 6, 'packs/apiary_reports' => 2, '.' => 1) + describe "#consumers" do + it "counts the references from each pack" do + expect(described_class.all.consumers).to eq("packs/hive_dashboard" => 6, "packs/apiary_reports" => 2, "." => 1) end end - describe '#producers' do - it 'counts the references to each pack' do - expect(described_class.all.producers).to eq('packs/honey_production' => 8, 'packs/apiary_reports' => 1) + describe "#producers" do + it "counts the references to each pack" do + expect(described_class.all.producers).to eq("packs/honey_production" => 8, "packs/apiary_reports" => 1) end end - describe '#including_files' do - it 'finds the references in files that match' do - references = described_class.all.including_files('packs/apiary_reports/**') + describe "#including_files" do + it "finds the references in files that match" do + references = described_class.all.including_files("packs/apiary_reports/**") expect(references).to be_a(described_class) expect(references.map(&:location)).to eq( [ - 'packs/apiary_reports/app/services/apiary_report.rb:2', - 'packs/apiary_reports/app/services/apiary_report.rb:4' + "packs/apiary_reports/app/services/apiary_report.rb:2", + "packs/apiary_reports/app/services/apiary_report.rb:4", ] ) end end - describe '#excluding_files' do - it 'finds the references in files that do not match' do - references = described_class.all.excluding_files('packs/hive_dashboard/**', 'app/**') + describe "#excluding_files" do + it "finds the references in files that do not match" do + references = described_class.all.excluding_files("packs/hive_dashboard/**", "app/**") expect(references).to be_a(described_class) expect(references.map(&:location)).to eq( [ - 'packs/apiary_reports/app/services/apiary_report.rb:2', - 'packs/apiary_reports/app/services/apiary_report.rb:4' + "packs/apiary_reports/app/services/apiary_report.rb:2", + "packs/apiary_reports/app/services/apiary_report.rb:4", ] ) end diff --git a/spec/query_packwerk/rule_rewriter_spec.rb b/spec/query_packwerk/rule_rewriter_spec.rb index 64aad99..72a4460 100644 --- a/spec/query_packwerk/rule_rewriter_spec.rb +++ b/spec/query_packwerk/rule_rewriter_spec.rb @@ -2,49 +2,49 @@ # frozen_string_literal: true RSpec.describe QueryPackwerk::RuleRewriter do - context 'With positional arguments' do - it 'anonymizes positional args' do - expect(described_class.rewrite('all(1, 2, 3)')).to eq('all(_, _, _)') + context "With positional arguments" do + it "anonymizes positional args" do + expect(described_class.rewrite("all(1, 2, 3)")).to eq("all(_, _, _)") end - it 'anonymizes complicated positional args' do + it "anonymizes complicated positional args" do code = "Model.find(1, 2, 's', a.b.c.d, Some::Nasty::Const.with(1))" - expect(described_class.rewrite(code)).to eq('Model.find(_, _, _, _, _)') + expect(described_class.rewrite(code)).to eq("Model.find(_, _, _, _, _)") end - it 'anonymizes splatted positional args' do + it "anonymizes splatted positional args" do code = "Model.find(1, 2, 's', *var)" - expect(described_class.rewrite(code)).to eq('Model.find(_, _, _, *_)') + expect(described_class.rewrite(code)).to eq("Model.find(_, _, _, *_)") end - it 'anonymizes function args' do + it "anonymizes function args" do code = "Model.find(1, 2, 's', &var)" - expect(described_class.rewrite(code)).to eq('Model.find(_, _, _, &_)') + expect(described_class.rewrite(code)).to eq("Model.find(_, _, _, &_)") end end - context 'With keyword arguments' do - it 'anonymizes keyword args' do - expect(described_class.rewrite('all(a: 1, b: 2)')).to eq('all(a: _, b: _)') + context "With keyword arguments" do + it "anonymizes keyword args" do + expect(described_class.rewrite("all(a: 1, b: 2)")).to eq("all(a: _, b: _)") end - it 'anonymizes complicated keyword args' do - code = 'Model.where(a: 1, b: { c: 2 }, d: A::B.c(1))' - expect(described_class.rewrite(code)).to eq('Model.where(a: _, b: _, d: _)') + it "anonymizes complicated keyword args" do + code = "Model.where(a: 1, b: { c: 2 }, d: A::B.c(1))" + expect(described_class.rewrite(code)).to eq("Model.where(a: _, b: _, d: _)") end - it 'anonymizes splatted kwargs' do - code = 'Model.where(a: 1, b: { c: 2 }, **d)' - expect(described_class.rewrite(code)).to eq('Model.where(a: _, b: _, **_)') + it "anonymizes splatted kwargs" do + code = "Model.where(a: 1, b: { c: 2 }, **d)" + expect(described_class.rewrite(code)).to eq("Model.where(a: _, b: _, **_)") end end - context 'With both types of arguments' do - it 'anonymizes mixed args' do - expect(described_class.rewrite('all(1, a: 1, b: 2)')).to eq('all(_, a: _, b: _)') + context "With both types of arguments" do + it "anonymizes mixed args" do + expect(described_class.rewrite("all(1, a: 1, b: 2)")).to eq("all(_, a: _, b: _)") end - it 'anonymizes complicated keyword args' do + it "anonymizes complicated keyword args" do code = <<~RUBY Model.where( 1, @@ -67,9 +67,9 @@ end end - context 'With a heredoc argument' do - it 'leaves the source as it is, since it does not parse without the heredoc body after it' do - expect(described_class.rewrite('Model.execute(1, <<~SQL)')).to eq('Model.execute(1, <<~SQL)') + context "With a heredoc argument" do + it "leaves the source as it is, since it does not parse without the heredoc body after it" do + expect(described_class.rewrite("Model.execute(1, <<~SQL)")).to eq("Model.execute(1, <<~SQL)") end end end diff --git a/spec/query_packwerk/violation_spec.rb b/spec/query_packwerk/violation_spec.rb index 3f7d14f..9b91620 100644 --- a/spec/query_packwerk/violation_spec.rb +++ b/spec/query_packwerk/violation_spec.rb @@ -2,22 +2,22 @@ # frozen_string_literal: true RSpec.describe QueryPackwerk::Violation do - include_context 'pseudo packs' + include_context "pseudo packs" - context 'when the violating file is an ERB template' do + context "when the violating file is an ERB template" do subject(:violation) do described_class.new( original_violation: ParsePackwerk::Violation.new( - type: 'privacy', + type: "privacy", to_package_name: package_name, - class_name: '::HoneyProductionNectar', + class_name: "::HoneyProductionNectar", files: [template] ), consuming_pack: ParsePackwerk.find(package_name) ) end - let(:template) { 'packs/hive_dashboard/app/views/apiaries/show.html.erb' } + let(:template) { "packs/hive_dashboard/app/views/apiaries/show.html.erb" } let(:template_source) do <<~ERB<%= HoneyProductionNectar.as_of_now.find_by(apiary_id: @apiary.id).volume %>
CONTEXT - <<~CONTEXT + <<~CONTEXT, > #{template}:4 (L3..5) <% if HoneyProductionNectar.as_of_now.exists?(apiary_id: @apiary.id) %> @@ -65,7 +65,7 @@ ) end - context 'when a reference is near the top of the template' do + context "when a reference is near the top of the template" do let(:template_source) do <<~ERB<%= HoneyProductionNectar.as_of_now.volume %>
@@ -75,7 +75,7 @@ ERB end - it 'shows context from the top of the template' do + it "shows context from the top of the template" do expect(violation.sources_with_contexts.values.flatten).to eq(["> #{template}:1 (L1..4)\n\n#{template_source}"]) end end diff --git a/spec/query_packwerk/violations_spec.rb b/spec/query_packwerk/violations_spec.rb index 28a01a1..15b5b6b 100644 --- a/spec/query_packwerk/violations_spec.rb +++ b/spec/query_packwerk/violations_spec.rb @@ -2,101 +2,101 @@ # frozen_string_literal: true RSpec.describe QueryPackwerk::Violations do - include_context 'pseudo packs' + include_context "pseudo packs" - describe '#where' do - it 'can query violations' do + describe "#where" do + it "can query violations" do violation_counts = described_class.where(privacy: true).map(&:type).tally - expect(violation_counts).to eq({ 'privacy' => 5 }) + expect(violation_counts).to eq({ "privacy" => 5 }) end - it 'can use the `===` interface for things like regex matching a field' do + it "can use the `===` interface for things like regex matching a field" do violations = described_class.where(constant_name: /::Beekeeping/).map(&:class_name) - expect(violations).to eq(['::Beekeeping::HoneyProduction::Nectars']) + expect(violations).to eq(["::Beekeeping::HoneyProduction::Nectars"]) end - it 'finds a constant named without its leading ::' do - violations = described_class.where(constant_name: 'Beekeeping::HoneyProduction::Nectars').map(&:class_name) + it "finds a constant named without its leading ::" do + violations = described_class.where(constant_name: "Beekeeping::HoneyProduction::Nectars").map(&:class_name) - expect(violations).to eq(['::Beekeeping::HoneyProduction::Nectars']) + expect(violations).to eq(["::Beekeeping::HoneyProduction::Nectars"]) end - it 'keeps the files that all parses, so each query parses a file only once' do + it "keeps the files that all parses, so each query parses a file only once" do expect(described_class.where(privacy: true).file_cache).to equal(described_class.all.file_cache) end end - describe '#empty? and #any?' do - it 'returns true for empty? when there are no violations' do + describe "#empty? and #any?" do + it "returns true for empty? when there are no violations" do empty_violations = described_class.new([]) expect(empty_violations.empty?).to be true expect(empty_violations.any?).to be false end - it 'returns false for empty? when there are violations' do + it "returns false for empty? when there are violations" do expect(described_class.all.empty?).to be false expect(described_class.all.any?).to be true end end - describe '#inspect' do - it 'returns a string representation of an empty collection' do + describe "#inspect" do + it "returns a string representation of an empty collection" do violations = described_class.new([]) expect(violations.inspect).to eq("#<#{described_class.name} []>") end - it 'returns a string representation of a collection with violations' do + it "returns a string representation of a collection with violations" do violations = described_class.all expect(violations.inspect).to eq("#<#{described_class.name} [\n#{described_class.all.map(&:inspect).join("\n")}\n]>") end end - describe '#anonymous_sources_with_locations' do - it 'can get anonymized sources with their file locations' do + describe "#anonymous_sources_with_locations" do + it "can get anonymized sources with their file locations" do # { constant => { violating code shape => [where it happened] } } expect(described_class.all.anonymous_sources_with_locations).to eq( { - '::Backfills::BackfillPollinationCoveredPeriodDates' => { - 'Backfills::BackfillPollinationCoveredPeriodDates.run!' => [ - 'db/data/20210309211702_backfill_pollination_covered_period_dates.rb:3' - ] + "::Backfills::BackfillPollinationCoveredPeriodDates" => { + "Backfills::BackfillPollinationCoveredPeriodDates.run!" => [ + "db/data/20210309211702_backfill_pollination_covered_period_dates.rb:3", + ], }, - '::Mutations::HoneyProduction::SaveNectar' => { - 'Mutations::HoneyProduction::SaveNectar' => [ - 'packs/hivemind_subgraph/app/lib/objects/mutation.rb:1' - ] + "::Mutations::HoneyProduction::SaveNectar" => { + "Mutations::HoneyProduction::SaveNectar" => [ + "packs/hivemind_subgraph/app/lib/objects/mutation.rb:1", + ], }, - '::HoneyProductionNectar' => { - 'HoneyProductionNectar.as_of_now.find_by(apiary_id: _)' => [ - 'packs/hive_graphql_concerns/app/public/objects/apiary.rb:3' - ] + "::HoneyProductionNectar" => { + "HoneyProductionNectar.as_of_now.find_by(apiary_id: _)" => [ + "packs/hive_graphql_concerns/app/public/objects/apiary.rb:3", + ], }, - '::HoneyProductionNectarPollinationInfo' => { - 'HoneyProductionNectarPollinationInfo.where(apiary_id: _).where.not(nectar_amount: _).exists?' => [ + "::HoneyProductionNectarPollinationInfo" => { + "HoneyProductionNectarPollinationInfo.where(apiary_id: _).where.not(nectar_amount: _).exists?" => [ # Privacy _and_ dependency violations both apply to the same line. This is intentional - 'packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6', - 'packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6' - ] + "packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6", + "packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6", + ], + }, + "::Beekeeping::HoneyProduction::Nectars" => { + "Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: _)" => [ + "packs/hive_graphql_concerns/app/public/objects/apiary.rb:7", + ], }, - '::Beekeeping::HoneyProduction::Nectars' => { - 'Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: _)' => [ - 'packs/hive_graphql_concerns/app/public/objects/apiary.rb:7' - ] - } } ) end end - describe '#sources_with_contexts' do - it 'shows the given number of lines around each source' do + describe "#sources_with_contexts" do + it "shows the given number of lines around each source" do contexts = described_class.all.sources_with_contexts(start_offset: 1, end_offset: 0) - expect(contexts['::Backfills::BackfillPollinationCoveredPeriodDates']).to eq( - 'Backfills::BackfillPollinationCoveredPeriodDates.run!' => [ - <<~CONTEXT + expect(contexts["::Backfills::BackfillPollinationCoveredPeriodDates"]).to eq( + "Backfills::BackfillPollinationCoveredPeriodDates.run!" => [ + <<~CONTEXT, > db/data/20210309211702_backfill_pollination_covered_period_dates.rb:3 (L2..3) def up @@ -109,12 +109,12 @@ def up end RSpec.describe QueryPackwerk::Violations do - include_context 'referenced packs' + include_context "referenced packs" - describe '.where' do - it 'finds the violations of a pack with an owner' do + describe ".where" do + it "finds the violations of a pack with an owner" do expect(described_class.where(owned: true).map { |violation| violation.consuming_pack.name }).to contain_exactly( - 'packs/hive_dashboard', 'packs/apiary_reports' + "packs/hive_dashboard", "packs/apiary_reports" ) expect(described_class.where(owned: false)).to be_empty end diff --git a/spec/query_packwerk_spec.rb b/spec/query_packwerk_spec.rb index 0f6d8f5..23486b3 100644 --- a/spec/query_packwerk_spec.rb +++ b/spec/query_packwerk_spec.rb @@ -2,224 +2,224 @@ # frozen_string_literal: true RSpec.describe QueryPackwerk do - include_context 'pseudo packs' + include_context "pseudo packs" - describe '#package' do - it 'gets a package by name' do + describe "#package" do + it "gets a package by name" do expect(described_class.package(package_name)).to be_a(QueryPackwerk::Package) end - it 'gets a package by its name in packs/, as violations_for does' do - expect(described_class.package('honey_production')&.name).to eq('packs/honey_production') + it "gets a package by its name in packs/, as violations_for does" do + expect(described_class.package("honey_production")&.name).to eq("packs/honey_production") end - it 'returns nil if the package does not exist' do - expect(described_class.package('not_here')).to be_nil + it "returns nil if the package does not exist" do + expect(described_class.package("not_here")).to be_nil end end - describe '#violations_for' do - it 'gets all violations for a pack' do + describe "#violations_for" do + it "gets all violations for a pack" do violations = described_class.violations_for(package_name) expect(violations).to be_a(QueryPackwerk::Violations) expect(violations.count).not_to eq(0) end - it 'gets nothing for an empty pack' do - violations = described_class.violations_for('not_here_boss') + it "gets nothing for an empty pack" do + violations = described_class.violations_for("not_here_boss") expect(violations.count).to eq(0) end end - describe '#violation_sources_for' do - it 'gets violation sources grouped by class name' do + describe "#violation_sources_for" do + it "gets violation sources grouped by class name" do expect(described_class.violation_sources_for(package_name)).to eq( { - '::Backfills::BackfillPollinationCoveredPeriodDates' => [ + "::Backfills::BackfillPollinationCoveredPeriodDates" => [ [ - 'db/data/20210309211702_backfill_pollination_covered_period_dates.rb:3', 'Backfills::BackfillPollinationCoveredPeriodDates.run!' - ] + "db/data/20210309211702_backfill_pollination_covered_period_dates.rb:3", "Backfills::BackfillPollinationCoveredPeriodDates.run!", + ], ], - '::Mutations::HoneyProduction::SaveNectar' => [ + "::Mutations::HoneyProduction::SaveNectar" => [ [ - 'packs/hivemind_subgraph/app/lib/objects/mutation.rb:1', - 'Mutations::HoneyProduction::SaveNectar' - ] + "packs/hivemind_subgraph/app/lib/objects/mutation.rb:1", + "Mutations::HoneyProduction::SaveNectar", + ], ], - '::HoneyProductionNectar' => [ + "::HoneyProductionNectar" => [ [ - 'packs/hive_graphql_concerns/app/public/objects/apiary.rb:3', - '::HoneyProductionNectar.as_of_now.find_by(apiary_id: object.id)' - ] + "packs/hive_graphql_concerns/app/public/objects/apiary.rb:3", + "::HoneyProductionNectar.as_of_now.find_by(apiary_id: object.id)", + ], ], - '::HoneyProductionNectarPollinationInfo' => [ + "::HoneyProductionNectarPollinationInfo" => [ [ - 'packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6', - "HoneyProductionNectarPollinationInfo.\n where(apiary_id: @apiary.id).\n where.not(nectar_amount: nil).\n exists?" + "packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6", + "HoneyProductionNectarPollinationInfo.\n where(apiary_id: @apiary.id).\n where.not(nectar_amount: nil).\n exists?", ], [ - 'packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6', - "HoneyProductionNectarPollinationInfo.\n where(apiary_id: @apiary.id).\n where.not(nectar_amount: nil).\n exists?" - ] + "packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb:6", + "HoneyProductionNectarPollinationInfo.\n where(apiary_id: @apiary.id).\n where.not(nectar_amount: nil).\n exists?", + ], ], - '::Beekeeping::HoneyProduction::Nectars' => [ + "::Beekeeping::HoneyProduction::Nectars" => [ [ - 'packs/hive_graphql_concerns/app/public/objects/apiary.rb:7', - '::Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: object.id)' - ] - ] + "packs/hive_graphql_concerns/app/public/objects/apiary.rb:7", + "::Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: object.id)", + ], + ], } ) end end - describe '#violation_counts_for' do - it 'gets violation counts grouped by class name' do + describe "#violation_counts_for" do + it "gets violation counts grouped by class name" do expect(described_class.violation_counts_for(package_name)).to eq( { - '::Backfills::BackfillPollinationCoveredPeriodDates' => { - 'Backfills::BackfillPollinationCoveredPeriodDates.run!' => 1 + "::Backfills::BackfillPollinationCoveredPeriodDates" => { + "Backfills::BackfillPollinationCoveredPeriodDates.run!" => 1, + }, + "::Mutations::HoneyProduction::SaveNectar" => { + "Mutations::HoneyProduction::SaveNectar" => 1, }, - '::Mutations::HoneyProduction::SaveNectar' => { - 'Mutations::HoneyProduction::SaveNectar' => 1 + "::HoneyProductionNectar" => { + "::HoneyProductionNectar.as_of_now.find_by(apiary_id: object.id)" => 1, }, - '::HoneyProductionNectar' => { - '::HoneyProductionNectar.as_of_now.find_by(apiary_id: object.id)' => 1 + "::HoneyProductionNectarPollinationInfo" => { + "HoneyProductionNectarPollinationInfo.\n where(apiary_id: @apiary.id).\n where.not(nectar_amount: nil).\n exists?" => 2, }, - '::HoneyProductionNectarPollinationInfo' => { - "HoneyProductionNectarPollinationInfo.\n where(apiary_id: @apiary.id).\n where.not(nectar_amount: nil).\n exists?" => 2 + "::Beekeeping::HoneyProduction::Nectars" => { + "::Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: object.id)" => 1, }, - '::Beekeeping::HoneyProduction::Nectars' => { - '::Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: object.id)' => 1 - } } ) end end - describe '#anonymous_violation_sources_for' do - it 'gets violation sources grouped by class name' do + describe "#anonymous_violation_sources_for" do + it "gets violation sources grouped by class name" do expect(described_class.anonymous_violation_sources_for(package_name)).to eq( - '::Backfills::BackfillPollinationCoveredPeriodDates' => [ - 'Backfills::BackfillPollinationCoveredPeriodDates.run!' + "::Backfills::BackfillPollinationCoveredPeriodDates" => [ + "Backfills::BackfillPollinationCoveredPeriodDates.run!", ], - '::Mutations::HoneyProduction::SaveNectar' => [ - 'Mutations::HoneyProduction::SaveNectar' + "::Mutations::HoneyProduction::SaveNectar" => [ + "Mutations::HoneyProduction::SaveNectar", ], - '::HoneyProductionNectar' => [ - 'HoneyProductionNectar.as_of_now.find_by(apiary_id: _)' + "::HoneyProductionNectar" => [ + "HoneyProductionNectar.as_of_now.find_by(apiary_id: _)", ], - '::HoneyProductionNectarPollinationInfo' => [ - 'HoneyProductionNectarPollinationInfo.where(apiary_id: _).where.not(nectar_amount: _).exists?' + "::HoneyProductionNectarPollinationInfo" => [ + "HoneyProductionNectarPollinationInfo.where(apiary_id: _).where.not(nectar_amount: _).exists?", ], - '::Beekeeping::HoneyProduction::Nectars' => [ - 'Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: _)' + "::Beekeeping::HoneyProduction::Nectars" => [ + "Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: _)", ] ) end end - describe '#anonymous_violation_counts_for' do - it 'gets violation sources grouped by class name' do + describe "#anonymous_violation_counts_for" do + it "gets violation sources grouped by class name" do expect(described_class.anonymous_violation_counts_for(package_name)).to eq( { - '::Backfills::BackfillPollinationCoveredPeriodDates' => { - 'Backfills::BackfillPollinationCoveredPeriodDates.run!' => 1 + "::Backfills::BackfillPollinationCoveredPeriodDates" => { + "Backfills::BackfillPollinationCoveredPeriodDates.run!" => 1, + }, + "::Mutations::HoneyProduction::SaveNectar" => { + "Mutations::HoneyProduction::SaveNectar" => 1, }, - '::Mutations::HoneyProduction::SaveNectar' => { - 'Mutations::HoneyProduction::SaveNectar' => 1 + "::HoneyProductionNectar" => { + "HoneyProductionNectar.as_of_now.find_by(apiary_id: _)" => 1, }, - '::HoneyProductionNectar' => { - 'HoneyProductionNectar.as_of_now.find_by(apiary_id: _)' => 1 + "::HoneyProductionNectarPollinationInfo" => { + "HoneyProductionNectarPollinationInfo.where(apiary_id: _).where.not(nectar_amount: _).exists?" => 2, }, - '::HoneyProductionNectarPollinationInfo' => { - 'HoneyProductionNectarPollinationInfo.where(apiary_id: _).where.not(nectar_amount: _).exists?' => 2 + "::Beekeeping::HoneyProduction::Nectars" => { + "Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: _)" => 1, }, - '::Beekeeping::HoneyProduction::Nectars' => { - 'Beekeeping::HoneyProduction::Nectars.nectar_status_for(apiary_id: _)' => 1 - } } ) end - it 'can be given a threshold' do + it "can be given a threshold" do expect(described_class.anonymous_violation_counts_for(package_name, threshold: 3)).to eq({}) end end end RSpec.describe QueryPackwerk do - include_context 'listed references' + include_context "listed references" - describe '#references_for' do + describe "#references_for" do it "gets all references from other packs to a pack's constants" do - references = described_class.references_for('honey_production') + references = described_class.references_for("honey_production") expect(references).to be_a(QueryPackwerk::References) expect(references.count).to eq(8) end end - describe '#references_from' do + describe "#references_from" do it "gets all references from a pack to other packs' constants" do - expect(described_class.references_from('hive_dashboard').map(&:constant_name).tally).to eq( - '::HoneyProductionNectar' => 3, - '::Beekeeping::NectarSource' => 1, - '::Beekeeping::Nectars' => 1, - '::ApiaryReportCard' => 1 + expect(described_class.references_from("hive_dashboard").map(&:constant_name).tally).to eq( + "::HoneyProductionNectar" => 3, + "::Beekeeping::NectarSource" => 1, + "::Beekeeping::Nectars" => 1, + "::ApiaryReportCard" => 1 ) end - it 'takes the name of a pack outside packs/, as the root pack' do - expect(described_class.references_from('.').map(&:location)).to eq(['app/services/apiary_summary.rb:2']) + it "takes the name of a pack outside packs/, as the root pack" do + expect(described_class.references_from(".").map(&:location)).to eq(["app/services/apiary_summary.rb:2"]) end end - describe '#reload!' do - it 'runs pks again for the next query' do - described_class.references_for('honey_production') + describe "#reload!" do + it "runs pks again for the next query" do + described_class.references_for("honey_production") described_class.reload! - described_class.references_for('honey_production') + described_class.references_for("honey_production") expect(QueryPackwerk::Pks).to have_received(:list_references).twice end - it 'returns nil, which the console shows plainly, as do the reload! of each collection' do + it "returns nil, which the console shows plainly, as do the reload! of each collection" do expect(described_class.reload!).to be_nil expect([QueryPackwerk::Packages, QueryPackwerk::Violations, QueryPackwerk::References].map(&:reload!)).to eq([nil, nil, nil]) end - it 'reads the package_todo.yml files again' do - expect(described_class.todos_for('apiary_reports').count).to eq(1) + it "reads the package_todo.yml files again" do + expect(described_class.todos_for("apiary_reports").count).to eq(1) - write_package_todo(pack_name: 'packs/apiary_reports', references: {}) + write_package_todo(pack_name: "packs/apiary_reports", references: {}) described_class.reload! - expect(described_class.todos_for('apiary_reports').count).to eq(0) + expect(described_class.todos_for("apiary_reports").count).to eq(0) end - it 'finds a pack added since, which pks lists references from' do - described_class.references_for('honey_production') + it "finds a pack added since, which pks lists references from" do + described_class.references_for("honey_production") - write_package_yml('packs/wax_reports') - write_file('packs/wax_reports/app/services/wax_report.rb', <<~RUBY) + write_package_yml("packs/wax_reports") + write_file("packs/wax_reports/app/services/wax_report.rb", <<~RUBY) class WaxReport def nectar_count = HoneyProductionNectar.count end RUBY listed_references << { - 'file' => 'packs/wax_reports/app/services/wax_report.rb', 'line' => 2, 'column' => 21, - 'constant_name' => '::HoneyProductionNectar', - 'referencing_pack_name' => 'packs/wax_reports', 'defining_pack_name' => 'packs/honey_production', - 'violations' => [ - { 'violation_type' => 'dependency', 'strict' => false, 'recorded' => false }, - { 'violation_type' => 'privacy', 'strict' => false, 'recorded' => false } - ] + "file" => "packs/wax_reports/app/services/wax_report.rb", "line" => 2, "column" => 21, + "constant_name" => "::HoneyProductionNectar", + "referencing_pack_name" => "packs/wax_reports", "defining_pack_name" => "packs/honey_production", + "violations" => [ + { "violation_type" => "dependency", "strict" => false, "recorded" => false }, + { "violation_type" => "privacy", "strict" => false, "recorded" => false }, + ], } described_class.reload! - expect(described_class.references_for('honey_production').consumers).to include('packs/wax_reports' => 1) + expect(described_class.references_for("honey_production").consumers).to include("packs/wax_reports" => 1) end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 89de8c9..d1cc0cd 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,19 +1,19 @@ # typed: false # frozen_string_literal: true -require 'pry' -require 'query_packwerk' -require_relative 'support/pack_helpers' -require_relative 'support/pseudo_packs' -require_relative 'support/referenced_packs' -require 'rubocop/rspec/support' -require 'packs/rspec/support' -require 'packs-specification' +require "pry" +require "query_packwerk" +require_relative "support/pack_helpers" +require_relative "support/pseudo_packs" +require_relative "support/referenced_packs" +require "rubocop/rspec/support" +require "packs/rspec/support" +require "packs-specification" RSpec.configure do |config| config.include PackHelpers # Enable flags like --only-failures and --next-failure - config.example_status_persistence_file_path = '.rspec_status' + config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! diff --git a/spec/support/pack_helpers.rb b/spec/support/pack_helpers.rb index fa056aa..91a07b3 100644 --- a/spec/support/pack_helpers.rb +++ b/spec/support/pack_helpers.rb @@ -2,28 +2,34 @@ # frozen_string_literal: true module PackHelpers - def write_package_yml(name, enforce_privacy: true, enforce_dependencies: true, dependencies: [], owner: nil, - config: {}) + def write_package_yml( + name, + enforce_privacy: true, + enforce_dependencies: true, + dependencies: [], + owner: nil, + config: {} + ) package_config = { - 'dependencies' => dependencies, - 'enforce_privacy' => enforce_privacy, - 'enforce_dependencies' => enforce_dependencies, - 'metadata' => { 'owner' => owner } + "dependencies" => dependencies, + "enforce_privacy" => enforce_privacy, + "enforce_dependencies" => enforce_dependencies, + "metadata" => { "owner" => owner }, } package_config = package_config.merge(config) - package_config.delete('enforce_privacy') if enforce_privacy.nil? + package_config.delete("enforce_privacy") if enforce_privacy.nil? write_pack(name, package_config) end def write_pack_with_violations(pack_name:, violations:) write_package_yml(pack_name) - write_violations(pack_name: pack_name, violations: violations) + write_violations(pack_name:, violations:) end def write_violations(pack_name:, violations:) - expected_violation_keys = %i[class_name files to_package_name type] + expected_violation_keys = %i(class_name files to_package_name type) package_todo = Hash.new do |references, violated_pack_name| references[violated_pack_name] = Hash.new do |constants_violated, constant_name| @@ -40,12 +46,12 @@ def write_violations(pack_name:, violations:) constant_name, files, pack_name, type = violation.slice(:class_name, :files, :to_package_name, :type).values package_todo[pack_name][constant_name].merge!( - 'files' => files, - 'violations' => [type] + "files" => files, + "violations" => [type] ) { |_k, old, current| (old + current).uniq } end - write_package_todo(pack_name: pack_name, references: package_todo) + write_package_todo(pack_name:, references: package_todo) end # packs/authorization: diff --git a/spec/support/pseudo_packs.rb b/spec/support/pseudo_packs.rb index eff709c..8993aa7 100644 --- a/spec/support/pseudo_packs.rb +++ b/spec/support/pseudo_packs.rb @@ -1,7 +1,7 @@ # typed: false # frozen_string_literal: true -RSpec.shared_context 'pseudo packs' do +RSpec.shared_context "pseudo packs" do before do write_pack_with_violations(pack_name: package_name, violations: raw_violations) violating_files.each do |file_name, file_contents| @@ -12,47 +12,47 @@ let(:raw_violations) do [ { - class_name: '::Mutations::HoneyProduction::SaveNectar', - files: ['packs/hivemind_subgraph/app/lib/objects/mutation.rb'], - to_package_name: 'packs/honey_production', - type: 'privacy' + class_name: "::Mutations::HoneyProduction::SaveNectar", + files: ["packs/hivemind_subgraph/app/lib/objects/mutation.rb"], + to_package_name: "packs/honey_production", + type: "privacy", }, { - class_name: '::HoneyProductionNectar', - files: ['packs/hive_graphql_concerns/app/public/objects/apiary.rb'], - to_package_name: 'packs/honey_production', - type: 'privacy' + class_name: "::HoneyProductionNectar", + files: ["packs/hive_graphql_concerns/app/public/objects/apiary.rb"], + to_package_name: "packs/honey_production", + type: "privacy", }, { - class_name: '::Beekeeping::HoneyProduction::Nectars', - files: ['packs/hive_graphql_concerns/app/public/objects/apiary.rb'], - to_package_name: 'packs/honey_production', - type: 'privacy' + class_name: "::Beekeeping::HoneyProduction::Nectars", + files: ["packs/hive_graphql_concerns/app/public/objects/apiary.rb"], + to_package_name: "packs/honey_production", + type: "privacy", }, { - class_name: '::HoneyProductionNectarPollinationInfo', - files: ['packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb'], - to_package_name: 'packs/honey_production', - type: 'dependency' + class_name: "::HoneyProductionNectarPollinationInfo", + files: ["packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb"], + to_package_name: "packs/honey_production", + type: "dependency", }, { - class_name: '::HoneyProductionNectarPollinationInfo', - files: ['packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb'], - to_package_name: 'packs/honey_production', - type: 'privacy' + class_name: "::HoneyProductionNectarPollinationInfo", + files: ["packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb"], + to_package_name: "packs/honey_production", + type: "privacy", }, { - class_name: '::Backfills::BackfillPollinationCoveredPeriodDates', - files: ['db/data/20210309211702_backfill_pollination_covered_period_dates.rb'], - to_package_name: 'packs/honey_production', - type: 'privacy' - } + class_name: "::Backfills::BackfillPollinationCoveredPeriodDates", + files: ["db/data/20210309211702_backfill_pollination_covered_period_dates.rb"], + to_package_name: "packs/honey_production", + type: "privacy", + }, ] end let(:violating_files) do cache = {} - cache['packs/hivemind_subgraph/app/lib/objects/mutation.rb'] = <<~RUBY + cache["packs/hivemind_subgraph/app/lib/objects/mutation.rb"] = <<~RUBY field :save_honey_production_nectar, mutation: Mutations::HoneyProduction::SaveNectar RUBY - cache['packs/hive_graphql_concerns/app/public/objects/apiary.rb'] = <<~RUBY + cache["packs/hive_graphql_concerns/app/public/objects/apiary.rb"] = <<~RUBY def honey_production_nectar # TODO: Update this to use Beekeeping::HoneyProduction::Nectars.nectar_status_for ::HoneyProductionNectar.as_of_now.find_by(apiary_id: object.id) @@ -67,7 +67,7 @@ def has_processed_honey_production_nectar end RUBY - cache['packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb'] = <<~RUBY + cache["packs/beehive_health_metrics/app/controllers/worker_bee_efficiency_controller.rb"] = <<~RUBY def claimed_hpn # Apiary reported receiving HPN nectar in most recent hive survey has_responded_to_survey_and_received_nectar = Hive::Survey.joins(:hive_questions). @@ -82,7 +82,7 @@ def claimed_hpn end RUBY - cache['db/data/20210309211702_backfill_pollination_covered_period_dates.rb'] = <<~RUBY + cache["db/data/20210309211702_backfill_pollination_covered_period_dates.rb"] = <<~RUBY class BackfillPollinationCoveredPeriodDates < ActiveRecord::Migration[6.0] def up Backfills::BackfillPollinationCoveredPeriodDates.run! @@ -97,5 +97,5 @@ def down cache end - let(:package_name) { 'packs/honey_production' } + let(:package_name) { "packs/honey_production" } end diff --git a/spec/support/referenced_packs.rb b/spec/support/referenced_packs.rb index de2fdf7..5917b16 100644 --- a/spec/support/referenced_packs.rb +++ b/spec/support/referenced_packs.rb @@ -5,7 +5,7 @@ # lists: allowed or not, recorded in a package_todo.yml or not, by a relative # name, through an association, in ERB, after multibyte characters, and to a # pack without an owner. -RSpec.shared_context 'referenced packs' do +RSpec.shared_context "referenced packs" do # QueryPackwerk keeps the packs it finds, so it'd keep these from, or for, # specs that write other packs around do |example| @@ -16,35 +16,35 @@ end before do - write_file('packwerk.yml', "cache: false\n") - write_package_yml('.', enforce_privacy: false, enforce_dependencies: false) - write_package_yml('packs/honey_production', config: { 'owner' => 'Honey' }) - write_package_yml('packs/hive_dashboard', dependencies: ['packs/honey_production']) - write_package_yml('packs/apiary_reports') + write_file("packwerk.yml", "cache: false\n") + write_package_yml(".", enforce_privacy: false, enforce_dependencies: false) + write_package_yml("packs/honey_production", config: { "owner" => "Honey" }) + write_package_yml("packs/hive_dashboard", dependencies: ["packs/honey_production"]) + write_package_yml("packs/apiary_reports") write_package_todo( - pack_name: 'packs/hive_dashboard', + pack_name: "packs/hive_dashboard", references: { - 'packs/honey_production' => { - '::HoneyProductionNectar' => { - 'violations' => ['privacy'], - 'files' => [ - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb', - 'packs/hive_dashboard/app/views/apiaries/show.html.erb' - ] - } - } + "packs/honey_production" => { + "::HoneyProductionNectar" => { + "violations" => ["privacy"], + "files" => [ + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb", + "packs/hive_dashboard/app/views/apiaries/show.html.erb", + ], + }, + }, } ) write_package_todo( - pack_name: 'packs/apiary_reports', + pack_name: "packs/apiary_reports", references: { - 'packs/honey_production' => { - '::HoneyProductionNectar' => { - 'violations' => ['dependency'], - 'files' => ['packs/apiary_reports/app/services/apiary_report.rb'] - } - } + "packs/honey_production" => { + "::HoneyProductionNectar" => { + "violations" => ["dependency"], + "files" => ["packs/apiary_reports/app/services/apiary_report.rb"], + }, + }, } ) @@ -53,24 +53,24 @@ let(:app_files) do { - 'packs/honey_production/app/models/honey_production_nectar.rb' => <<~RUBY, + "packs/honey_production/app/models/honey_production_nectar.rb" => <<~RUBY, class HoneyProductionNectar < ApplicationRecord end RUBY - 'packs/honey_production/app/models/beekeeping/nectar_source.rb' => <<~RUBY, + "packs/honey_production/app/models/beekeeping/nectar_source.rb" => <<~RUBY, module Beekeeping class NectarSource < ApplicationRecord end end RUBY - 'packs/honey_production/app/public/beekeeping/nectars.rb' => <<~RUBY, + "packs/honey_production/app/public/beekeeping/nectars.rb" => <<~RUBY, module Beekeeping module Nectars def self.status_for(apiary_id:); end end end RUBY - 'packs/hive_dashboard/app/services/beekeeping/apiary_status.rb' => <<~RUBY, + "packs/hive_dashboard/app/services/beekeeping/apiary_status.rb" => <<~RUBY, module Beekeeping class ApiaryStatus def nectar @@ -87,33 +87,33 @@ def status end end RUBY - 'packs/hive_dashboard/app/models/hive.rb' => <<~RUBY, + "packs/hive_dashboard/app/models/hive.rb" => <<~RUBY, class Hive < ApplicationRecord has_many :honey_production_nectars, dependent: :destroy end RUBY - 'packs/hive_dashboard/app/services/report_link.rb' => <<~RUBY, + "packs/hive_dashboard/app/services/report_link.rb" => <<~RUBY, class ReportLink def card = ApiaryReportCard.new end RUBY - 'packs/hive_dashboard/app/views/apiaries/show.html.erb' => <<~ERB, + "packs/hive_dashboard/app/views/apiaries/show.html.erb" => <<~ERB, <% if HoneyProductionNectar.as_of_now.exists?(apiary_id: @apiary.id) %><%= HoneyProductionNectar.as_of_now.find_by(apiary_id: @apiary.id).volume %>
<% end %> ERB - 'packs/apiary_reports/app/services/apiary_report.rb' => <<~'RUBY', + "packs/apiary_reports/app/services/apiary_report.rb" => <<~'RUBY', class ApiaryReport def nectar_count = HoneyProductionNectar.count def title = "Récolte 🍯 #{HoneyProductionNectar.model_name.human}" end RUBY - 'packs/apiary_reports/app/public/apiary_report_card.rb' => <<~RUBY, + "packs/apiary_reports/app/public/apiary_report_card.rb" => <<~RUBY, class ApiaryReportCard end RUBY - 'app/services/apiary_summary.rb' => <<~RUBY + "app/services/apiary_summary.rb" => <<~RUBY, class ApiarySummary def status = Beekeeping::Nectars.status_for(apiary_id: 1) end @@ -124,7 +124,7 @@ def status = Beekeeping::Nectars.status_for(apiary_id: 1) # What `pks list-references` prints for the app. spec/query_packwerk/pks_spec.rb # checks this against pks itself, when it's installed. let(:listed_references) do - JSON.parse(<<~JSON).fetch('references') + JSON.parse(<<~JSON).fetch("references") { "references": [ {"file": "app/services/apiary_summary.rb", "line": 2, "column": 15, "constant_name": "::Beekeeping::Nectars", "referencing_pack_name": ".", "defining_pack_name": "packs/honey_production", "violations": []}, @@ -143,8 +143,8 @@ def status = Beekeeping::Nectars.status_for(apiary_id: 1) end # Stands in for pks, with what it lists for the referenced packs -RSpec.shared_context 'listed references' do - include_context 'referenced packs' +RSpec.shared_context "listed references" do + include_context "referenced packs" before do allow(QueryPackwerk::Pks).to receive(:list_references).and_return(listed_references)