Module: Libcodeowners::FilePathFinder

Extended by:
T::Helpers, T::Sig
Defined in:
lib/libcodeowners/file_path_finder.rb

Class Method Summary collapse

Class Method Details

.from_backtrace(backtrace) ⇒ Object



27
28
29
30
31
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
# File 'lib/libcodeowners/file_path_finder.rb', line 27

def 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(#{Pathname.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(#{Pathname.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



15
16
17
18
19
20
21
22
23
24
# File 'lib/libcodeowners/file_path_finder.rb', line 15

def path_from_klass(klass)
  if klass
    path = Object.const_source_location(klass.to_s)&.first
    (path && Pathname.new(path).relative_path_from(Pathname.pwd).to_s) || nil
  else
    nil
  end
rescue NameError
  nil
end