archunit 0.0.1 → 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 (122) hide show
  1. checksums.yaml +4 -4
  2. data/API.md +498 -0
  3. data/CHANGELOG.md +85 -0
  4. data/CODE_OF_CONDUCT.md +40 -0
  5. data/CONTRIBUTING.md +75 -0
  6. data/GUIDE.md +804 -0
  7. data/README.md +224 -289
  8. data/SECURITY.md +64 -0
  9. data/SUPPORT.md +23 -0
  10. data/assets/logo-rounded.png +0 -0
  11. data/exe/archunit +7 -0
  12. data/lib/archunit/cli/analysis_report.rb +62 -0
  13. data/lib/archunit/cli/analysis_text.rb +25 -0
  14. data/lib/archunit/cli/baseline_context.rb +42 -0
  15. data/lib/archunit/cli/baseline_document.rb +58 -0
  16. data/lib/archunit/cli/baseline_fingerprint.rb +36 -0
  17. data/lib/archunit/cli/baseline_identity.rb +85 -0
  18. data/lib/archunit/cli/baseline_ledger.rb +38 -0
  19. data/lib/archunit/cli/baseline_object.rb +15 -0
  20. data/lib/archunit/cli/baseline_options.rb +48 -0
  21. data/lib/archunit/cli/baseline_run.rb +85 -0
  22. data/lib/archunit/cli/baseline_schema.rb +53 -0
  23. data/lib/archunit/cli/baseline_text.rb +31 -0
  24. data/lib/archunit/cli/configuration.rb +93 -0
  25. data/lib/archunit/cli/options.rb +117 -0
  26. data/lib/archunit/cli/report.rb +121 -0
  27. data/lib/archunit/cli/runner.rb +108 -0
  28. data/lib/archunit/cli.rb +15 -0
  29. data/lib/archunit/common/extraction/dependency_evidence.rb +44 -0
  30. data/lib/archunit/common/extraction/edge.rb +7 -2
  31. data/lib/archunit/common/extraction/import_kind.rb +4 -1
  32. data/lib/archunit/common/extraction/parse_diagnostic.rb +23 -0
  33. data/lib/archunit/common/extraction/source_exclusions.rb +43 -0
  34. data/lib/archunit/common/fluentapi/check_options.rb +53 -2
  35. data/lib/archunit/common/fluentapi/checkable.rb +25 -1
  36. data/lib/archunit/common/logging/check_logger.rb +8 -0
  37. data/lib/archunit/common/logging/inspection.rb +59 -0
  38. data/lib/archunit/common/logging/logging_options.rb +5 -0
  39. data/lib/archunit/common/pattern.rb +18 -8
  40. data/lib/archunit/common/projection/cycles/johnson_cycles.rb +35 -19
  41. data/lib/archunit/common/projection/cycles/tarjan_scc.rb +30 -10
  42. data/lib/archunit/error/source_parse_error.rb +38 -0
  43. data/lib/archunit/extraction/analysis_observer.rb +24 -0
  44. data/lib/archunit/extraction/analysis_profile.rb +30 -0
  45. data/lib/archunit/extraction/analysis_snapshot.rb +51 -0
  46. data/lib/archunit/extraction/arch_ignore.rb +91 -0
  47. data/lib/archunit/extraction/conservative_local_flow.rb +100 -0
  48. data/lib/archunit/extraction/constant_index.rb +110 -0
  49. data/lib/archunit/extraction/constant_visitor.rb +137 -0
  50. data/lib/archunit/extraction/dependency_context.rb +30 -0
  51. data/lib/archunit/extraction/discover_gemspec_load_paths.rb +96 -0
  52. data/lib/archunit/extraction/enumerate_source_files.rb +36 -9
  53. data/lib/archunit/extraction/extract_dependencies.rb +74 -15
  54. data/lib/archunit/extraction/extract_graph.rb +74 -40
  55. data/lib/archunit/extraction/extract_imports.rb +57 -124
  56. data/lib/archunit/extraction/extraction_profile.rb +105 -0
  57. data/lib/archunit/extraction/graph_assembly.rb +32 -0
  58. data/lib/archunit/extraction/graph_cache_key.rb +27 -0
  59. data/lib/archunit/extraction/import_calls.rb +93 -0
  60. data/lib/archunit/extraction/import_resolver.rb +65 -0
  61. data/lib/archunit/extraction/import_source_policy.rb +123 -0
  62. data/lib/archunit/extraction/import_visitor.rb +89 -0
  63. data/lib/archunit/extraction/load_arguments.rb +34 -0
  64. data/lib/archunit/extraction/local_string_tracker.rb +81 -0
  65. data/lib/archunit/extraction/resolve_import.rb +5 -3
  66. data/lib/archunit/extraction/resolve_load_paths.rb +98 -0
  67. data/lib/archunit/extraction/resolved_import.rb +5 -2
  68. data/lib/archunit/extraction/source_analysis.rb +26 -0
  69. data/lib/archunit/extraction/static_import_path.rb +111 -0
  70. data/lib/archunit/extraction/validate_extraction_paths.rb +37 -0
  71. data/lib/archunit/files/extraction/extract_file_info.rb +14 -5
  72. data/lib/archunit/files/extraction/file_info.rb +1 -2
  73. data/lib/archunit/files/fluentapi/depend_on_external_module_condition.rb +2 -0
  74. data/lib/archunit/files/fluentapi/depend_on_external_module_condition_builder.rb +2 -0
  75. data/lib/archunit/files/fluentapi/depend_on_file_condition.rb +6 -0
  76. data/lib/archunit/files/fluentapi/depend_on_file_condition_builder.rb +6 -0
  77. data/lib/archunit/files/fluentapi/file_condition_builder.rb +12 -0
  78. data/lib/archunit/files/fluentapi/file_rule_support.rb +8 -1
  79. data/lib/archunit/files/fluentapi/files.rb +6 -0
  80. data/lib/archunit/files/fluentapi/match_pattern_file_condition_builder.rb +14 -0
  81. data/lib/archunit/files/fluentapi/positive_match_pattern_file_condition_builder.rb +2 -0
  82. data/lib/archunit/graph/fluentapi/graph.rb +5 -0
  83. data/lib/archunit/graph/fluentapi/project_graph_builder.rb +44 -0
  84. data/lib/archunit/graph/projection/aggregate_edges.rb +4 -2
  85. data/lib/archunit/graph/projection/graph_query_options.rb +1 -2
  86. data/lib/archunit/graph/projection/graph_report_edge.rb +12 -2
  87. data/lib/archunit/graph/rendering/json_renderer.rb +3 -1
  88. data/lib/archunit/layers/fluentapi/architecture_preset.rb +49 -0
  89. data/lib/archunit/layers/fluentapi/layer_definition_builder.rb +4 -0
  90. data/lib/archunit/layers/fluentapi/layer_dependency_rule_builder.rb +4 -0
  91. data/lib/archunit/layers/fluentapi/layered_architecture.rb +5 -0
  92. data/lib/archunit/layers/fluentapi/layers.rb +5 -0
  93. data/lib/archunit/layers/fluentapi/preset_definitions.rb +39 -0
  94. data/lib/archunit/layers/fluentapi/preset_options.rb +69 -0
  95. data/lib/archunit/layers/fluentapi/preset_rule.rb +45 -0
  96. data/lib/archunit/metrics/extraction/extract_distance_info.rb +2 -3
  97. data/lib/archunit/metrics/extraction/extract_project_info.rb +14 -10
  98. data/lib/archunit/metrics/extraction/metric_info.rb +2 -4
  99. data/lib/archunit/metrics/extraction/source_metrics_visitor.rb +2 -4
  100. data/lib/archunit/metrics/fluentapi/custom_metric_builder.rb +2 -0
  101. data/lib/archunit/metrics/fluentapi/custom_metric_condition.rb +4 -1
  102. data/lib/archunit/metrics/fluentapi/logged_metric.rb +23 -0
  103. data/lib/archunit/metrics/fluentapi/metric_predicate_condition.rb +4 -1
  104. data/lib/archunit/metrics/fluentapi/metric_report_builder.rb +6 -3
  105. data/lib/archunit/metrics/fluentapi/metric_selection.rb +18 -2
  106. data/lib/archunit/metrics/fluentapi/metric_threshold_condition.rb +2 -1
  107. data/lib/archunit/metrics/fluentapi/metrics.rb +5 -0
  108. data/lib/archunit/metrics/fluentapi/metrics_builder.rb +18 -3
  109. data/lib/archunit/metrics/reporting/metrics_export_options.rb +6 -2
  110. data/lib/archunit/slices/fluentapi/diagram_slice_condition.rb +1 -0
  111. data/lib/archunit/slices/fluentapi/forbidden_slice_dependency_condition.rb +1 -0
  112. data/lib/archunit/slices/fluentapi/negative_slice_condition_builder.rb +2 -0
  113. data/lib/archunit/slices/fluentapi/positive_slice_condition_builder.rb +8 -0
  114. data/lib/archunit/slices/fluentapi/slice_scope_builder.rb +12 -0
  115. data/lib/archunit/slices/fluentapi/slices.rb +5 -0
  116. data/lib/archunit/testing/assert_passes.rb +4 -0
  117. data/lib/archunit/testing/result_factory.rb +16 -4
  118. data/lib/archunit/testing/rspec_adapter.rb +1 -2
  119. data/lib/archunit/testing.rb +7 -3
  120. data/lib/archunit/version.rb +1 -1
  121. data/lib/archunit.rb +11 -0
  122. metadata +67 -9
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../common/extraction/import_kind'
4
+ require_relative 'extraction_profile'
5
+ require_relative 'resolve_import'
6
+
7
+ module ArchUnit
8
+ module Extraction
9
+ # Resolves one source file's imports and reuses context-independent feature lookups.
10
+ class ImportResolver
11
+ def initialize( # rubocop:disable Metrics/ParameterLists
12
+ source_path:, project_root:, load_paths:, profile: nil, cache: nil, helper_load_paths: nil
13
+ )
14
+ @source_path = source_path
15
+ @project_root = project_root
16
+ @load_paths = load_paths
17
+ @helper_load_paths = helper_load_paths || load_paths
18
+ @profile = profile
19
+ @cache = cache
20
+ end
21
+
22
+ def resolve(module_name, import_kind)
23
+ key = cache_key(module_name, import_kind)
24
+ return cached_resolution(key) if @cache&.key?(key)
25
+
26
+ @profile&.increment(:resolution_cache_misses) if @cache
27
+ resolution = uncached_resolution(module_name, import_kind)
28
+ @cache[key] = resolution if @cache
29
+ resolution
30
+ end
31
+
32
+ private
33
+
34
+ def cached_resolution(key)
35
+ @profile&.increment(:resolution_cache_hits)
36
+ @cache[key]
37
+ end
38
+
39
+ def uncached_resolution(module_name, import_kind)
40
+ ExtractionProfile.measure(@profile, :target_resolution) do
41
+ Extraction.resolve_import(
42
+ module_name,
43
+ source_file: @source_path,
44
+ project_root: @project_root,
45
+ import_kind:,
46
+ load_paths: resolution_paths(import_kind)
47
+ )
48
+ end
49
+ end
50
+
51
+ def resolution_paths(kind)
52
+ return @helper_load_paths if kind == Common::Extraction::ImportKind::REQUIRE_DEPENDENCY
53
+
54
+ @load_paths
55
+ end
56
+
57
+ def cache_key(module_name, import_kind)
58
+ source_context = if import_kind == Common::Extraction::ImportKind::REQUIRE_RELATIVE
59
+ File.dirname(@source_path.to_s)
60
+ end
61
+ [module_name, import_kind, source_context].freeze
62
+ end
63
+ end
64
+ end
65
+ end
@@ -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
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'prism'
4
+ require_relative '../common/extraction/import_kind'
5
+ require_relative 'conservative_local_flow'
6
+ require_relative 'local_string_tracker'
7
+ require_relative 'load_arguments'
8
+ require_relative 'static_import_path'
9
+ require_relative 'import_calls'
10
+
11
+ module ArchUnit
12
+ module Extraction
13
+ # Collects supported dependency calls from a Prism syntax tree.
14
+ class ImportVisitor < Prism::Visitor
15
+ include ConservativeLocalFlow
16
+
17
+ attr_reader :imports, :unresolved_imports
18
+
19
+ def initialize(source_path: nil, syntax_tree: nil, rails_imports: false)
20
+ super()
21
+ @imports = []
22
+ @unresolved_imports = 0
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
+ end
29
+
30
+ def visit_call_node(node)
31
+ import_kind = @calls.kind(node)
32
+ record_import(node, import_kind) if import_kind
33
+ super
34
+ invalidate_escaped_locals(node) unless import_kind
35
+ end
36
+
37
+ def visit_local_variable_write_node(node)
38
+ super
39
+ @local_strings.assign(node.name, node.value)
40
+ end
41
+
42
+ private
43
+
44
+ def record_import(node, import_kind)
45
+ arguments = node.arguments&.arguments || []
46
+ module_name = import_module_name(node, arguments, import_kind)
47
+ unless valid_module_name?(module_name)
48
+ @unresolved_imports += 1
49
+ return
50
+ end
51
+
52
+ @imports << located_import(module_name, import_kind, node)
53
+ end
54
+
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))
58
+ end
59
+
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
65
+ end
66
+
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
70
+
71
+ [Prism::SymbolNode, Prism::StringNode].none? { |type| arguments.first.is_a?(type) }
72
+ end
73
+
74
+ def located_import(module_name, import_kind, node)
75
+ [module_name, import_kind, node.location.start_line, node.location.end_line]
76
+ end
77
+
78
+ def valid_module_name?(module_name)
79
+ module_name.is_a?(String) && !module_name.empty? && !module_name.include?("\0")
80
+ end
81
+
82
+ def invalidate_escaped_locals(node)
83
+ @local_strings.invalidate_escaped(node)
84
+ @local_strings.capture_scopes if %i[eval binding local_variable_set].include?(node.name)
85
+ end
86
+ end
87
+ private_constant :ImportVisitor
88
+ end
89
+ end
@@ -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
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'prism'
4
+
5
+ module ArchUnit
6
+ module Extraction
7
+ # Conservatively tracks local variables with a safely known String value.
8
+ class LocalStringTracker
9
+ UNKNOWN = Object.new.freeze
10
+ private_constant :UNKNOWN
11
+
12
+ def initialize(path_resolver: nil)
13
+ @path_resolver = path_resolver
14
+ @scopes = [{}]
15
+ @captured_scopes = [false]
16
+ @uncertain_depth = 0
17
+ end
18
+
19
+ def resolve(node)
20
+ return node.unescaped if node.is_a?(Prism::StringNode)
21
+ return UNKNOWN if @uncertain_depth.positive? || @captured_scopes.last
22
+ return scope.fetch(node.name, UNKNOWN) if node.is_a?(Prism::LocalVariableReadNode)
23
+
24
+ @path_resolver&.resolve(node) || UNKNOWN
25
+ end
26
+
27
+ def assign(name, value)
28
+ invalidate_escaped(value) if value && !value.is_a?(Prism::StringNode)
29
+ scope[name] = resolve(value)
30
+ end
31
+
32
+ def invalidate_escaped(node)
33
+ local_reads(node).each { |name| scope[name] = UNKNOWN if scope.key?(name) }
34
+ end
35
+
36
+ def isolated_scope
37
+ @scopes << {}
38
+ @captured_scopes << false
39
+ yield
40
+ ensure
41
+ @scopes.pop
42
+ @captured_scopes.pop
43
+ end
44
+
45
+ def invalidate_all
46
+ @scopes.each { |values| values.transform_values! { UNKNOWN } }
47
+ end
48
+
49
+ def capture_scopes
50
+ @captured_scopes.map! { true }
51
+ invalidate_all
52
+ end
53
+
54
+ def uncertain_flow
55
+ invalidate_scope
56
+ @uncertain_depth += 1
57
+ yield
58
+ ensure
59
+ @uncertain_depth -= 1
60
+ invalidate_scope
61
+ end
62
+
63
+ private
64
+
65
+ def local_reads(node)
66
+ return [node.name] if node.is_a?(Prism::LocalVariableReadNode)
67
+
68
+ node.compact_child_nodes.flat_map { |child| local_reads(child) }.uniq
69
+ end
70
+
71
+ def invalidate_scope
72
+ scope.transform_values! { UNKNOWN }
73
+ end
74
+
75
+ def scope
76
+ @scopes.last
77
+ end
78
+ end
79
+ private_constant :LocalStringTracker
80
+ end
81
+ end
@@ -8,8 +8,8 @@ module ArchUnit
8
8
  module Extraction
9
9
  module_function
10
10
 
11
- def resolve_import(module_name, source_file:, project_root:, import_kind:)
12
- roots = import_search_roots(source_file, project_root, import_kind)
11
+ def resolve_import(module_name, source_file:, project_root:, import_kind:, load_paths: nil)
12
+ roots = import_search_roots(source_file, project_root, import_kind, load_paths)
13
13
  resolved = if import_kind == Common::Extraction::ImportKind::LOAD
14
14
  resolve_load(module_name, roots, import_kind)
15
15
  else
@@ -19,9 +19,11 @@ module ArchUnit
19
19
  resolved&.tr('\\', '/')&.freeze
20
20
  end
21
21
 
22
- def import_search_roots(source_file, project_root, import_kind)
22
+ def import_search_roots(source_file, project_root, import_kind, load_paths)
23
23
  if import_kind == Common::Extraction::ImportKind::REQUIRE_RELATIVE
24
24
  [File.dirname(File.expand_path(source_file))]
25
+ elsif load_paths
26
+ load_paths
25
27
  else
26
28
  root = File.expand_path(project_root)
27
29
  [File.join(root, 'lib'), root]
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+ require_relative '../error/user_error'
5
+ require_relative 'discover_gemspec_load_paths'
6
+
7
+ module ArchUnit
8
+ module Extraction
9
+ # Builds the deterministic feature search path used for static Ruby import resolution.
10
+ module LoadPaths
11
+ module_function
12
+
13
+ def resolve(project_root, explicit_paths: [], source_files: nil)
14
+ root = canonical_root(project_root)
15
+ defaults = [root.join('lib'), root].select(&:directory?)
16
+ explicit = resolve_explicit_paths(root, explicit_paths)
17
+ discovered = GemspecLoadPaths.resolve(root, source_files:)
18
+
19
+ deduplicate(defaults + explicit + discovered)
20
+ end
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
+
27
+ def canonical_root(value)
28
+ path = value.respond_to?(:to_path) ? value.to_path : value
29
+ unless path.is_a?(String) && !path.empty?
30
+ raise UserError, 'project_root must be a non-empty path'
31
+ end
32
+
33
+ root = Pathname.new(path).expand_path
34
+ raise UserError, 'project_root must be an existing directory' unless root.directory?
35
+
36
+ root.realpath
37
+ end
38
+ private_class_method :canonical_root
39
+
40
+ def resolve_explicit_paths(root, paths)
41
+ validate_explicit_paths(paths)
42
+ paths.map { |value| resolve_explicit_path(root, value) }
43
+ end
44
+ private_class_method :resolve_explicit_paths
45
+
46
+ def resolve_explicit_path(root, value)
47
+ candidate = Pathname.new(value.tr('\\', '/'))
48
+ candidate = root.join(candidate) unless candidate.absolute?
49
+ candidate = candidate.expand_path
50
+ validate_explicit_path(candidate, root, value)
51
+ candidate.realpath
52
+ end
53
+ private_class_method :resolve_explicit_path
54
+
55
+ def validate_explicit_path(candidate, root, value)
56
+ unless candidate.directory?
57
+ raise UserError, "load path must be an existing directory: #{value}"
58
+ end
59
+
60
+ canonical = candidate.realpath
61
+ return if within_project?(canonical, root)
62
+
63
+ raise UserError, "load path must stay inside the project root: #{value}"
64
+ end
65
+ private_class_method :validate_explicit_path
66
+
67
+ def validate_explicit_paths(paths)
68
+ valid = paths.is_a?(Array) && paths.all? do |path|
69
+ path.is_a?(String) && !path.empty?
70
+ end
71
+ return if valid
72
+
73
+ raise UserError, 'load_paths must be an Array of non-empty paths'
74
+ end
75
+ private_class_method :validate_explicit_paths
76
+
77
+ def within_project?(path, root)
78
+ path.relative_path_from(root).each_filename.first != '..'
79
+ rescue ArgumentError
80
+ false
81
+ end
82
+ private_class_method :within_project?
83
+
84
+ def deduplicate(paths)
85
+ paths.each_with_object([]) do |path, result|
86
+ value = normalized(path).freeze
87
+ result << value unless result.include?(value)
88
+ end.freeze
89
+ end
90
+ private_class_method :deduplicate
91
+
92
+ def normalized(path)
93
+ path.to_s.tr('\\', '/')
94
+ end
95
+ private_class_method :normalized
96
+ end
97
+ end
98
+ end
@@ -4,11 +4,14 @@ require_relative '../common/extraction/import_kind'
4
4
 
5
5
  module ArchUnit
6
6
  module Extraction
7
- ResolvedImport = Data.define(:module_name, :import_kind, :line_number, :resolved_path) do
8
- def initialize(module_name:, import_kind:, line_number:, resolved_path: nil)
7
+ ResolvedImport = Data.define(:module_name, :import_kind, :line_number, :resolved_path,
8
+ :end_line) do
9
+ def initialize(module_name:, import_kind:, line_number:, resolved_path: nil,
10
+ end_line: line_number)
9
11
  validate_module_name(module_name)
10
12
  validate_import_kind(import_kind)
11
13
  validate_line_number(line_number)
14
+ validate_line_number(end_line)
12
15
  validate_resolved_path(resolved_path)
13
16
 
14
17
  module_name = module_name.dup.freeze
@@ -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