Repository navigation
Expand file tree
/
Copy pathgit-fork
More file actions
executable file
·71 lines (61 loc) · 1.98 KB
/
Copy pathgit-fork
File metadata and controls
executable file
·71 lines (61 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env bash
set -euo pipefail
GH_USERNAME="${1:-gonzaloserrano}"
# Ensure we are inside a git repo
if [ ! -f ".git/config" ]; then
echo "No .git/config found. Run this inside a git repository." >&2
exit 1
fi
# Ensure origin exists
if ! git config --get remote.origin.url >/dev/null 2>&1; then
echo "No 'origin' remote found in this repo." >&2
exit 1
fi
# If fork already exists, do nothing (except print config)
if git config --get remote.fork.url >/dev/null 2>&1; then
echo "Remote 'fork' already exists. Nothing to do."
echo
cat .git/config
exit 0
fi
origin_url="$(git config --get remote.origin.url)"
origin_url="${origin_url%/}" # strip trailing slash
# Build fork URL based on origin URL
case "$origin_url" in
git@github.com:*)
# SSH form: git@github.com:ORG/REPO(.git)
repo_path="${origin_url#git@github.com:}" # ORG/REPO(.git)
repo_name="${repo_path#*/}" # REPO(.git)
fork_url="git@github.com:${GH_USERNAME}/${repo_name}"
;;
https://github.com/*)
# HTTPS form: https://github.com/ORG/REPO(.git)
repo_path="${origin_url#https://github.com/}" # ORG/REPO(.git)
repo_name="${repo_path#*/}" # REPO(.git)
fork_url="https://github.com/${GH_USERNAME}/${repo_name}"
;;
*)
echo "Unsupported origin URL format: $origin_url" >&2
exit 1
;;
esac
# Check if fork exists on GitHub, create if not
org_name="${repo_path%%/*}"
repo_base="${repo_name%.git}" # strip .git suffix if present
if ! gh repo view "${GH_USERNAME}/${repo_base}" >/dev/null 2>&1; then
echo "Fork ${GH_USERNAME}/${repo_base} does not exist on GitHub."
read -rp "Create it? [y/N] " answer
if [[ "$answer" =~ ^[Yy]$ ]]; then
gh repo fork "${org_name}/${repo_base}" --remote=false
else
echo "Aborted."
exit 1
fi
fi
# Add the fork remote
git remote add fork "$fork_url"
# Ensure the desired fetch refspec
git config remote.fork.fetch "+refs/heads/*:refs/remotes/fork/*"
# Print resulting config
echo
cat .git/config