diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84b8540..4516082 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,9 @@ jobs: - name: Exercise architecture presets run: bundle exec ruby scripts/check_presets.rb + - name: Exercise named method calls + run: bundle exec ruby scripts/check_named_calls.rb + - name: Exercise documented library examples run: bundle exec ruby scripts/check_documentation_examples.rb @@ -179,6 +182,7 @@ jobs: ruby scripts/check_analysis_diagnostics.rb ruby scripts/check_baselines.rb ruby scripts/check_presets.rb + ruby scripts/check_named_calls.rb ruby scripts/check_documentation_examples.rb ruby scripts/check_cli.rb ruby -e " diff --git a/API.md b/API.md index 6fe17c1..7104d31 100644 --- a/API.md +++ b/API.md @@ -139,6 +139,30 @@ dense graphs can have exponentially many results. Scope cycle rules to meaningfu +### Named method calls (unreleased) + +Use `should_not.contain_calls_named(:delete_all)` or pass a nonempty array of exact names. The +optional `ArchUnit::NamedCallOptions.new(receiver: :bare)` limits the rule to calls with no +explicit receiver. The default `:any` includes explicit `self`, other receivers, and safe +navigation. The positive mood is not supported. + +This is a syntactic check. A call to a locally defined method with the same name also matches; +Prism distinguishes method definitions, comments, strings, and local variable reads from calls. +Ordinary operators and attribute/index assignments are included when parsed as explicit calls. +Implicit sends in compound assignments, `receiver.()`, and targets of `send` or `public_send` +are not inferred. Neither alias expansion nor runtime receiver types are checked. + +CLI violations add a `call` object with `file`, `name`, `receiver` (`bare`, `self` or +`explicit`), `safe_navigation`, and one-based `line` and byte `column` of the call token. +The `source_calls` analysis scope has no dependency counts. A baseline matches occurrences by +file, method name, receiver form and safe-navigation flag, not receiver identity or line number. +It accepts at most the previously recorded number of matching calls. + +Named-call rules share a cached source inventory per project and effective source exclusions. They +don't change or reuse the dependency graph: a mixed graph and call suite has separate source passes. +Use `clear_cache: true` or `ArchUnit.clear_graph_cache` after source edits in a long-lived process. +Included parse errors fail the check, even when the malformed file isn't selected by the rule. + ## Layer rules Use `ArchUnit.project_layers(project_locator = nil)` to name architectural layers and then declare diff --git a/CHANGELOG.md b/CHANGELOG.md index 447aeed..5edb884 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 1.1.1 (unreleased) +- Add file-scoped named method-call restrictions, with an optional bare-call mode, source + coordinates in test and CLI output, and explicit occurrence-based baseline support. + - Add opt-in static Rails association dependencies for explicit literal `class_name` on supported model-body macros, with evidence, isolated baselines and CLI uncertainty counts. No Rails boot, automatic inflection, or change to existing default graphs. diff --git a/GUIDE.md b/GUIDE.md index 9716687..5d005a6 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -171,6 +171,18 @@ rule = ArchUnit.project_files.in_folder('app/services/**') ) ~~~ +### Keep write calls out of query files (unreleased) + +~~~ruby +rule = ArchUnit.project_files.in_path('app/queries/**') + .should_not.contain_calls_named(%i[delete_all destroy_all]) +expect(rule).to pass +~~~ + +`store.read` is allowed; `store.delete_all` is reported at the written call site. This also +matches the same spelling on unrelated receivers, and does not infer `send(:delete_all)`. +Use it for a naming policy in a known part of your own code, not as proof of read-only behavior. + ### Layer Dependencies Named layers express an allowlist or blocklist over groups of files: diff --git a/benchmark/semantic/cases.json b/benchmark/semantic/cases.json index 26f71da..f981151 100644 --- a/benchmark/semantic/cases.json +++ b/benchmark/semantic/cases.json @@ -2,12 +2,14 @@ { "name": "explicit_constant_forbidden_method", "source": "module Api; class Request; def call = ::Db::Store.delete_all; end; end", + "expected_named_calls": 1, "expected_direct_db": 1, "comparator_policy": "method_name" }, { "name": "explicit_constant_allowed_method", "source": "module Api; class Request; def call = ::Db::Store.read; end; end", + "expected_named_calls": 0, "expected_direct_db": 1, "comparator_policy": "method_name" }, @@ -20,6 +22,7 @@ { "name": "dynamic_parameter_receiver", "source": "module Api; class Request; def call(store) = store.delete_all; end; end", + "expected_named_calls": 1, "expected_direct_db": 0, "comparator_policy": "method" }, diff --git a/benchmark/semantic/probes.rb b/benchmark/semantic/probes.rb index 6db6a0d..6a1b450 100644 --- a/benchmark/semantic/probes.rb +++ b/benchmark/semantic/probes.rb @@ -54,12 +54,23 @@ def library_facts(root, specification) options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants) graph = ArchUnit::Extraction.extract_graph(root, options:, profile:) count = boundary_count(root, specification, options) + calls = named_call_count(root, specification) { name: specification['name'], direct_file_boundary_violations: count, - counters: profile.counters, syntax: syntax_facts(specification), + named_call_violations: calls, counters: profile.counters, + syntax: syntax_facts(specification), metric_method_fields: ArchUnit::MetricMethodInfo.members, has_semantic_method_edges: graph.any? { |edge| edge.respond_to?(:resolved_method) } } end + def named_call_count(root, specification) + file = ArchUnit.project_files(root).in_path('app/api/**') + count = file.should_not.contain_calls_named(:delete_all).check.length + return count unless specification.key?('expected_named_calls') + return count if specification['expected_named_calls'] == count + + raise "unexpected named call count: #{specification['name']}" + end + def boundary_count(root, specification, options) rule = ArchUnit.project_files(root).in_path('app/api/**') .should_not.depend_on_files.in_path('app/db/**') diff --git a/lib/archunit.rb b/lib/archunit.rb index 3d7bffb..eecacf6 100644 --- a/lib/archunit.rb +++ b/lib/archunit.rb @@ -52,6 +52,8 @@ module ArchUnit Violation = Common::Assertion::Violation EmptyTestViolation = Common::Assertion::EmptyTestViolation CheckOptions = Common::FluentApi::CheckOptions + NamedCallOptions = Files::FluentApi::NamedCallOptions + NamedCallViolation = Files::Assertion::NamedCallViolation Checkable = Common::FluentApi::Checkable ImportKind = Common::Extraction::ImportKind Edge = Common::Extraction::Edge diff --git a/lib/archunit/cli/analysis_text.rb b/lib/archunit/cli/analysis_text.rb index 04f43e3..02365ba 100644 --- a/lib/archunit/cli/analysis_text.rb +++ b/lib/archunit/cli/analysis_text.rb @@ -15,7 +15,7 @@ def self.write(analysis, out) end def self.write_scope(scope, out) - mode = scope[:dependency_analysis] || 'source metrics (dependency analysis unavailable)' + mode = scope[:dependency_analysis] || source_scope(scope) out.puts(" Scope #{scope[:id]}: #{scope[:project_root]} — #{mode}; #{scope[:status]}") counts = scope[:counters].map do |name, value| "#{name}=#{value.nil? ? 'unavailable' : value}" @@ -23,6 +23,12 @@ def self.write_scope(scope, out) out.puts(" #{counts.join(', ')}; cache_hits=#{scope[:cache_hits]}") end private_class_method :write_scope + + def self.source_scope(scope) + name = scope[:kind] == 'source_calls' ? 'source calls' : 'source metrics' + "#{name} (dependency analysis unavailable)" + end + private_class_method :source_scope end end end diff --git a/lib/archunit/cli/baseline_identity.rb b/lib/archunit/cli/baseline_identity.rb index 37f1b7c..1630fd2 100644 --- a/lib/archunit/cli/baseline_identity.rb +++ b/lib/archunit/cli/baseline_identity.rb @@ -12,6 +12,7 @@ module BaselineIdentity Files::Assertion::FileDependencyViolation => :dependency, Files::Assertion::ExternalModuleDependencyViolation => :dependency, Files::Assertion::FilePatternViolation => :pattern, + Files::Assertion::NamedCallViolation => :named_call, Files::Assertion::CycleViolation => :cycle, Layers::Assertion::LayerDependencyViolation => :layer, Slices::Assertion::SliceDependencyViolation => :slice, @@ -51,6 +52,12 @@ def self.pattern(value) 'negated' => value.negated? } end + def self.named_call(value) + call = value.call + { 'file' => identifier(call.file), 'name' => call.name, 'receiver' => call.receiver.to_s, + 'safe_navigation' => call.safe_navigation } + end + def self.filter(value) [value.regexp.source, value.regexp.options, value.target.to_s, value.matching.to_s, value.exclusions.map { |item| filter(item) }.sort_by { |item| JSON.generate(item) }] @@ -78,8 +85,8 @@ def self.identifier(value) normalized end - private_class_method :dependency, :edge, :layer, :slice, :pattern, :filter, :cycle, - :threshold, :identifier + private_class_method :dependency, :edge, :layer, :slice, :pattern, :named_call, :filter, + :cycle, :threshold, :identifier end end end diff --git a/lib/archunit/cli/report.rb b/lib/archunit/cli/report.rb index b31fe78..25909e6 100644 --- a/lib/archunit/cli/report.rb +++ b/lib/archunit/cli/report.rb @@ -38,7 +38,7 @@ def add_rule(rule, violations: nil, analysis: nil) payload[:rules] << { name: rule.name, rationale: rule.checkable.rationale, status: rule_status(violations), analysis: analysis || { status: 'unavailable', scope_ids: [] }, - violations: (violations || []).map { |violation| violation_payload(violation) } + violations: violation_payloads(violations) } end @@ -86,6 +86,15 @@ def violation_payload(violation) { type: violation.class.name, message: formatted.message, details: formatted.details } end + def violation_payloads(violations) + (violations || []).map do |violation| + result = violation_payload(violation) + named_call = violation.is_a?(Files::Assertion::NamedCallViolation) + result[:call] = violation.call.to_h if named_call + result + end + end + def write_text(out) write_header(out) write_notice(out) diff --git a/lib/archunit/common/extraction/call_site.rb b/lib/archunit/common/extraction/call_site.rb new file mode 100644 index 0000000..aabac5a --- /dev/null +++ b/lib/archunit/common/extraction/call_site.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +module ArchUnit + module Common + module Extraction + # A direct call as written in Ruby source, without inferred receiver type. + CallSite = Data.define(:file, :name, :receiver, :safe_navigation, :line, :column) + end + end +end diff --git a/lib/archunit/extraction/analysis_snapshot.rb b/lib/archunit/extraction/analysis_snapshot.rb index 41a65af..eb1d5ba 100644 --- a/lib/archunit/extraction/analysis_snapshot.rb +++ b/lib/archunit/extraction/analysis_snapshot.rb @@ -23,9 +23,9 @@ def self.graph(root, patterns, options, counters: nil, status: 'analyzed') build(root, patterns, settings, graph_counters(options, counters), status) end - def self.source(discovery, count: nil, status: 'analyzed') + def self.source(discovery, count: nil, status: 'analyzed', kind: 'source_metrics') settings = { - kind: 'source_metrics', dependency_analysis: nil, rails_imports: nil, load_paths: nil + kind:, dependency_analysis: nil, rails_imports: nil, load_paths: nil } counters = COUNTERS.to_h { |key| [key, key == :source_files ? count : nil] } build(discovery.root, discovery.patterns, settings, counters, status) diff --git a/lib/archunit/extraction/extract_graph.rb b/lib/archunit/extraction/extract_graph.rb index ca094df..a8933f8 100644 --- a/lib/archunit/extraction/extract_graph.rb +++ b/lib/archunit/extraction/extract_graph.rb @@ -16,6 +16,7 @@ require_relative 'analysis_observer' require_relative 'graph_assembly' require_relative 'graph_views' +require_relative 'named_call_analysis' module ArchUnit # Assembles the normalized dependency graph for a Ruby project. @@ -54,6 +55,7 @@ def extract_graph_entry( def clear_graph_cache GRAPH_CACHE_MUTEX.synchronize { graph_cache.clear } + clear_named_calls nil end diff --git a/lib/archunit/extraction/named_call_analysis.rb b/lib/archunit/extraction/named_call_analysis.rb new file mode 100644 index 0000000..b772781 --- /dev/null +++ b/lib/archunit/extraction/named_call_analysis.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require_relative 'analysis_observer' +require_relative 'analysis_snapshot' +require_relative 'enumerate_source_files' +require_relative 'extract_imports' +require_relative 'locate_project' +require_relative 'named_call_visitor' + +module ArchUnit + # Ruby-specific extraction of source facts for file policies. + module Extraction + # Independent, on-demand source facts; graph-only checks never collect or cache them. + NamedCalls = Data.define(:by_file, :snapshot) + NAMED_CALL_MUTEX = Mutex.new + private_constant :NamedCalls, :NAMED_CALL_MUTEX + + module_function + + # @api private + def extract_named_calls(locator, options:) + root = Pathname.new(locate_project(locator)) + patterns = resolve_project_exclude_patterns( + root, nil, source_exclusions: options.source_exclusions + ) + entry, cache_hit = fetch_named_calls(root, patterns.sort.freeze, options) + AnalysisObserver.record(entry.snapshot, cache_hit:) + entry.by_file + end + + def clear_named_calls + NAMED_CALL_MUTEX.synchronize { @named_call_cache&.clear } + end + private_class_method :clear_named_calls + + def fetch_named_calls(root, patterns, options) + key = [root.to_s, patterns] + NAMED_CALL_MUTEX.synchronize do + named_call_cache.delete(key) if options.clear_cache? + entry = named_call_cache[key] + return [entry, true] if entry + + [named_call_cache[key] = build_named_calls(root, patterns), false] + end + rescue StandardError + AnalysisObserver.record(call_snapshot(root, patterns, nil, 'error')) + raise + end + private_class_method :fetch_named_calls + + def build_named_calls(root, patterns) + files = enumerate_source_files_with_patterns(root, patterns) + by_file = files.to_h { |file| [file, calls_in_file(root, file)] }.freeze + NamedCalls.new(by_file:, snapshot: call_snapshot(root, patterns, files.length, 'analyzed')) + end + private_class_method :build_named_calls + + def calls_in_file(root, file) + visitor = NamedCallVisitor.new(file) + visitor.visit(parse_source(root.join(file), nil).value) + visitor.calls.sort_by { |call| [call.line, call.column] }.freeze + end + private_class_method :calls_in_file + + def call_snapshot(root, patterns, count, status) + discovery = SourceDiscovery.new(root:, patterns:, files: []) + AnalysisSnapshot.source(discovery, count:, status:, kind: 'source_calls') + end + private_class_method :call_snapshot + + def named_call_cache + @named_call_cache ||= {} + end + private_class_method :named_call_cache + end +end diff --git a/lib/archunit/extraction/named_call_visitor.rb b/lib/archunit/extraction/named_call_visitor.rb new file mode 100644 index 0000000..91cbb77 --- /dev/null +++ b/lib/archunit/extraction/named_call_visitor.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +require 'prism' +require_relative '../common/extraction/call_site' + +module ArchUnit + module Extraction + # Collects syntactic calls. Generated and dynamically dispatched names are not inferred. + class NamedCallVisitor < Prism::Visitor + attr_reader :calls + + def initialize(file) + super() + @file = file + @calls = [] + end + + def visit_call_node(node) + @calls << call_site(node) if node.message_loc + super + end + + private + + def call_site(node) + location = node.message_loc + Common::Extraction::CallSite.new( + file: @file, name: node.name.to_s.encode(Encoding::UTF_8).freeze, + receiver: receiver_form(node.receiver), safe_navigation: node.safe_navigation?, + line: location.start_line, column: location.start_column + 1 + ) + end + + def receiver_form(receiver) + return :bare if receiver.nil? + + receiver.is_a?(Prism::SelfNode) ? :self : :explicit + end + end + private_constant :NamedCallVisitor + end +end diff --git a/lib/archunit/files/assertion/named_calls.rb b/lib/archunit/files/assertion/named_calls.rb new file mode 100644 index 0000000..85dcaf7 --- /dev/null +++ b/lib/archunit/files/assertion/named_calls.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +require_relative '../../common/assertion/violation' +require_relative '../../common/extraction/call_site' + +module ArchUnit + module Files + # Rules and violations over already extracted call sites. + module Assertion + # One forbidden direct call site, with its coordinates and receiver form. + class NamedCallViolation < Common::Assertion::Violation + attr_reader :call + + def initialize(call:) + unless call.is_a?(Common::Extraction::CallSite) + raise ArgumentError, 'call must be a CallSite' + end + + @call = call + super() + end + + def ==(other) + other.is_a?(self.class) && call == other.call + end + alias eql? == + + def hash + [self.class, call].hash + end + end + + module_function + + def gather_named_call_violations(calls, names, receiver:) + calls.filter_map do |call| + next unless names.include?(call.name) && (receiver == :any || call.receiver == :bare) + + NamedCallViolation.new(call:) + end + end + end + end +end diff --git a/lib/archunit/files/fluentapi/file_rule_support.rb b/lib/archunit/files/fluentapi/file_rule_support.rb index f5b4896..acb3159 100644 --- a/lib/archunit/files/fluentapi/file_rule_support.rb +++ b/lib/archunit/files/fluentapi/file_rule_support.rb @@ -19,6 +19,13 @@ def selected_nodes(views, filters) ) end + def selected_paths(paths, filters) + selected = paths.select do |path| + Common::PatternMatching.matches_all_patterns?(path, filters) + end + Common::Logging::Inspection.selection('selected file', selected) { |path| path } + end + def matching_nodes(nodes, filters) nodes.select do |node| Common::PatternMatching.matches_all_patterns?(node.label, filters) diff --git a/lib/archunit/files/fluentapi/named_call_condition.rb b/lib/archunit/files/fluentapi/named_call_condition.rb new file mode 100644 index 0000000..f8a0384 --- /dev/null +++ b/lib/archunit/files/fluentapi/named_call_condition.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +require_relative '../../common/fluentapi/checkable' +require_relative '../../extraction/named_call_analysis' +require_relative '../assertion/named_calls' +require_relative 'file_rule_support' +require_relative 'named_call_options' + +module ArchUnit + module Files + module FluentApi + # Executable file rule forbidding named direct calls, with no runtime dispatch claims. + class NamedCallCondition + include Common::FluentApi::Checkable + + attr_reader :project_locator, :filters, :names, :call_options + + def initialize(mood, names, call_options:) + @project_locator = mood.project_locator + @filters = mood.filters + @names = immutable_names(names) + @call_options = NamedCallOptions.resolve(call_options) + freeze + end + + private + + def immutable_names(names) + entries = names.is_a?(Array) ? names : [names] + raise ArgumentError, 'provide at least one method name' if entries.empty? + + entries.to_set { |value| method_name(value) }.freeze + end + + def method_name(value) + if (value.is_a?(String) || value.is_a?(Symbol)) && !value.to_s.strip.empty? + return value.to_s.encode(Encoding::UTF_8).freeze + end + + raise ArgumentError, 'method names must be non-blank Strings or Symbols' + end + + def perform_check(options) + inventory = ArchUnit::Extraction.extract_named_calls(project_locator, options:) + paths = FileRuleSupport.selected_paths(inventory.keys, filters) + empty = empty_test_violation(paths, filters:, negated: true, options:) + return empty if empty + + paths.flat_map do |path| + Assertion.gather_named_call_violations(inventory.fetch(path), names, + receiver: call_options.receiver) + end + end + end + end + end +end diff --git a/lib/archunit/files/fluentapi/named_call_options.rb b/lib/archunit/files/fluentapi/named_call_options.rb new file mode 100644 index 0000000..9727f80 --- /dev/null +++ b/lib/archunit/files/fluentapi/named_call_options.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module ArchUnit + module Files + module FluentApi + # Controls whether a named-call restriction considers all receiver forms or only bare calls. + NamedCallOptions = Data.define(:receiver) do + # @param receiver [Symbol] :any or :bare (excluding every explicit receiver, even self) + def initialize(receiver: :any) + unless %i[any bare].include?(receiver) + raise ArgumentError, 'receiver must be :any or :bare' + end + + super + end + + def self.resolve(options) + return new if options.nil? + return options if options.is_a?(self) + + raise ArgumentError, 'options must be a NamedCallOptions value or nil' + end + end + end + end +end diff --git a/lib/archunit/files/fluentapi/negated_match_pattern_file_condition_builder.rb b/lib/archunit/files/fluentapi/negated_match_pattern_file_condition_builder.rb index c35b00f..65e3003 100644 --- a/lib/archunit/files/fluentapi/negated_match_pattern_file_condition_builder.rb +++ b/lib/archunit/files/fluentapi/negated_match_pattern_file_condition_builder.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative 'match_pattern_file_condition_builder' +require_relative 'named_call_condition' module ArchUnit module Files @@ -10,6 +11,14 @@ class NegatedMatchPatternFileConditionBuilder < MatchPatternFileConditionBuilder def initialize(scope) super(scope, negated: true) end + + # Forbids direct syntactic calls by method name in the selected files. + # @param names [String, Symbol, Array] + # @param options [NamedCallOptions, nil] + # @return [NamedCallCondition] + def contain_calls_named(names, options = nil) + NamedCallCondition.new(self, names, call_options: options) + end end end end diff --git a/lib/archunit/testing/named_call_formatter.rb b/lib/archunit/testing/named_call_formatter.rb new file mode 100644 index 0000000..d672b1e --- /dev/null +++ b/lib/archunit/testing/named_call_formatter.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require_relative 'test_violation' + +module ArchUnit + module Testing + # Presents precise source coordinates without claiming what Ruby dispatches at runtime. + module NamedCallFormatter + private + + def named_call(violation) + call = violation.call + TestViolation.new( + message: "Forbidden method call '#{call.name}'", + details: "#{call.file}:#{call.line}:#{call.column} (#{call.receiver} receiver)." + ) + end + end + end +end diff --git a/lib/archunit/testing/violation_factory.rb b/lib/archunit/testing/violation_factory.rb index b6f7f40..f9d3be1 100644 --- a/lib/archunit/testing/violation_factory.rb +++ b/lib/archunit/testing/violation_factory.rb @@ -7,6 +7,7 @@ require_relative '../files/assertion/depend_on_external_modules' require_relative '../files/assertion/depend_on_files' require_relative '../files/assertion/matching_files' +require_relative '../files/assertion/named_calls' require_relative '../layers/assertion/layer_dependency_violation' require_relative '../metrics/assertion/custom_metric' require_relative '../metrics/assertion/metric_predicate' @@ -15,6 +16,7 @@ require_relative '../slices/assertion/slice_dependency_violation' require_relative 'layer_violation_formatter' require_relative 'metric_violation_formatter' +require_relative 'named_call_formatter' require_relative 'slice_violation_formatter' require_relative 'test_violation' @@ -25,6 +27,7 @@ module Testing class ViolationFactory extend LayerViolationFormatter extend MetricViolationFormatter + extend NamedCallFormatter extend SliceViolationFormatter FORMATTERS = { @@ -34,6 +37,7 @@ class ViolationFactory Files::Assertion::ExternalModuleDependencyViolation => :external_module_dependency, Files::Assertion::CycleViolation => :cycle, Files::Assertion::CustomFileViolation => :custom_file, + Files::Assertion::NamedCallViolation => :named_call, Layers::Assertion::LayerDependencyViolation => :layer_dependency, Slices::Assertion::SliceDependencyViolation => :slice_dependency }.merge(MetricViolationFormatter::FORMATTERS).freeze diff --git a/scripts/check_named_calls.rb b/scripts/check_named_calls.rb new file mode 100644 index 0000000..7ffe913 --- /dev/null +++ b/scripts/check_named_calls.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'archunit' +require 'archunit/cli' +require 'json' +require 'pathname' +require 'stringio' +require 'tmpdir' + +def check_named_call(root, expected_status:) + output = StringIO.new + error = StringIO.new + status = ArchUnit::CLI.run(%w[check --format=json], cwd: root.to_s, out: output, err: error) + abort "unexpected named-call exit: #{status}: #{error.string}" unless status == expected_status + + JSON.parse(output.string) +end + +Dir.mktmpdir('archunit-named-call-smoke') do |dir| + root = Pathname.new(dir) + root.join('Gemfile').write("raise 'never boot target'") + root.join('.archunit.rb').write(<<~RUBY) + rule('query boundaries') do + project_files.in_path('query.rb').should_not.contain_calls_named(:delete_all) + end + RUBY + file = root.join('query.rb') + file.write("store.delete_all\nraise 'never execute target'") + report = check_named_call(root, expected_status: 1) + call = report.dig('rules', 0, 'violations', 0, 'call') + evidence = call&.values_at('name', 'line', 'column') + abort 'missing named-call evidence' unless evidence == ['delete_all', 1, 7] + file.write("store.read\nraise 'never execute target'") + check_named_call(root, expected_status: 0) +end +puts 'Named call rule passed the CLI red-to-green smoke without executing target code.' diff --git a/spec/benchmark/semantic_probes_spec.rb b/spec/benchmark/semantic_probes_spec.rb index fd3eed5..475f951 100644 --- a/spec/benchmark/semantic_probes_spec.rb +++ b/spec/benchmark/semantic_probes_spec.rb @@ -13,6 +13,7 @@ dynamic = observations.find { |item| item[:name] == 'dynamic_parameter_receiver' } expect(dynamic[:syntax][:calls]).to include(include(name: :delete_all, resolved_runtime_receiver: nil)) + expect(dynamic[:named_call_violations]).to eq(1) inherited = observations.find { |item| item[:name] == 'inherited_unqualified_constant' } expect(inherited[:direct_file_boundary_violations]).to eq(0) expect(inherited[:counters][:unresolved_constant_references]).to be_positive diff --git a/spec/cli/named_calls_spec.rb b/spec/cli/named_calls_spec.rb new file mode 100644 index 0000000..b1d05c5 --- /dev/null +++ b/spec/cli/named_calls_spec.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require 'archunit/cli' +require 'json' +require 'pathname' +require 'stringio' +require 'tmpdir' + +RSpec.describe ArchUnit::CLI, 'named method call restrictions' do + around do |example| + Dir.mktmpdir('archunit-cli-calls') do |dir| + @root = Pathname.new(dir) + @root.join('Gemfile').write("raise 'must not boot'") + @source = @root.join('query.rb') + @source.write('store.delete_all') + @debt = @root.join('debt.json') + @root.join('.archunit.rb').write(<<~RUBY) + rule('read only') { project_files.in_path('query.rb').should_not.contain_calls_named(:delete_all) } + rule('second policy') { project_files.in_path('query.rb').should_not.contain_calls_named(:update_all) } + RUBY + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def check(command = 'check', *args) + out = StringIO.new + flags = [command, '--format=json', *args] + code = described_class.run(flags, cwd: @root.to_s, out:, err: StringIO.new) + [code, JSON.parse(out.string)] + end + + it 'reports structured syntax evidence and reuses the source-only analysis across rules' do + code, report = check + expect(code).to eq(1) + violations = report.fetch('rules').first.fetch('violations') + expect(violations.first.fetch('call')).to eq( + 'file' => 'query.rb', 'name' => 'delete_all', 'receiver' => 'explicit', + 'line' => 1, 'column' => 7, 'safe_navigation' => false + ) + expect(report.dig('analysis', 'scopes')).to contain_exactly( + include('kind' => 'source_calls', 'cache_hits' => 1, 'observations' => 2) + ) + @source.write('store.read') + expect(check.first).to eq(0) + end + + it 'accepts one occurrence despite shifted lines, but never hides a new occurrence' do + expect(check('baseline', '--output', @debt.to_s).first).to eq(0) + entry = JSON.parse(@debt.read).fetch('entries').first + expect(entry.fetch('data')).to eq( + 'file' => 'query.rb', 'name' => 'delete_all', 'receiver' => 'explicit', + 'safe_navigation' => false + ) + @source.write("# added comment\nstore.delete_all\n") + expect(check('check', '--baseline', @debt.to_s).first).to eq(0) + @source.write("store.delete_all\nstore.delete_all\n") + code, report = check('check', '--baseline', @debt.to_s) + expect(code).to eq(1) + expect(report.fetch('baseline')).to include('accepted_count' => 1, 'new_count' => 1) + @source.write('store&.delete_all') + expect(check('check', '--baseline', @debt.to_s).last.fetch('baseline')) + .to include('accepted_count' => 0, 'new_count' => 1, 'stale_count' => 1) + end + + it 'does not accept a partial parse even after a previously passing check' do + @source.write('store.read') + expect(check.first).to eq(0) + @source.write('class Broken <') + code, report = check + expect(code).to eq(2) + expect(report.dig('error', 'diagnostics')).not_to be_empty + expect(report.dig('analysis', 'scopes', 0)).to include( + 'kind' => 'source_calls', 'status' => 'error' + ) + end +end diff --git a/spec/common/fluentapi/rule_rationale_spec.rb b/spec/common/fluentapi/rule_rationale_spec.rb index 6d3828f..6be4c85 100644 --- a/spec/common/fluentapi/rule_rationale_spec.rb +++ b/spec/common/fluentapi/rule_rationale_spec.rb @@ -37,6 +37,7 @@ def all_terminals files.should.have_no_cycles, files.should_not.depend_on_files.in_folder('app/database/**'), files.should_not.depend_on_external_modules.matching('json'), + files.should_not.contain_calls_named(:require_relative), files.should.adhere_to(->(_file) { true }, 'Ruby files'), ArchUnit.project_layers(@root).layer('api').defined_by('app/api/**') .where_layer('api').may_only_depend_on_layers, diff --git a/spec/files/fluentapi/named_call_condition_spec.rb b/spec/files/fluentapi/named_call_condition_spec.rb new file mode 100644 index 0000000..d7d5692 --- /dev/null +++ b/spec/files/fluentapi/named_call_condition_spec.rb @@ -0,0 +1,133 @@ +# frozen_string_literal: true + +require 'pathname' +require 'minitest' +require 'tmpdir' + +RSpec.describe ArchUnit::Files::FluentApi::NamedCallCondition do + around do |example| + Dir.mktmpdir('archunit-named-calls') do |directory| + @root = Pathname.new(directory) + write('Gemfile', "raise 'do not load'") + example.run + ensure + ArchUnit.clear_graph_cache + end + end + + def write(path, content) + file = @root.join(path) + file.dirname.mkpath + file.write(content) + end + + def scope + ArchUnit.files(@root).in_path('queries/**') + end + + def rule(names = :delete_all, options = nil) + scope.should_not.contain_calls_named(names, options) + end + + it 'distinguishes calls from definitions, comments, strings, and dynamic invocation' do + write('queries/search.rb', <<~RUBY) + class Search + def delete_all; end + def self.run(store) + # delete_all + "delete_all" + store.send(:delete_all) + store.read + end + end + raise 'do not execute the source' + RUBY + expect(rule).to pass + expect(scope.should).not_to respond_to(:contain_calls_named) + end + + it 'records explicit, implicit, self, safe navigation and nested calls in source order' do + write('queries/search.rb', <<~RUBY) + class Search + def delete_all; end + def self.run(store) + delete_all + self.delete_all() + store&.delete_all + [store].each { |item| item.delete_all } + end + end + RUBY + results = rule.check.map(&:call) + expect(results.map { |site| [site.line, site.column, site.receiver, site.safe_navigation] }) + .to eq([[4, 5, :bare, false], [5, 10, :self, false], [6, 12, :explicit, true], + [7, 32, :explicit, false]]) + expect(results.map(&:file).uniq).to eq(['queries/search.rb']) + bare = ArchUnit::NamedCallOptions.new(receiver: :bare) + expect(rule(:delete_all, bare).check.map(&:call)).to eq([results.first]) + end + + it 'matches operator calls and repeated and nested names without altering the dependency graph' do + write('queries/search.rb', 'store.update(store.update(1 + 2)); store[:key] = 42') + original = ArchUnit::Extraction.extract_graph(@root) + expected = %w[update update + []=] + expect(rule(expected).check.map { |item| item.call.name }).to eq(expected) + expect(ArchUnit::Extraction.extract_graph(@root)).to equal(original) + end + + it 'validates the rule lazily and freezes independently owned names' do + names = [+'delete_all', :delete_all] + expect(ArchUnit::Extraction).not_to receive(:extract_named_calls) + condition = rule(names) + names.first.replace('safe') + expect(condition.names.to_a).to eq(['delete_all']) + expect(condition).to be_frozen + expect(condition.names).to be_frozen + expect { rule([]) }.to raise_error(ArgumentError, /at least one/) + expect { rule(' ') }.to raise_error(ArgumentError, /method names/) + expect { rule('read', :bare) }.to raise_error(ArgumentError, /NamedCallOptions/) + expect { ArchUnit::NamedCallOptions.new(receiver: :self) }.to raise_error(ArgumentError) + end + + it 'reuses parsing across rules and refreshes facts with clear_cache or global clearing' do + write('queries/search.rb', 'store.delete_all') + expect(Prism).to receive(:parse).exactly(3).times.and_call_original + expect(rule.check.size).to eq(1) + expect(rule(:read).check).to be_empty + write('queries/search.rb', 'store.read') + expect(rule.check.size).to eq(1) + expect(rule.check(ArchUnit::CheckOptions.new(clear_cache: true))).to be_empty + ArchUnit.clear_graph_cache + expect(rule(:read).check.size).to eq(1) + end + + it 'keeps non-selected syntax errors fatal and respects source exclusions and empty scopes' do + write('queries/search.rb', 'store.delete_all') + write('unrelated.rb', 'class Broken <') + expect { rule.check }.to raise_error(ArchUnit::SourceParseError) + covered = ArchUnit::CheckOptions.new(source_exclusions: ['unrelated.rb']) + expect(rule.check(covered).size).to eq(1) + excluded = covered.with(source_exclusions: %w[unrelated.rb queries/**]) + expect(rule.check(excluded).first).to be_a(ArchUnit::EmptyTestViolation) + expect(rule.check(excluded.with(allow_empty_tests: true))).to eq([]) + end + + it 'gives the shared assertion formatter source coordinates and the method name' do + write('queries/search.rb', 'store.delete_all') + expect { ArchUnit.assert_passes(rule) } + .to raise_error(%r{Forbidden method call 'delete_all'.*queries/search.rb:1:7}m) + expect(rule).not_to pass + end + + it 'uses the same evidence in Minitest assertions' do + write('queries/search.rb', 'store.delete_all') + ArchUnit::Testing::MinitestAdapter.install! + context = Class.new do + include Minitest::Assertions + + attr_accessor :assertions + end.new + context.assertions = 0 + expect { context.assert_passes(rule) }.to raise_error(Minitest::Assertion, /delete_all/) + end +end