Skip to content

Instantly share code, notes, and snippets.

@teknoraver
Created August 8, 2024 11:06
Show Gist options
  • Save teknoraver/560ba78581e457ab7c90086874932072 to your computer and use it in GitHub Desktop.
Save teknoraver/560ba78581e457ab7c90086874932072 to your computer and use it in GitHub Desktop.
Clone a GitHub repo and, if it's a fork, setup the upstream as remote
#!/bin/sh
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <git-repo-url>"
exit 1
fi
url=$1
repo=$url
case "$url" in
https://*)
repo=${repo#https://github.com/*}
repo=${repo%*.git}
;;
[email protected]:*)
repo=${repo#[email protected]:*}
repo=${repo%*.git}
;;
*)
echo "$url is not a GitHub repo"
;;
esac
dir=${repo#*/}
[email protected]:$repo.git
api_url=https://api.github.com/repos/$repo
json=/tmp/ghclone-$$
curl -s "$api_url" >$json
fork=$(jq -r .fork <"$json")
[ "$fork" = true ] &&
upstream=$(jq -r .source.clone_url <"$json")
rm -f "$json"
git clone "$downstream" || exit
# Repo is not a fork
[ -z "$upstream" ] && exit 0
cd "$dir"
exec git remote add -f upstream "$upstream"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment