Skip to content

Commit

Permalink
Fix whereami to work after a chdir in a main script
Browse files Browse the repository at this point in the history
fixes #1220
  • Loading branch information
onlynone committed Apr 23, 2024
1 parent 6f4d2c1 commit 4a205fd
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lib/pry/commands/whereami.rb
Expand Up @@ -44,11 +44,31 @@ class << self
def setup
if target.respond_to?(:source_location)
file, @line = target.source_location
@file = expand_path(file)
else
@file = expand_path(target.eval('__FILE__'))
file = target.eval('__FILE__')
@line = target.eval('__LINE__')
end

# If the current location is in a top-level script, then the filename
# returned by source_location or __FILE__ will be just the filename with
# no path: e.g. 'myscript.rb'. If the current working directory has been
# changed, then expand_path(file) will construct an incorrect path to
# the source. We can use __dir__ to fix this case.
if !file.nil? && !File.absolute_path?(file)
dir = target.eval('__dir__')

# We have to be careful not to join with dir if it's also a relative
# path. There are some cases where the file and dir paths are both
# relative to the same directory, like:
#
# __FILE__: "spec/fixtures/example.erb"
# __dir__: "spec/fixtures"
if !dir.nil? && File.absolute_path?(dir)
file = File.join(dir, file)
end
end

@file = expand_path(file)
@method = Pry::Method.from_binding(target)
end

Expand Down
11 changes: 11 additions & 0 deletions spec/commands/whereami_spec.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'method_source'
require 'open3'

describe "whereami" do
it 'should work with methods that have been undefined' do
Expand Down Expand Up @@ -277,4 +278,14 @@ def blimey!
it "should work inside an object" do
expect(pry_eval(Object.new, 'whereami')).to match(/Inside #<Object/)
end

it 'should work after chdir from main script' do
script_dir = File.expand_path(File.join(__dir__, '..', 'fixtures'))
script = 'whereami_main_chdir.rb'

output, status = Open3.capture2(RbConfig.ruby, script, chdir: script_dir)

expect(output.strip).to eq File.join(script_dir, script)
end

end
22 changes: 22 additions & 0 deletions spec/fixtures/whereami_main_chdir.rb
@@ -0,0 +1,22 @@
# frozen_string_literal: true

if $PROGRAM_NAME != __FILE__
fail "#{__FILE__} should only be executed as a top level program"
end

$LOAD_PATH.unshift File.expand_path(File.join(__dir__, '..', '..', 'lib'))

require 'pry'
require 'pry/testable'

include Pry::Testable::Evalable

class Cor
def blimey!
Dir.chdir '..' do
pry_eval(binding, 'whereami', '_file_')
end
end
end

puts Cor.new.blimey!

0 comments on commit 4a205fd

Please sign in to comment.