From c60241f9d9ad906f083713ee185e8bd8a2b69d6e Mon Sep 17 00:00:00 2001
From: Daniel Hahler <github@thequod.de>
Date: Fri, 14 Sep 2018 03:46:43 +0200
Subject: [PATCH] Add helper functions for $PATH manipulation (#90)

---
 README.md             | 18 ++++++++++++++++++
 autoenv.zsh           | 23 +++++++++++++++++++++++
 tests/autoenv_utils.t | 29 +++++++++++++++++++++++++++++
 3 files changed, 70 insertions(+)
 create mode 100644 tests/autoenv_utils.t

diff --git a/README.md b/README.md
index c49e66f..fe81fe6 100644
--- a/README.md
+++ b/README.md
@@ -149,6 +149,24 @@ zsh-autoenv works automatically once installed.
 You can use ``autoenv-edit`` to edit the nearest/current autoenv files.
 It will use ``$AUTOENV_EDITOR``, ``$EDITOR``, or ``vim`` for editing.
 
+## Helper functions
+
+The following helper functions are available:
+
+### autoenv_append_path
+
+Appends path(s) to `$path` (`$PATH`), if they are not in there already.
+
+### autoenv_prepend_path
+
+Prepends path(s) to `$path` (`$PATH`), if they are not in there already.
+
+### autoenv_remove_path
+
+Removes path(s) from `$path` (`$PATH`).
+
+Returns 0 in case `$path` has changed, 1 otherwise.
+
 ## Recipes
 
 ### Automatically activate Python virtualenvs
diff --git a/autoenv.zsh b/autoenv.zsh
index e70eec1..598443b 100644
--- a/autoenv.zsh
+++ b/autoenv.zsh
@@ -59,6 +59,29 @@ autoenv_source_parent() {
   fi
 }
 
+autoenv_append_path() {
+  local i
+  for i; do
+    (( ${path[(i)$i]} <= ${#path} )) && continue
+    path+=($i)
+  done
+}
+autoenv_prepend_path() {
+  local i
+  for i; do
+    (( ${path[(i)$i]} <= ${#path} )) && continue
+    path=($i $path)
+  done
+}
+autoenv_remove_path() {
+  local i
+  local old_path=$path
+  for i; do
+    path=("${(@)path:#$i}")
+  done
+  [[ $old_path != $path ]]
+}
+
 # Internal functions. {{{
 # Internal: stack of loaded env files (i.e. entered directories). {{{
 typeset -g -a _autoenv_stack_entered
diff --git a/tests/autoenv_utils.t b/tests/autoenv_utils.t
new file mode 100644
index 0000000..e3d2271
--- /dev/null
+++ b/tests/autoenv_utils.t
@@ -0,0 +1,29 @@
+Tests for provided utils/helpers.
+
+  $ source $TESTDIR/setup.zsh || return 1
+
+  $ PATH=
+  $ autoenv_prepend_path custom_path
+  $ echo $PATH
+  custom_path
+
+  $ autoenv_prepend_path custom_path
+  $ echo $PATH
+  custom_path
+
+  $ autoenv_prepend_path another_path a_third_one
+  $ echo $PATH
+  a_third_one:another_path:custom_path
+
+  $ autoenv_remove_path another_path a_third_one
+  $ echo $PATH
+  custom_path
+
+  $ autoenv_remove_path does_not_exist
+  [1]
+  $ echo $PATH
+  custom_path
+
+  $ autoenv_remove_path custom_path
+  $ echo PATH:$PATH
+  PATH:
-- 
2.51.0