Skip to content

Instantly share code, notes, and snippets.

@yeban
Created April 26, 2012 10:30
Show Gist options
  • Save yeban/2498631 to your computer and use it in GitHub Desktop.
Save yeban/2498631 to your computer and use it in GitHub Desktop.
cd to the project root (identified by the presence of a SCM directory, like .git, or .bzr)
# Copyright (C) 2011 Anurag Priyam - MIT License
#
# cd to the project root (identified by the presence of a SCM directory, like
# .git, or .bzr)
#
# Install
# -------
#
# Put something like this in your .zshrc:
#
# . /path/to/rooter.sh
#
# This installs the 'cdr' command for use.
#
# Use
# ---
#
# $ pwd
# /home/yeban/drizzle/drizzle/libdrizzle-2.0/libdrizzle
# $ cdr
# $ pwd
# /home/yeban/src/drizzle/drizzle
#
# Todo
# ----
#
# Make it more efficient? Currently, it iterates over each ancestral directory
# looking for a known SCM directory. Is there a better way?
#
# array of some known SCM directories
scmdirs=('.git' '.bzr' '.hg')
# return true if the given directory has an SCM subdirectory
_has_scm_dir(){
if [[ -d $1 ]]; then
for scmdir in ${scmdirs[@]}; do
if [[ -d "$1/$scmdir" ]]; then
return 0
fi
done
fi
return 1
}
# return the project root of the given directory
_get_root_dir(){
local dir=$1
if [[ -d $dir ]]; then
while [ $dir != "/" ]
do
if _has_scm_dir $dir; then
echo $dir; return 0
fi
dir=$(dirname $dir)
done
fi
return 1
}
# cd to the project root of the current working directory
cdr(){
cd $(_get_root_dir $(pwd))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment