# cdg : cd to a git repo if [ -d "$GCLONE_PATH" ]; then gclone() { # Check if cloning via HTTP(S) or SSH if [[ $1 == http* ]]; then server=`echo $1 | rev | cut -d '/' -f 3- | rev | cut -d '/' -f 3-` name=`echo $1 | rev | cut -d '/' -f -2 | rev` else server=`echo $1 | cut -d ':' -f 1 | cut -d '@' -f 2-` name=`echo $1 | cut -d ':' -f 2-` fi user=`echo $name | cut -d '/' -f 1` repo=`echo $name | cut -d '/' -f 2-` if [[ $repo == *.git ]]; then repo=${repo%.*} fi # Final path to the repo repo_path=$GCLONE_PATH/$server/$user if [ -d $repo_path/$repo ]; then echo "Repository already exists" return 1 fi tempdir=`mktemp -d` git clone $1 $tempdir/$repo # If the clone worked, move the repo in the good place if [ $? -eq 0 ]; then mkdir -p $repo_path mv $tempdir/$repo $repo_path/$repo if [ ! -f $GCLONE_PATH/.cdgcache ]; then # If there is no cache, generate the cache manually _cdg_refresh_cache else # If there is a cache, just append the current dir at the end # and sort it back echo $repo_path >> $GCLONE_PATH/.cdgcache echo $repo_path/$repo >> $GCLONE_PATH/.cdgcache cat $GCLONE_PATH/.cdgcache | sort | uniq > $GCLONE_PATH/.cdgcache.tmp mv $GCLONE_PATH/.cdgcache.tmp $GCLONE_PATH/.cdgcache fi retval=0 else retval=1 fi # Remove the temp dir rm -rf $tempdir return $retval } cdg() { if [ $# -ne 1 ]; then echo "This function expects a single parameter" return 1 else found_dirs=`_cdg_existing_dirs | grep /$1$` total=`echo $found_dirs | wc -l` if [[ "" == "$found_dirs" ]]; then echo "$1 not found, refreshing cache" _cdg_refresh_cache return 2 elif [ $total -gt 1 ]; then counter=0 echo "Multiple entries for $1 found:" echo $found_dirs | while read found_dir; do counter=$(($counter+1)) echo "["$counter"]" $found_dir done read choice if [[ "$choice" == "" ]]; then cd `echo $found_dirs | head -1 | tail -1` elif [[ "$choice" =~ '^[0-9]+$' ]] && [ $choice -le $total ] && [ $choice -gt 0 ]; then cd `echo $found_dirs | head -$choice | tail -1` else echo "I expected a number that was less than the max..." return 3 fi return 3 else cd $found_dirs > /dev/null 2>&1 if [ $? -ne 0 ]; then echo "cd didn't work, refreshing cache..." _cdg_refresh_cache return 4 fi fi fi } cdgclone() { gclone $1 && cdg `basename $1` } _cdg() { _arguments "1: :($(_cdg_existing_dirs | rev | cut -d '/' -f 1 | rev))" } compdef _cdg cdg _cdg_refresh_cache() { tmpfile=`mktemp` find $GCLONE_PATH -maxdepth 3 \ -not -name ".cdgcache" \ -not -name "git" | sort > $tmpfile mv $tmpfile $GCLONE_PATH/.cdgcache } _cdg_existing_dirs() { if [ ! -f $GCLONE_PATH/.cdgcache ]; then _cdg_refresh_cache fi cat $GCLONE_PATH/.cdgcache } fi