General clone into ~/src/TLD/some/dir from a git uri function.
Tries to strip out miscellany that we don’t need from the uri. Also allows wrapper functions that simplify usage.
Note the bb, gh, and mt wrappers which make it easy to get repos from bitbucket, github, and my own sites respectively.
Usage is simply:
try_git some_uri optional_branch_if_not_master
The gh wrapper wraps this and simplifies usage by setting up the uri as https so we can do the following example:
gh user/repo maybe_branch
This checks out something from https://github.com/user/repo.git to ~/src/github.com/user/repo
This also makes for a somewhat easy way to cd into the dir as well without push/popd. The bb wrapper behaves the same.
Presuming using the bare try_git function, the dir in ~/src/TLD is simply what comes after the tld.
Example:
try_git git://example.tld/some/random/path.git checks out to ~/src/example.tld/some/random/path
try_git()
{
# assume https if input doesn't contain a protocol
proto=https
destination=${HOME}/src
branch="${2:-master}"
echo "${1}" | grep '://' > /dev/null 2>&1
[ $? = 0 ] && proto=$(echo "${1}" | sed -e 's|[:]\/\/.*||g')
git_dir=$(echo "${1}" | sed -e 's|.*[:]\/\/||g')
rrepo="${proto}://${git_dir}"
# strip user@, :NNN, and .git from input uri's
repo="${destination}/"$(echo "${git_dir}" |
sed -e 's/\.git$//g' |
sed -e 's|.*\@||g' |
sed -e 's|\:[[:digit:]]\{1,\}\/|/|g' |
tr -d '~')
if [ ! -d "${repo}" ]; then
if git ls-remote "${rrepo}" > /dev/null 2>&1; then
install -dm755 "${repo}"
echo "git clone ${rrepo} ${repo}"
git clone --recursive "${rrepo}" "${repo}"
else
echo "${rrepo} doesn't look to be a git repository"
fi
fi
if [ "${branch}" != "master" ]; then
wtdir="${repo}@${branch}"
if [ ! -d "${wtdir}" ]; then
if git branch -r --list 'origin/*' | grep -E "^\s+origin/${branch}$" > /dev/null 2>&1; then
git worktree add ${repo}@${branch} ${branch}
else
echo "${wtdir} branch ${branch} not present in ${rrepo}"
return
fi
fi
echo "${wtdir}" | sed -e "s|$HOME|~|"
cd "${wtdir}"
else
if [ -d "${repo}" ]; then
echo "${repo}" | sed -e "s|$HOME|~|"
cd "${repo}"
fi
fi
}
mt()
{
try_git "ssh://gitea@git.mitchty.net:2222/${1}" "${2:-master}"
}
gh()
{
try_git "https://github.com/${1}" "${2:-master}"
}
bb()
{
try_git "https://bitbucket.org/${1}" "${2:-master}"
}