Skip to content

Instantly share code, notes, and snippets.

@nuffin
Created June 1, 2024 14:11
Show Gist options
  • Save nuffin/1d41eaf9252ee8b689f35d05e0104505 to your computer and use it in GitHub Desktop.
Save nuffin/1d41eaf9252ee8b689f35d05e0104505 to your computer and use it in GitHub Desktop.
clonegit command, to clone git repositories in a structured directory
# Usage:
# clonegit git-repo-url
# clonegit -c git-repo-url
# to clone and change into the cloned directory
# clonegit -k /path/to/private-ssh-key git-repo-url
# to clone the repository with a specified ssh key
#
# tested in bash and zsh, in Linux and macOS
test -z "${GITROOT}" && export GITROOT=${HOME}/studio
clonegit()
{
#echo BASH_VERSION=${BASH_VERSION}
#echo ZSH_VERSION=${ZSH_VERSION}
local CMD
test ! -z "${BASH_VERSION}" && CMD=${FUNCNAME}
test ! -z "${ZSH_VERSION}" && CMD=${funcstack[1]}
usage()
{
echo "Usage: ${CMD} [-c|--chdir] [-k /path/to/ssh-key-file] [email protected]:owner/project.git|https://gitserver.com/owner/project.git"
}
local GETOPT_RESULT
GETOPT_RESULT=$(getopt --name "${CMD}" --unquoted --options 'ck:' --longoptions 'chdir,key:' -- "$@")
test $? -ne 0 && usage && return 1
eval set -- "${GETOPT_RESULT}"
local CHDIR_AFTER_CLONE
local SSH_KEY_PATH
local GIT_SSH_KEY_OPTION
while test "${1}" != "--"; do
case ${1} in
-c|--chdir)
CHDIR_AFTER_CLONE=1
;;
-k|--key)
SSH_KEY_PATH=${2}
shift
;;
?)
echo "Invalid option: -${OPTARG}."
usage
return 1
;;
esac
shift
done
shift ## skip --
local repo=${1}
local repo_dir=${2}
test -z "${repo}" && usage && return
[[ "${repo}" = *.git ]] || repo="${repo}.git"
local hostname
local username
local reposname
read hostname username reposname << __EOF__
$(echo ${repo} | sed -E "s,.git$,,; s,(.*@|(https|http|ssh)://)([a-z0-9\.-]+)(:[0-9]+/|:|/)(.*)/(.*),\3 \5 \6,")
__EOF__
#echo hostname=${hostname}
#echo username=${username}
#echo reposname=${reposname}
local target_dir=${GITROOT}/${hostname}/${username}
test ! -z ${SSH_KEY_PATH} && GIT_SSH_KEY_OPTION="-c core.sshCommand=\"ssh -i ${SSH_KEY_PATH}\""
echo -n "Cloning ${repo} "
test ! -z "${SSH_KEY_PATH}" && echo -n "with ssh key file ${SSH_KEY_PATH} "
echo "into ${target_dir}/ as ${reposname} ..."
test -d ${target_dir} || mkdir -p ${target_dir}
(cd ${target_dir} && sh -c "git clone ${GIT_SSH_KEY_OPTION[@]} ${repo} ${repo_dir}")
test ! -z "${CHDIR_AFTER_CLONE}" && cd ${target_dir}/${reposname}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment