pathhack [-f] [+HACK|-HACK] [--] [COMMAND [ARGS...]]
authorMark Wooding <mdw@distorted.org.uk>
Wed, 5 Apr 2006 12:37:23 +0000 (13:37 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Wed, 5 Apr 2006 13:43:20 +0000 (14:43 +0100)
Path hacks are stored in ~/bin/hacks.  `+HACK' adds a hack to the path,
`-HACK' removes it.  If a COMMAND is given, run the command with the
hacked path; otherwise set it in the current shell.

If `-f' is given, force reordering of added hacks; otherwise, if a hack
is already inserted, ignore it.

With no arguments, print the installed hacks in order.

bashrc

diff --git a/bashrc b/bashrc
index 6fb97f4..82d50c8 100644 (file)
--- a/bashrc
+++ b/bashrc
@@ -1,3 +1,4 @@
+# -*-sh-*-
 #
 # $Id: .bashrc,v 1.6 1996/12/08 20:33:42 mdw Exp $
 #
@@ -174,6 +175,104 @@ core () {
   esac
 }
 
+# --- Turning on and off path hacks ---
+
+path-add () {
+  local pathvar export dir val
+  case $# in
+    1) pathvar=PATH dir=$1 export="export PATH";;
+    2) pathvar=$1 dir=$2 export=:;;
+    *) echo >&2 "Usage: $0 [VAR] DIR";;
+  esac
+  eval "val=\$$pathvar"
+  case ":$val:" in
+    *:"$dir":*) ;;
+    *) val=$dir:$val ;;
+  esac
+  eval "$pathvar=\$val"
+  $export
+}
+
+path-remove () {
+  local pathvar export dir val
+  case $# in
+    1) pathvar=PATH dir=$1 export="export PATH";;
+    2) pathvar=$1 dir=$2 export=:;;
+    *) echo >&2 "Usage: $0 [VAR] DIR";;
+  esac
+  eval "val=\$$pathvar"
+  case ":$val:" in
+    :"$dir":) val= ;;
+    :"$dir":*) val=${val#$dir:} ;;
+    *:"$dir":) val=${val%:$dir} ;;
+    *:"$dir":*) val=${val/:$dir:/:} ;;
+  esac
+  eval "$pathvar=\$val"
+  $export
+}
+
+pathhack () {
+  if [ $# -eq 0 ]; then
+    local IFS=:
+    for e in $PATH; do
+      case "$e" in
+       "$HOME/bin/hacks/"*)
+         echo ${e#$HOME/bin/hacks/}
+         ;;
+      esac
+    done
+    return
+  fi
+  local force=nil
+  local path=$PATH
+  while [ $# -gt 0 ]; do
+    arg=$1
+    case "$arg" in
+      -f | --force)
+       force=t
+       shift
+       continue
+       ;;
+      --)
+        shift
+       break
+       ;;
+      [-+]*)
+        ;;
+      *)
+        break
+       ;;
+    esac
+    hack=${arg#[+-]}
+    dir=$HOME/bin/hacks/$hack
+    [ -d "$dir" ] || {
+      echo "$0: path hack $hack not found"
+      return 1
+    }
+    case "$arg,$force,:$PATH:" in
+      -*,*,*:"$dir":*)
+        path-remove path "$dir"
+       ;;
+      +*,t,*:"$dir":*)
+        path-remove path "$dir"
+       path-add path "$dir"
+       ;;
+      +*,nil,*:"$dir":*)
+        ;;
+      +*,*)
+        path-add path "$dir"
+       ;;
+    esac
+    shift
+  done
+  if [ $# -eq 0 ]; then
+    PATH=$path
+    export PATH
+  else
+    PATH=$path "$@"
+  fi
+}
+
 # --- Fix `man' under Slowaris ---
 
 case "$MACHTYPE" in