Class: RBS::Inline::CLI::PathCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/rbs/inline/cli.rb

Overview

Calculate the path under ‘output_path` that has the same structure relative to one of the `base_paths`

“‘rb calculator = PathCalculator.new(Pathname(“/rbs-inline”), [Pathname(“app”), Pathname(“lib”)], Pathname(“/tmp/sig”)) calculator.calculate(Pathname(“/rbs-inline/app/models/foo.rb”)) # => Pathname(“/tmp/sig/models/foo.rb”) calculator.calculate(Pathname(“/rbs-inline/lib/bar.rb”)) # => Pathname(“/tmp/sig/bar.rb”) calculator.calculate(Pathname(“/rbs-inline/hello/world.rb”)) # => Pathname(“/tmp/sig/hello/world.rb”) calculator.calculate(Pathname(“/foo.rb”)) # => nil “`

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pwd, base_paths, output_path) ⇒ PathCalculator

Returns a new instance of PathCalculator.



29
30
31
32
33
# File 'lib/rbs/inline/cli.rb', line 29

def initialize(pwd, base_paths, output_path) #: void
  @pwd = pwd
  @base_paths = base_paths
  @output_path = output_path
end

Instance Attribute Details

#base_pathsObject (readonly)

: Array



22
23
24
# File 'lib/rbs/inline/cli.rb', line 22

def base_paths
  @base_paths
end

#output_pathObject (readonly)

: Pathname



24
25
26
# File 'lib/rbs/inline/cli.rb', line 24

def output_path
  @output_path
end

#pwdObject (readonly)

: Pathname



20
21
22
# File 'lib/rbs/inline/cli.rb', line 20

def pwd
  @pwd
end

Instance Method Details

#calculate(path) ⇒ Object

: (Pathname) -> Pathname?



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rbs/inline/cli.rb', line 36

def calculate(path)
  path = pwd + path if path.relative?
  path = path.cleanpath
  return nil unless has_prefix?(path, prefix: pwd)

  if prefix = base_paths.find {|base| has_prefix?(path, prefix: pwd + base) }
    relative_to_output = path.relative_path_from(pwd + prefix)
  else
    relative_to_output = path.relative_path_from(pwd)
  end

  output_path + relative_to_output
end

#has_prefix?(path, prefix:) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/rbs/inline/cli.rb', line 53

def has_prefix?(path, prefix:)
  path.descend.include?(prefix)
end