From 69c7a20896813aefa519aaee7b75552731cd672a Mon Sep 17 00:00:00 2001
From: Mike McQuaid <mike@mikemcquaid.com>
Date: Wed, 19 Apr 2017 10:49:20 +0100
Subject: [PATCH] Fix `brew edit` with environment filtering.

For many people `brew edit` makes use of the `EDITOR` variable to pick a
sensible editor. With environment filtering enabled unless this editor
is found in the default system PATH it'll fall back to e.g. `vim`.

Instead, ensure that we export the original, pre-filtering `PATH` as
`HOMEBREW_PATH` and use that internally to locate the editor. In future
this same approach will likely be used for requirements to be able to
find tools, too, and for other variables which we want to expose to
Homebrew itself but not other build tools.

Note that `HOMEBREW_PATH` is the same as `PATH` when build filtering
hasn't been enabled.
---
 Library/Homebrew/test/utils_spec.rb | 8 +++++++-
 Library/Homebrew/utils.rb           | 6 +++---
 bin/brew                            | 8 ++++++++
 3 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/Library/Homebrew/test/utils_spec.rb b/Library/Homebrew/test/utils_spec.rb
index 314c299a8f..dd7ea20de9 100644
--- a/Library/Homebrew/test/utils_spec.rb
+++ b/Library/Homebrew/test/utils_spec.rb
@@ -189,7 +189,13 @@ describe "globally-scoped helper methods" do
 
   specify "#which_editor" do
     ENV["HOMEBREW_EDITOR"] = "vemate"
-    expect(which_editor).to eq("vemate")
+    ENV["HOMEBREW_PATH"] = dir
+
+    editor = dir/"vemate"
+    FileUtils.touch editor
+    FileUtils.chmod 0755, editor
+
+    expect(which_editor).to eql editor
   end
 
   specify "#gzip" do
diff --git a/Library/Homebrew/utils.rb b/Library/Homebrew/utils.rb
index 46a8cc68e0..7a14916e1c 100644
--- a/Library/Homebrew/utils.rb
+++ b/Library/Homebrew/utils.rb
@@ -320,8 +320,8 @@ def which_all(cmd, path = ENV["PATH"])
 end
 
 def which_editor
-  editor = ENV.values_at("HOMEBREW_EDITOR", "VISUAL", "EDITOR").compact.first
-  return editor unless editor.nil?
+  editor = ENV.values_at("HOMEBREW_EDITOR", "VISUAL").compact.first
+  return which(editor, ENV["HOMEBREW_PATH"]) unless editor.nil?
 
   # Find Textmate
   editor = "mate" if which "mate"
@@ -334,7 +334,7 @@ def which_editor
 
   opoo <<-EOS.undent
     Using #{editor} because no editor was set in the environment.
-    This may change in the future, so we recommend setting EDITOR, VISUAL,
+    This may change in the future, so we recommend setting EDITOR,
     or HOMEBREW_EDITOR to your preferred text editor.
   EOS
 
diff --git a/bin/brew b/bin/brew
index 43a807c7b2..84be2fb1d7 100755
--- a/bin/brew
+++ b/bin/brew
@@ -44,6 +44,14 @@ fi
 
 HOMEBREW_LIBRARY="$HOMEBREW_REPOSITORY/Library"
 
+for VAR in EDITOR PATH
+do
+  VAR_NEW="HOMEBREW_${VAR}"
+  # TODO: find a better solution than this.
+  env | grep -q "$VAR_NEW" && continue
+  export "$VAR_NEW"="${!VAR}"
+done
+
 if [[ -n "$HOMEBREW_ENV_FILTERING" ]]
 then
   PATH="/usr/bin:/bin:/usr/sbin:/sbin"
-- 
GitLab