archunit 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. checksums.yaml +4 -4
  2. data/API.md +213 -5
  3. data/CHANGELOG.md +41 -1
  4. data/CODE_OF_CONDUCT.md +40 -0
  5. data/CONTRIBUTING.md +75 -0
  6. data/GUIDE.md +804 -0
  7. data/README.md +198 -562
  8. data/SECURITY.md +64 -0
  9. data/SUPPORT.md +23 -0
  10. data/exe/archunit +7 -0
  11. data/lib/archunit/cli/analysis_report.rb +62 -0
  12. data/lib/archunit/cli/analysis_text.rb +25 -0
  13. data/lib/archunit/cli/baseline_context.rb +42 -0
  14. data/lib/archunit/cli/baseline_document.rb +58 -0
  15. data/lib/archunit/cli/baseline_fingerprint.rb +36 -0
  16. data/lib/archunit/cli/baseline_identity.rb +85 -0
  17. data/lib/archunit/cli/baseline_ledger.rb +38 -0
  18. data/lib/archunit/cli/baseline_object.rb +15 -0
  19. data/lib/archunit/cli/baseline_options.rb +48 -0
  20. data/lib/archunit/cli/baseline_run.rb +85 -0
  21. data/lib/archunit/cli/baseline_schema.rb +53 -0
  22. data/lib/archunit/cli/baseline_text.rb +31 -0
  23. data/lib/archunit/cli/configuration.rb +93 -0
  24. data/lib/archunit/cli/options.rb +117 -0
  25. data/lib/archunit/cli/report.rb +121 -0
  26. data/lib/archunit/cli/runner.rb +108 -0
  27. data/lib/archunit/cli.rb +15 -0
  28. data/lib/archunit/common/extraction/import_kind.rb +3 -1
  29. data/lib/archunit/common/extraction/source_exclusions.rb +43 -0
  30. data/lib/archunit/common/fluentapi/check_options.rb +13 -3
  31. data/lib/archunit/extraction/analysis_observer.rb +24 -0
  32. data/lib/archunit/extraction/analysis_profile.rb +30 -0
  33. data/lib/archunit/extraction/analysis_snapshot.rb +51 -0
  34. data/lib/archunit/extraction/constant_visitor.rb +8 -0
  35. data/lib/archunit/extraction/dependency_context.rb +30 -0
  36. data/lib/archunit/extraction/enumerate_source_files.rb +17 -5
  37. data/lib/archunit/extraction/extract_dependencies.rb +5 -14
  38. data/lib/archunit/extraction/extract_graph.rb +45 -55
  39. data/lib/archunit/extraction/extract_imports.rb +11 -14
  40. data/lib/archunit/extraction/graph_assembly.rb +32 -0
  41. data/lib/archunit/extraction/graph_cache_key.rb +27 -0
  42. data/lib/archunit/extraction/import_calls.rb +93 -0
  43. data/lib/archunit/extraction/import_resolver.rb +11 -2
  44. data/lib/archunit/extraction/import_source_policy.rb +123 -0
  45. data/lib/archunit/extraction/import_visitor.rb +31 -46
  46. data/lib/archunit/extraction/load_arguments.rb +34 -0
  47. data/lib/archunit/extraction/local_string_tracker.rb +4 -3
  48. data/lib/archunit/extraction/resolve_load_paths.rb +5 -0
  49. data/lib/archunit/extraction/source_analysis.rb +26 -0
  50. data/lib/archunit/extraction/static_import_path.rb +111 -0
  51. data/lib/archunit/layers/fluentapi/architecture_preset.rb +49 -0
  52. data/lib/archunit/layers/fluentapi/preset_definitions.rb +39 -0
  53. data/lib/archunit/layers/fluentapi/preset_options.rb +69 -0
  54. data/lib/archunit/layers/fluentapi/preset_rule.rb +45 -0
  55. data/lib/archunit/metrics/extraction/extract_distance_info.rb +1 -1
  56. data/lib/archunit/metrics/extraction/extract_project_info.rb +8 -4
  57. data/lib/archunit/metrics/fluentapi/metric_report_builder.rb +4 -3
  58. data/lib/archunit/metrics/fluentapi/metrics_builder.rb +3 -3
  59. data/lib/archunit/metrics/reporting/metrics_export_options.rb +6 -2
  60. data/lib/archunit/version.rb +1 -1
  61. data/lib/archunit.rb +2 -0
  62. metadata +48 -8
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'prism'
4
+
5
+ module ArchUnit
6
+ module Extraction
7
+ # Source-local guards, not a claim to model arbitrary cross-file monkey-patching.
8
+ class ImportSourcePolicy < Prism::Visitor
9
+ REFLECTION = %i[
10
+ eval class_eval module_eval instance_eval class_exec module_exec instance_exec
11
+ define_method define_singleton_method alias_method remove_method undef_method
12
+ const_set remove_const refine using send public_send __send__ singleton_class
13
+ ].freeze
14
+ private_constant :REFLECTION
15
+
16
+ def initialize(tree)
17
+ super()
18
+ @tree = tree
19
+ @disabled = {}
20
+ end
21
+
22
+ def allowed?(capability)
23
+ unless @analyzed
24
+ @analyzed = true
25
+ visit(@tree)
26
+ end
27
+ !@disabled[capability]
28
+ end
29
+
30
+ def visit_constant_write_node(node)
31
+ shadow(node.name)
32
+ super
33
+ end
34
+ alias visit_constant_or_write_node visit_constant_write_node
35
+ alias visit_constant_and_write_node visit_constant_write_node
36
+ alias visit_constant_operator_write_node visit_constant_write_node
37
+
38
+ def visit_constant_target_node(node)
39
+ shadow(node.name)
40
+ super
41
+ end
42
+
43
+ def visit_constant_path_target_node(node)
44
+ shadow(node.name)
45
+ super
46
+ end
47
+
48
+ def visit_constant_path_write_node(node)
49
+ shadow(node.target.name)
50
+ super
51
+ end
52
+ alias visit_constant_path_or_write_node visit_constant_path_write_node
53
+ alias visit_constant_path_and_write_node visit_constant_path_write_node
54
+ alias visit_constant_path_operator_write_node visit_constant_path_write_node
55
+
56
+ def visit_class_node(node)
57
+ shadow(node.constant_path.name) if node.constant_path.respond_to?(:name)
58
+ super
59
+ end
60
+
61
+ def visit_module_node(node)
62
+ shadow(node.constant_path.name) if node.constant_path.respond_to?(:name)
63
+ super
64
+ end
65
+
66
+ def visit_def_node(node)
67
+ @disabled[:directory_calls] = true if node.name == :__dir__
68
+ @disabled[:string_addition] = true if node.name == :+
69
+ @disabled[:rails_helpers] = true if node.name == :require_dependency
70
+ shadow(node.receiver.name) if node.receiver.respond_to?(:name)
71
+ super
72
+ end
73
+
74
+ def visit_singleton_class_node(node)
75
+ shadow(node.expression.name) if node.expression.respond_to?(:name)
76
+ super
77
+ end
78
+
79
+ def visit_call_node(node)
80
+ disable if REFLECTION.include?(node.name)
81
+ check_autoload(node) if node.name == :autoload
82
+ check_mixin(node) if %i[include prepend extend].include?(node.name)
83
+ super
84
+ end
85
+
86
+ def visit_alias_method_node(node)
87
+ disable
88
+ super
89
+ end
90
+
91
+ def visit_undef_node(node)
92
+ disable
93
+ super
94
+ end
95
+
96
+ private
97
+
98
+ def shadow(name)
99
+ @disabled[:file_calls] = true if name == :File
100
+ @disabled[:string_addition] = true if name == :String
101
+ end
102
+
103
+ def check_autoload(node)
104
+ name = node.arguments&.arguments&.first
105
+ if name.is_a?(Prism::SymbolNode) || name.is_a?(Prism::StringNode)
106
+ shadow(name.unescaped.to_sym)
107
+ else
108
+ disable
109
+ end
110
+ end
111
+
112
+ def check_mixin(node)
113
+ shadow(node.receiver.name) if node.receiver.respond_to?(:name)
114
+ end
115
+
116
+ def disable
117
+ @disabled.merge!(file_calls: true, directory_calls: true,
118
+ string_addition: true, rails_helpers: true)
119
+ end
120
+ end
121
+ private_constant :ImportSourcePolicy
122
+ end
123
+ end
@@ -4,6 +4,9 @@ require 'prism'
4
4
  require_relative '../common/extraction/import_kind'
5
5
  require_relative 'conservative_local_flow'
6
6
  require_relative 'local_string_tracker'
7
+ require_relative 'load_arguments'
8
+ require_relative 'static_import_path'
9
+ require_relative 'import_calls'
7
10
 
8
11
  module ArchUnit
9
12
  module Extraction
@@ -11,27 +14,24 @@ module ArchUnit
11
14
  class ImportVisitor < Prism::Visitor
12
15
  include ConservativeLocalFlow
13
16
 
14
- CALL_KINDS = {
15
- require: Common::Extraction::ImportKind::REQUIRE,
16
- require_relative: Common::Extraction::ImportKind::REQUIRE_RELATIVE,
17
- autoload: Common::Extraction::ImportKind::AUTOLOAD,
18
- load: Common::Extraction::ImportKind::LOAD
19
- }.freeze
20
-
21
17
  attr_reader :imports, :unresolved_imports
22
18
 
23
- def initialize
24
- super
19
+ def initialize(source_path: nil, syntax_tree: nil, rails_imports: false)
20
+ super()
25
21
  @imports = []
26
22
  @unresolved_imports = 0
27
- @local_strings = LocalStringTracker.new
23
+ policy = ImportSourcePolicy.new(syntax_tree)
24
+ @calls = ImportCalls.new(rails_imports:, source_policy: policy)
25
+ @local_strings = LocalStringTracker.new(
26
+ path_resolver: StaticImportPath.new(source_path:, source_policy: policy)
27
+ )
28
28
  end
29
29
 
30
30
  def visit_call_node(node)
31
- import_call = supported_import_call?(node)
32
- record_import(node) if import_call
31
+ import_kind = @calls.kind(node)
32
+ record_import(node, import_kind) if import_kind
33
33
  super
34
- invalidate_escaped_locals(node) unless import_call
34
+ invalidate_escaped_locals(node) unless import_kind
35
35
  end
36
36
 
37
37
  def visit_local_variable_write_node(node)
@@ -41,11 +41,9 @@ module ArchUnit
41
41
 
42
42
  private
43
43
 
44
- def record_import(node)
45
- import_kind = CALL_KINDS[node.name]
44
+ def record_import(node, import_kind)
46
45
  arguments = node.arguments&.arguments || []
47
- argument = import_argument(arguments, import_kind)
48
- module_name = @local_strings.resolve(argument)
46
+ module_name = import_module_name(node, arguments, import_kind)
49
47
  unless valid_module_name?(module_name)
50
48
  @unresolved_imports += 1
51
49
  return
@@ -54,44 +52,31 @@ module ArchUnit
54
52
  @imports << located_import(module_name, import_kind, node)
55
53
  end
56
54
 
57
- def located_import(module_name, import_kind, node)
58
- [module_name, import_kind, node.location.start_line, node.location.end_line]
59
- end
60
-
61
- def valid_module_name?(module_name)
62
- module_name.is_a?(String) && !module_name.empty? && !module_name.include?("\0")
55
+ def import_module_name(node, arguments, import_kind)
56
+ invalidate_import_arguments(node, arguments, import_kind)
57
+ @local_strings.resolve(@calls.path(arguments, import_kind))
63
58
  end
64
59
 
65
- def supported_import_call?(node)
66
- import_kind = CALL_KINDS[node.name]
67
- import_kind && supported_receiver?(node, import_kind) &&
68
- !import_argument(node.arguments&.arguments || [], import_kind).nil?
60
+ def invalidate_import_arguments(node, arguments, kind)
61
+ unsafe = @calls.uncertain?(kind) || unsafe_auxiliary_arguments?(node, arguments, kind)
62
+ unsafe ||= kind == Common::Extraction::ImportKind::LOAD &&
63
+ LoadArguments.effectful?(node, arguments)
64
+ @local_strings.invalidate_all if unsafe
69
65
  end
70
66
 
71
- def supported_receiver?(node, import_kind)
72
- return true if node.receiver.nil?
73
- if import_kind == Common::Extraction::ImportKind::AUTOLOAD
74
- return constant_receiver?(node.receiver)
75
- end
67
+ def unsafe_auxiliary_arguments?(node, arguments, import_kind)
68
+ return true if node.block.is_a?(Prism::BlockArgumentNode)
69
+ return false unless import_kind == Common::Extraction::ImportKind::AUTOLOAD
76
70
 
77
- node.receiver.respond_to?(:full_name) &&
78
- node.receiver.full_name.delete_prefix('::') == 'Kernel'
71
+ [Prism::SymbolNode, Prism::StringNode].none? { |type| arguments.first.is_a?(type) }
79
72
  end
80
73
 
81
- def constant_receiver?(receiver)
82
- receiver.is_a?(Prism::ConstantReadNode) || receiver.is_a?(Prism::ConstantPathNode)
74
+ def located_import(module_name, import_kind, node)
75
+ [module_name, import_kind, node.location.start_line, node.location.end_line]
83
76
  end
84
77
 
85
- def import_argument(arguments, import_kind)
86
- if import_kind == Common::Extraction::ImportKind::AUTOLOAD
87
- return unless arguments.length == 2
88
-
89
- arguments[1]
90
- else
91
- return unless arguments.length == 1
92
-
93
- arguments[0]
94
- end
78
+ def valid_module_name?(module_name)
79
+ module_name.is_a?(String) && !module_name.empty? && !module_name.include?("\0")
95
80
  end
96
81
 
97
82
  def invalidate_escaped_locals(node)
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'prism'
4
+
5
+ module ArchUnit
6
+ module Extraction
7
+ # Bounds positional import arity and Kernel.load wrapping without evaluating source.
8
+ module LoadArguments
9
+ VARIADIC = [Prism::SplatNode, Prism::ForwardingArgumentsNode].freeze
10
+ PURE_WRAP = [Prism::TrueNode, Prism::FalseNode, Prism::NilNode,
11
+ Prism::LocalVariableReadNode].freeze
12
+ private_constant :VARIADIC, :PURE_WRAP
13
+
14
+ def self.possible?(arguments, max: 2)
15
+ !arguments.empty? && arguments.count { |argument| !variadic?(argument) } <= max
16
+ end
17
+
18
+ def self.path(arguments)
19
+ arguments.first unless arguments.any? { |argument| variadic?(argument) }
20
+ end
21
+
22
+ def self.effectful?(node, arguments)
23
+ node.block.is_a?(Prism::BlockArgumentNode) ||
24
+ (arguments.length > 1 && PURE_WRAP.none? { |type| arguments[1].is_a?(type) })
25
+ end
26
+
27
+ def self.variadic?(argument)
28
+ VARIADIC.any? { |type| argument.is_a?(type) }
29
+ end
30
+ private_class_method :variadic?
31
+ end
32
+ private_constant :LoadArguments
33
+ end
34
+ end
@@ -4,12 +4,13 @@ require 'prism'
4
4
 
5
5
  module ArchUnit
6
6
  module Extraction
7
- # Conservatively tracks local variables whose current value is a literal String.
7
+ # Conservatively tracks local variables with a safely known String value.
8
8
  class LocalStringTracker
9
9
  UNKNOWN = Object.new.freeze
10
10
  private_constant :UNKNOWN
11
11
 
12
- def initialize
12
+ def initialize(path_resolver: nil)
13
+ @path_resolver = path_resolver
13
14
  @scopes = [{}]
14
15
  @captured_scopes = [false]
15
16
  @uncertain_depth = 0
@@ -20,7 +21,7 @@ module ArchUnit
20
21
  return UNKNOWN if @uncertain_depth.positive? || @captured_scopes.last
21
22
  return scope.fetch(node.name, UNKNOWN) if node.is_a?(Prism::LocalVariableReadNode)
22
23
 
23
- UNKNOWN
24
+ @path_resolver&.resolve(node) || UNKNOWN
24
25
  end
25
26
 
26
27
  def assign(name, value)
@@ -19,6 +19,11 @@ module ArchUnit
19
19
  deduplicate(defaults + explicit + discovered)
20
20
  end
21
21
 
22
+ # The caller explicitly supplies helper search roots; no Rails environment is consulted.
23
+ def with_explicit_first(root, paths, explicit_paths)
24
+ deduplicate(resolve_explicit_paths(root, explicit_paths) + paths)
25
+ end
26
+
22
27
  def canonical_root(value)
23
28
  path = value.respond_to?(:to_path) ? value.to_path : value
24
29
  unless path.is_a?(String) && !path.empty?
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'analysis_observer'
4
+ require_relative 'analysis_snapshot'
5
+
6
+ module ArchUnit
7
+ module Extraction
8
+ # Records a complete source-metric pass or an unavailable, failed pass.
9
+ # @api private
10
+ module SourceAnalysis
11
+ def self.observe(discovery)
12
+ result = yield
13
+ publish(discovery, count: discovery.files.length, status: 'analyzed')
14
+ result
15
+ rescue StandardError
16
+ publish(discovery, count: nil, status: 'error')
17
+ raise
18
+ end
19
+
20
+ def self.publish(discovery, count:, status:)
21
+ AnalysisObserver.record(AnalysisSnapshot.source(discovery, count:, status:))
22
+ end
23
+ private_class_method :publish
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+ require 'prism'
5
+ require_relative 'import_source_policy'
6
+
7
+ module ArchUnit
8
+ module Extraction
9
+ # Folds a small AST whitelist; never invokes methods/receivers from project source.
10
+ class StaticImportPath
11
+ MAX_DEPTH = 12
12
+ MAX_BYTES = 16_384
13
+ private_constant :MAX_DEPTH, :MAX_BYTES
14
+
15
+ def initialize(source_path:, syntax_tree: nil, source_policy: nil)
16
+ @source_path = source_path&.to_s
17
+ @policy = source_policy || ImportSourcePolicy.new(syntax_tree)
18
+ end
19
+
20
+ def resolve(node, depth = 0)
21
+ return unless node && @source_path && depth <= MAX_DEPTH
22
+
23
+ value = resolve_node(node, depth)
24
+ value if valid_value?(value)
25
+ rescue ArgumentError, Encoding::CompatibilityError
26
+ nil
27
+ end
28
+
29
+ private
30
+
31
+ attr_reader :policy
32
+
33
+ def resolve_node(node, depth)
34
+ case node
35
+ when Prism::StringNode then node.unescaped
36
+ when Prism::SourceFileNode then @source_path
37
+ when Prism::CallNode then resolve_call(node, depth)
38
+ end
39
+ end
40
+
41
+ def valid_value?(value)
42
+ value.is_a?(String) && value.bytesize <= MAX_BYTES && !value.include?("\0")
43
+ end
44
+
45
+ def resolve_call(node, depth)
46
+ return if node.block || node.safe_navigation?
47
+
48
+ arguments = node.arguments&.arguments || []
49
+ return directory(node, arguments) if node.name == :__dir__
50
+ return concatenate(node, arguments, depth) if node.name == :+
51
+
52
+ resolve_file_call(node, arguments, depth)
53
+ end
54
+
55
+ def resolve_file_call(node, arguments, depth)
56
+ return unless file_receiver?(node.receiver) && policy.allowed?(:file_calls)
57
+
58
+ values = arguments.map { |argument| resolve(argument, depth + 1) }
59
+ return if values.any?(&:nil?)
60
+
61
+ file_call(node.name, values)
62
+ end
63
+
64
+ def directory(node, arguments)
65
+ return unless node.receiver.nil? && arguments.empty? && policy.allowed?(:directory_calls)
66
+
67
+ @directory ||= File.dirname(File.realpath(@source_path))
68
+ end
69
+
70
+ def concatenate(node, arguments, depth)
71
+ return unless arguments.length == 1 && policy.allowed?(:string_addition)
72
+
73
+ left = resolve(node.receiver, depth + 1)
74
+ right = resolve(arguments.first, depth + 1)
75
+ "#{left}#{right}" if left && right
76
+ end
77
+
78
+ def file_receiver?(node)
79
+ return node.name == :File if node.is_a?(Prism::ConstantReadNode)
80
+
81
+ node.is_a?(Prism::ConstantPathNode) && node.parent.nil? && node.name == :File
82
+ end
83
+
84
+ def file_call(name, values)
85
+ case name
86
+ when :dirname
87
+ File.dirname(values.first) if values.length == 1 && absolute?(values.first)
88
+ when :expand_path
89
+ expand_path(values)
90
+ end
91
+ end
92
+
93
+ def expand_path(values)
94
+ return unless [1, 2].include?(values.length)
95
+ return unless values.all? { |value| deterministic?(value) }
96
+ return unless absolute?(values.length == 2 ? values.last : values.first)
97
+
98
+ File.expand_path(*values)
99
+ end
100
+
101
+ def absolute?(value)
102
+ Pathname.new(value).absolute?
103
+ end
104
+
105
+ def deterministic?(value)
106
+ !value.start_with?('~') && !value.match?(%r{\A[a-z]:(?![/\\])}i)
107
+ end
108
+ end
109
+ private_constant :StaticImportPath
110
+ end
111
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'preset_options'
4
+ require_relative 'preset_definitions'
5
+ require_relative 'preset_rule'
6
+
7
+ # Public preset entry point composed from the existing named-layer vocabulary.
8
+ module ArchUnit
9
+ module Layers
10
+ module FluentApi
11
+ # Composes named-layer builders, so presets share all existing extraction/assertion semantics.
12
+ # @api private
13
+ module ArchitecturePreset
14
+ def self.build(name, options = nil)
15
+ options = PresetOptions.resolve(options)
16
+ folders = PresetDefinitions.folders(name, options.folders)
17
+ architecture = define_layers(folders, options.project_locator)
18
+ policy = apply_policy(architecture, name)
19
+ PresetRule.new(name:, architecture: policy)
20
+ end
21
+
22
+ def self.apply_policy(architecture, name)
23
+ dependencies = PresetDefinitions::ALLOWED.fetch(name)
24
+ dependencies.reduce(architecture) do |rule, (source, targets)|
25
+ rule.where_layer(source).may_only_depend_on_layers(*targets)
26
+ end
27
+ end
28
+
29
+ def self.define_layers(folders, locator)
30
+ architecture = LayeredArchitecture.new(project_locator: locator)
31
+ folders.reduce(architecture) do |rule, (name, patterns)|
32
+ Array(patterns).reduce(rule) do |current, pattern|
33
+ current.layer(name).defined_by(pattern)
34
+ end
35
+ end
36
+ end
37
+ private_class_method :define_layers, :apply_policy
38
+ end
39
+ end
40
+ end
41
+
42
+ # Starts a completed layered, hexagonal, or Rails folder policy.
43
+ # @param name [Symbol] :layered, :hexagonal or :rails
44
+ # @param options [Layers::FluentApi::PresetOptions, nil] source locator/pattern overrides
45
+ # @return [Layers::FluentApi::PresetRule] lazy, immutable Checkable
46
+ def self.architecture_preset(name, options = nil)
47
+ Layers::FluentApi::ArchitecturePreset.build(name, options)
48
+ end
49
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module Layers
5
+ module FluentApi
6
+ # Small opinionated policies, not a claim to recognize an application's architecture.
7
+ # @api private
8
+ module PresetDefinitions
9
+ FOLDERS = {
10
+ layered: { 'presentation' => 'app/api/**', 'application' => 'app/services/**',
11
+ 'persistence' => 'app/db/**' }.freeze,
12
+ hexagonal: { 'domain' => 'app/domain/**', 'application' => 'app/application/**',
13
+ 'adapters' => 'app/adapters/**' }.freeze,
14
+ rails: { 'controllers' => 'app/controllers/**', 'services' => 'app/services/**',
15
+ 'models' => 'app/models/**' }.freeze
16
+ }.freeze
17
+ ALLOWED = {
18
+ layered: { 'presentation' => %w[application].freeze,
19
+ 'application' => %w[persistence].freeze, 'persistence' => [].freeze }.freeze,
20
+ hexagonal: { 'domain' => [].freeze, 'application' => %w[domain].freeze,
21
+ 'adapters' => %w[application domain].freeze }.freeze,
22
+ rails: { 'controllers' => %w[services models].freeze, 'services' => %w[models].freeze,
23
+ 'models' => [].freeze }.freeze
24
+ }.freeze
25
+
26
+ def self.folders(name, overrides)
27
+ defaults = FOLDERS.fetch(name) do
28
+ raise ArgumentError, "unknown architecture preset: #{name}"
29
+ end
30
+ unknown = overrides.keys - defaults.keys
31
+ raise ArgumentError, "unknown preset layers: #{unknown.join(', ')}" unless unknown.empty?
32
+
33
+ defaults.merge(overrides)
34
+ end
35
+ end
36
+ private_constant :PresetDefinitions
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArchUnit
4
+ module Layers
5
+ module FluentApi
6
+ # Immutable source-pattern overrides for an architecture preset; no I/O during construction.
7
+ PresetOptions = Data.define(:project_locator, :folders) do
8
+ def initialize(project_locator: nil, folders: {})
9
+ project_locator = immutable_locator(project_locator)
10
+ folders = immutable_folders(folders)
11
+ super
12
+ end
13
+
14
+ def self.resolve(value)
15
+ return new if value.nil?
16
+ return value if value.is_a?(self)
17
+
18
+ raise ArgumentError, 'options must be a PresetOptions value or nil'
19
+ end
20
+
21
+ private
22
+
23
+ def immutable_locator(value)
24
+ return if value.nil?
25
+
26
+ value = value.to_path if value.respond_to?(:to_path)
27
+ return value.dup.freeze if value.is_a?(String) && !value.empty?
28
+
29
+ raise ArgumentError, 'project_locator must be a non-empty path or nil'
30
+ end
31
+
32
+ def immutable_folders(value)
33
+ unless value.is_a?(Hash)
34
+ raise ArgumentError,
35
+ 'folders must map layer names to source globs'
36
+ end
37
+
38
+ entries = value.map { |name, patterns| folder_entry(name, patterns) }
39
+ if entries.map(&:first).uniq.length != entries.length
40
+ raise ArgumentError, 'duplicate normalized preset layer names'
41
+ end
42
+
43
+ entries.to_h.freeze
44
+ end
45
+
46
+ def folder_entry(name, patterns)
47
+ unless name.is_a?(Symbol) || (name.is_a?(String) && !name.empty?)
48
+ raise ArgumentError, 'preset layer names must be Symbols or non-empty Strings'
49
+ end
50
+
51
+ [name.to_s.dup.freeze, immutable_patterns(patterns)]
52
+ end
53
+
54
+ def immutable_patterns(value)
55
+ patterns = value.is_a?(Array) ? value : [value]
56
+ unless !patterns.empty? && patterns.all? { |item| valid_pattern?(item) }
57
+ raise ArgumentError, 'preset folders must contain non-empty source globs'
58
+ end
59
+
60
+ patterns.map { |pattern| pattern.tr('\\', '/').freeze }.uniq.freeze
61
+ end
62
+
63
+ def valid_pattern?(value)
64
+ value.is_a?(String) && !value.strip.empty?
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'layered_architecture'
4
+ require_relative '../../error/user_error'
5
+
6
+ module ArchUnit
7
+ module Layers
8
+ module FluentApi
9
+ # Completed preset: existing layer assertions plus an explicit ambiguity guard.
10
+ class PresetRule
11
+ include Common::FluentApi::Checkable
12
+
13
+ attr_reader :name, :architecture
14
+
15
+ def initialize(name:, architecture:)
16
+ unless name.is_a?(Symbol) && architecture.is_a?(LayeredArchitecture)
17
+ raise ArgumentError, 'preset requires a Symbol name and LayeredArchitecture'
18
+ end
19
+
20
+ @name = name
21
+ @architecture = architecture
22
+ freeze
23
+ end
24
+
25
+ private
26
+
27
+ def perform_check(options)
28
+ graph = ArchUnit::Extraction.extract_graph(architecture.project_locator, options:)
29
+ graph.each do |edge|
30
+ validate_membership(edge.source) if edge.source == edge.target && !edge.external
31
+ end
32
+ architecture.check(options.with(clear_cache: false))
33
+ end
34
+
35
+ def validate_membership(path)
36
+ matches = architecture.layer_definitions.select { |layer| layer.matches?(path) }
37
+ return if matches.length <= 1
38
+
39
+ names = matches.map(&:name).join(', ')
40
+ raise UserError, "preset file '#{path}' matches multiple layers: #{names}"
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -12,7 +12,7 @@ module ArchUnit
12
12
 
13
13
  # Enriches static file facts with distinct internal incoming/outgoing dependencies.
14
14
  def extract_distance_infos(project_locator = nil, options: nil)
15
- project = extract_project_info(project_locator)
15
+ project = extract_project_info(project_locator, options:)
16
16
  graph = ArchUnit::Extraction.extract_graph(project.project_root, options:)
17
17
  outgoing, incoming = coupling_indexes(graph, project.files.map(&:path))
18
18
  build_distance_infos(project, outgoing, incoming)