Class: LayerChecker::DependencyExtractor

Inherits:
Object
  • Object
show all
Defined in:
lib/layer_checker/dependency_extractor.rb

Class Method Summary collapse

Class Method Details

.extract(file_path) ⇒ Object

Extract dependencies from a Ruby file



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/layer_checker/dependency_extractor.rb', line 8

def self.extract(file_path)
  return [] unless File.exist?(file_path)

  source = File.read(file_path)
  dependencies = []

  begin
    buffer = Parser::Source::Buffer.new(file_path)
    buffer.source = source
    
    parser = Parser::CurrentRuby.new
    ast = parser.parse(buffer)
    
    dependencies = extract_from_ast(ast) if ast
  rescue Parser::SyntaxError => e
    # Skip files with syntax errors
    warn "Syntax error in #{file_path}: #{e.message}" if ENV['DEBUG']
  end

  dependencies.uniq
end

.extract_const_name(node) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/layer_checker/dependency_extractor.rb', line 67

def self.extract_const_name(node)
  return nil unless node.is_a?(Parser::AST::Node) && node.type == :const

  parts = []
  current = node

  while current && current.is_a?(Parser::AST::Node)
    if current.type == :const
      parts.unshift(current.children[1].to_s)
      current = current.children[0]
    elsif current.type == :cbase
      # Absolute constant (::Something)
      break
    else
      break
    end
  end

  parts.join('::')
end

.extract_from_ast(node, dependencies = []) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/layer_checker/dependency_extractor.rb', line 32

def self.extract_from_ast(node, dependencies = [])
  return dependencies unless node.is_a?(Parser::AST::Node)

  case node.type
  when :const
    # Extract constant references (e.g., UserService, User::Profile)
    const_name = extract_const_name(node)
    dependencies << { type: :constant, name: const_name, node: node } if const_name
  
  when :send
    # Extract method calls that might reference other modules
    # e.g., UserService.new, User.find(1)
    if node.children[0].is_a?(Parser::AST::Node) && node.children[0].type == :const
      const_name = extract_const_name(node.children[0])
      dependencies << { type: :method_call, name: const_name, node: node } if const_name
    end
  
  when :class, :module
    # Extract class/module inheritance and includes
    if node.children[1] # superclass
      if node.children[1].is_a?(Parser::AST::Node) && node.children[1].type == :const
        const_name = extract_const_name(node.children[1])
        dependencies << { type: :inheritance, name: const_name, node: node.children[1] } if const_name
      end
    end
  end

  # Recursively process child nodes
  node.children.each do |child|
    extract_from_ast(child, dependencies) if child.is_a?(Parser::AST::Node)
  end

  dependencies
end