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

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

Overview

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

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.

Parameters:

  • pwd (Pathname)
  • base_paths (Array[Pathname])
  • output_path (Pathname)


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_pathsArray[Pathname] (readonly)

: Array

Returns:

  • (Array[Pathname])


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

def base_paths
  @base_paths
end

#output_pathPathname (readonly)

: Pathname

Returns:

  • (Pathname)


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

def output_path
  @output_path
end

#pwdPathname (readonly)

: Pathname

Returns:

  • (Pathname)


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

def pwd
  @pwd
end

Instance Method Details

#calculate(path) ⇒ Pathname?

: (Pathname) -> Pathname?

Parameters:

  • (Pathname)

Returns:

  • (Pathname, nil)


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

Parameters:

  • path (Pathname)
  • prefix: (Pathname)

Returns:

  • (Boolean)


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

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