From 45915e6a1c5e777f5fb975ef3094642a75fb6b66 Mon Sep 17 00:00:00 2001 From: Robin Daugherty Date: Wed, 4 Nov 2020 15:31:28 -0500 Subject: [PATCH] Support for virtual and host paths --- lib/better_errors/editor.rb | 20 ++++++++++++++++- spec/better_errors/editor_spec.rb | 37 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/lib/better_errors/editor.rb b/lib/better_errors/editor.rb index 06df7f4d..b8de8fb7 100644 --- a/lib/better_errors/editor.rb +++ b/lib/better_errors/editor.rb @@ -70,12 +70,30 @@ def initialize(url_proc) @url_proc = url_proc end - def url(file, line) + def url(raw_path, line) + if virtual_path && raw_path.start_with?(virtual_path) + if host_path + file = raw_path.sub(%r{\A#{virtual_path}}, host_path) + else + file = raw_path.sub(%r{\A#{virtual_path}/}, '') + end + else + file = raw_path + end + url_proc.call(file, line) end private attr_reader :url_proc + + def virtual_path + @virtual_path ||= ENV['BETTER_ERRORS_VIRTUAL_PATH'] + end + + def host_path + @host_path ||= ENV['BETTER_ERRORS_HOST_PATH'] + end end end diff --git a/spec/better_errors/editor_spec.rb b/spec/better_errors/editor_spec.rb index 033c05d5..ca0127a3 100644 --- a/spec/better_errors/editor_spec.rb +++ b/spec/better_errors/editor_spec.rb @@ -230,4 +230,41 @@ end end end + + describe "#url" do + subject(:url) { described_instance.url("/full/path/to/lib/file.rb", 42) } + let(:described_instance) { described_class.for_formatting_string("%{file_unencoded}")} + before do + ENV['BETTER_ERRORS_VIRTUAL_PATH'] = virtual_path + ENV['BETTER_ERRORS_HOST_PATH'] = host_path + end + let(:virtual_path) { nil } + let(:host_path) { nil } + + context "when $BETTER_ERRORS_VIRTUAL_PATH is set" do + let(:virtual_path) { "/full/path/to" } + + context "when $BETTER_ERRORS_HOST_PATH is not set" do + let(:host_path) { nil } + + it "removes the VIRTUAL_PATH prefix, making the path relative" do + expect(url).to eq("lib/file.rb") + end + end + + context "when $BETTER_ERRORS_HOST_PATH is set" do + let(:host_path) { '/Users/myname/Code' } + + it "replaces the VIRTUAL_PATH prefix with the HOST_PATH" do + expect(url).to eq("/Users/myname/Code/lib/file.rb") + end + end + end + + context "when $BETTER_ERRORS_VIRTUAL_PATH is not set" do + it "does not alter file paths" do + expect(url).to eq("/full/path/to/lib/file.rb") + end + end + end end