Skip to content

Instantly share code, notes, and snippets.

@shouptech
Last active June 10, 2021 01:35
Show Gist options
  • Save shouptech/740e6842ca795620a3f5c86a23c41931 to your computer and use it in GitHub Desktop.
Save shouptech/740e6842ca795620a3f5c86a23c41931 to your computer and use it in GitHub Desktop.
Cloning repos with namespaces
#!/bin/bash
#
# This scripts will clone a git repository into its own namespace, in the
# directory $HOME/code.
#
# For example, the URL: git@gitlab.com:shouptech/example.git, would clone to:
# $HOME/code/gitlab.com/shouptech/example
#
# This script is intended to make managing multiple repositories from multiple
# sources easier.
#
# It currently supports URLs in the format of
# https://<servername>/<projectpath>.git
# and
# git@<servername>:<projectpath>.git
#
# Projects will be cloned to:
# $HOME/code/<servername>/<projectpath>
# Exit codes used. See sysexits.h
CLONE_PREFIX="$HOME/code"
EX_OK=0
EX_USAGE=64
EX_DATAERR=65
usage() {
echo "Usage: $0 clone_url"
exit $EX_USAGE
}
clone_repo() {
clone_url="$1"
clone_path="$2"
echo "Cloning to path $clone_path..."
if [ -d "$clone_path" ]; then
echo "$clone_path already exists. Exiting for safety..."
exit $EX_DATAERR
fi
mkdir -p "$clone_path"
git clone "$clone_url" "$clone_path"
}
parse_path() {
clone_url="$1"
if [[ "$clone_url" == git* ]]; then
after_git=${clone_url/#git@/}
before_git=${after_git/%.git/}
clone_path="$CLONE_PREFIX/${before_git/://}"
elif [[ "$clone_url" == https* ]]; then
after_https=${clone_url/#https:\/\//}
clone_path="$CLONE_PREFIX/${after_https/%.git/}"
else
echo "$1 is not a supported git URL for this script."
exit $EX_DATAERR
fi
clone_repo $clone_url $clone_path
}
main() {
if [ -z "$1" ]; then
usage
fi
parse_path "$1"
}
main "$@"
exit $EX_OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment