aboutsummaryrefslogtreecommitdiff
path: root/sh/shrc.d/vr.sh
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2016-08-20 16:26:06 +1200
committerTom Ryder <tom@sanctum.geek.nz>2016-08-20 16:26:39 +1200
commit6e3fd021588c87a0743dbc1ec5b3f5aba900f839 (patch)
tree74a790cf3a96c7f55660c612964462f194aa20ce /sh/shrc.d/vr.sh
parentAssume POSIX sh (diff)
downloaddotfiles-6e3fd021588c87a0743dbc1ec5b3f5aba900f839.tar.gz
dotfiles-6e3fd021588c87a0743dbc1ec5b3f5aba900f839.zip
Port vr(1) to POSIX sh
Diffstat (limited to 'sh/shrc.d/vr.sh')
-rw-r--r--sh/shrc.d/vr.sh49
1 files changed, 49 insertions, 0 deletions
diff --git a/sh/shrc.d/vr.sh b/sh/shrc.d/vr.sh
new file mode 100644
index 00000000..b8a31aee
--- /dev/null
+++ b/sh/shrc.d/vr.sh
@@ -0,0 +1,49 @@
+# Move to the root directory of a VCS working copy
+vr() {
+
+ # Set positional parameters to the result of trying to figure out the
+ # repository root
+ set -- "$(
+
+ # Check we have at most one argument
+ if [ "$#" -gt 1 ] ; then
+ printf >&2 'vr(): Too many arguments\n'
+ exit 2
+ fi
+
+ # Get path from first argument, strip trailing slash
+ path=${1:-"$PWD"}
+ [ "$path" = / ] || path=${path%/}
+
+ # Step into the directory
+ cd -- "$path" || exit
+
+ # Ask Git the top level (good)
+ git rev-parse --show-toplevel 2>/dev/null && exit
+
+ # Ask Mercurial the top level (great)
+ hg root 2>/dev/null && exit
+
+ # If we can get SVN info, iterate upwards until we can't; hopefully
+ # that's the root (bad)
+ while svn info >/dev/null 2>&1 ; do
+ root=$PWD
+ [ "$root" = / ] && break
+ cd .. || exit
+ done
+ if [ -n "$root" ] ; then
+ printf '%s\n' "$root"
+ exit
+ fi
+
+ # Couldn't find repository root, say so
+ printf >&2 'vr(): Failed to find repository root\n'
+ exit 1
+ )"
+
+ # Check we figured out a target, or bail
+ [ -n "$1" ] || return
+
+ # Try to change into the determined directory
+ command cd -- "$@"
+}