Last active
March 4, 2019 23:04
-
-
Save honzahommer/c8987e1e33b2098452e839d5e8ed765d to your computer and use it in GitHub Desktop.
Get GitHub or GitLab upstream repo URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
repo_upstream_url() { | |
local repo_url | |
local repo_host | |
local repo_path | |
local repo_upstream | |
local repo_api_private_token | |
local repo_api_url | |
local repo_api_key | |
repo_url=`git remote get-url origin 2> /dev/null` | |
if [ -z "$repo_url" ]; then | |
echo "no remote origin url" | |
return 1 | |
fi | |
repo_host=`echo "$repo_url" | sed -e 's|.*://||' -e 's|git@||' -Ee 's|([^/:]+).*|\1|'` | |
repo_path=`echo "$repo_url" | sed -e 's|.*://||' -e 's|git@||' -e 's|:|/|' -e 's|^[^/]*/||' -e 's|.git$||'` | |
if [ -z "$repo_host" ] || [ -z "$repo_path" ]; then | |
echo "no repo host or repo path" | |
return 1 | |
fi | |
case $repo_host in | |
github.com) | |
repo_api_url=https://api.github.com/repos/$repo_path | |
repo_api_key=.source.clone_url | |
;; | |
*) | |
repo_api_private_token=`awk -F'[:=]' '$1==host && $2==property { print $3 }' host="$repo_host" property=private_token ~/.gitlabrc 2> /dev/null` | |
if [ -n "$repo_api_private_token" ]; then | |
repo_api_url="https://$repo_host/api/v4/projects/`echo $repo_path | xxd -plain | tr -d '\n' | sed 's/\(..\)/%\1/g'`?private_token=$repo_api_private_token" | |
repo_api_key=.forked_from_project.http_url_to_repo | |
fi | |
;; | |
esac | |
if [ -z "$repo_api_url" ] || [ -z "$repo_api_key" ]; then | |
echo "no api url or object key" | |
return 1 | |
fi | |
repo_upstream=`wget -qO- "$repo_api_url" | jq -r "if $repo_api_key != null then $repo_api_key else \"\" end"` | |
if [ -z "$repo_upstream" ]; then | |
echo "no upstream found" | |
return 1 | |
fi | |
echo $repo_upstream | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment