Skip to content

Commit

Permalink
Add Loc#source to display the source content form a RBI location
Browse files Browse the repository at this point in the history
Signed-off-by: Alexandre Terrasa <alexandre.terrasa@shopify.com>
  • Loading branch information
Morriar committed Mar 10, 2022
1 parent b4f823a commit e0f5cf9
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/rbi/loc.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,20 @@ def initialize(file: nil, begin_line: nil, end_line: nil, begin_column: nil, end
def to_s
"#{file}:#{begin_line}:#{begin_column}-#{end_line}:#{end_column}"
end

sig { returns(T.nilable(String)) }
def source
file = self.file
return nil unless file
return nil unless ::File.file?(file)

return ::File.read(file) unless begin_line && end_line

string = String.new
::File.foreach(file).with_index do |line, line_number|
string << line if line_number + 1 >= begin_line && line_number + 1 <= end_line
end
string
end
end
end
69 changes: 69 additions & 0 deletions test/rbi/loc_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# typed: true
# frozen_string_literal: true

require "test_helper"

module RBI
class LocTest < Minitest::Test
extend T::Sig

TEST_FILE_PATH = "tmp/rbi/tests/source.rbi"

TEST_FILE_CONTENT = <<~RBI
# typed: true
class Foo
def foo; end
end
class Bar; end
class Baz; end
RBI

def setup
dir = ::File.dirname(TEST_FILE_PATH)
FileUtils.mkdir_p(dir)
::File.write(TEST_FILE_PATH, TEST_FILE_CONTENT)
end

def teardown
FileUtils.rm_rf(TEST_FILE_PATH)
end

def test_loc_source_without_file_returns_nil
loc = Loc.new(file: nil)
assert_nil(loc.source)
end

def test_loc_source_with_unexisting_file_returns_nil
loc = Loc.new(file: "tmp/rbi/tests/not_found.rbi")
assert_nil(loc.source)
end

def test_loc_source_from_file_without_lines
loc = Loc.new(file: TEST_FILE_PATH)
assert_equal(TEST_FILE_CONTENT, loc.source)
end

def test_loc_source_from_file_between_lines
loc = Loc.new(file: TEST_FILE_PATH, begin_line: 3, end_line: 5)
assert_equal(<<~RBI, loc.source)
class Foo
def foo; end
end
RBI
end

def test_loc_source_from_file_at_line
loc = Loc.new(file: TEST_FILE_PATH, begin_line: 7, end_line: 7)
assert_equal(<<~RBI, loc.source)
class Bar; end
RBI
end

def test_loc_source_from_file_out_of_range
loc = Loc.new(file: TEST_FILE_PATH, begin_line: -10, end_line: 100)
assert_equal(TEST_FILE_CONTENT, loc.source)
end
end
end

0 comments on commit e0f5cf9

Please sign in to comment.