Module: CodeOwnership::Private::FilePathFinder

Extended by:
T::Sig
Defined in:
lib/code_ownership/private/file_path_finder.rb

Class Method Summary collapse

Class Method Details

.from_backtrace(backtrace) ⇒ Object



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
66
67
68
69
70
71
72
# File 'lib/code_ownership/private/file_path_finder.rb', line 38

def self.from_backtrace(backtrace)
  return [] unless backtrace

  # The pattern for a backtrace hasn't changed in forever and is considered
  # stable: https://github.com/ruby/ruby/blob/trunk/vm_backtrace.c#L303-L317
  #
  # This pattern matches a line like the following:
  #
  #   ./app/controllers/some_controller.rb:43:in `block (3 levels) in create'
  #
  backtrace_line = if RUBY_VERSION >= '3.4.0'
                     %r{\A(#{pwd}/|\./)?
                         (?<file>.+)       # Matches 'app/controllers/some_controller.rb'
                         :
                         (?<line>\d+)      # Matches '43'
                         :in\s
                         '(?<function>.*)' # Matches "`block (3 levels) in create'"
                       \z}x
                   else
                     %r{\A(#{pwd}/|\./)?
                         (?<file>.+)       # Matches 'app/controllers/some_controller.rb'
                         :
                         (?<line>\d+)      # Matches '43'
                         :in\s
                         `(?<function>.*)' # Matches "`block (3 levels) in create'"
                       \z}x
                   end

  backtrace.lazy.filter_map do |line|
    match = line.match(backtrace_line)
    next unless match

    T.must(match[:file])
  end
end

.path_from_klass(klass) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/code_ownership/private/file_path_finder.rb', line 22

def self.path_from_klass(klass)
  if klass
    path = Object.const_source_location(klass.to_s)&.first
    return nil unless path

    if path.start_with?(pwd_prefix)
      path.delete_prefix(pwd_prefix)
    else
      Pathname.new(path).relative_path_from(pwd).to_s
    end
  end
rescue NameError
  nil
end

.pwdObject



15
16
17
# File 'lib/code_ownership/private/file_path_finder.rb', line 15

def self.pwd
  @pwd ||= T.let(Pathname.pwd, T.nilable(Pathname))
end

.pwd_prefixObject



10
11
12
# File 'lib/code_ownership/private/file_path_finder.rb', line 10

def self.pwd_prefix
  @pwd_prefix ||= T.let("#{Dir.pwd}/", T.nilable(String))
end