-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathadd-user-to-repository.sh
More file actions
executable file
·75 lines (65 loc) · 2.44 KB
/
add-user-to-repository.sh
File metadata and controls
executable file
·75 lines (65 loc) · 2.44 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
72
73
74
75
#!/bin/bash
# Adds a user to a repo
function print_usage {
echo "Usage: $0 <org> <repo> <role> <user> [skip_invite_check]"
echo "Example: ./add-user-to-repository.sh joshjohanning-org my-repo ADMIN joshjohanning"
echo "Example: ./add-user-to-repository.sh joshjohanning-org my-repo ADMIN joshjohanning true"
echo "Valid roles: ADMIN, MAINTAIN, WRITE, TRIAGE, READ"
echo "skip_invite_check: true to skip checking/canceling pending invitations, defaults to false"
exit 1
}
if [ -z "$4" ]; then
print_usage
fi
org="$1"
repo="$2"
permission=$(echo "$3" | tr '[:lower:]' '[:upper:]')
user="$4"
skip_invite_check="${5:-false}"
case "$permission" in
"ADMIN" | "MAINTAIN" | "WRITE" | "TRIAGE" | "READ")
;;
*)
print_usage
;;
esac
# Check for existing pending invitations (unless skipped)
if [ "$skip_invite_check" != "true" ]; then
echo "Checking for existing invitations for $user..."
invitation_data=$(gh api "/repos/$org/$repo/invitations" --jq ".[] | select(.invitee.login == \"$user\") | {id: .id, expired: .expired}" 2>/dev/null)
if [ -n "$invitation_data" ]; then
invitation_id=$(echo "$invitation_data" | jq -r '.id')
is_expired=$(echo "$invitation_data" | jq -r '.expired')
if [ "$is_expired" = "true" ]; then
echo "Found expired invitation (ID: $invitation_id) for $user. Canceling it..."
gh api -X DELETE "/repos/$org/$repo/invitations/$invitation_id"
if [ $? -eq 0 ]; then
echo "Successfully canceled expired invitation."
else
echo "Warning: Failed to cancel expired invitation. Proceeding anyway..."
fi
else
echo "Found active invitation (ID: $invitation_id) for $user. Leaving it as is."
echo "Skipping new invitation since an active one already exists."
exit 0
fi
fi
else
echo "Skipping invitation check as requested..."
fi
echo "Adding/inviting $user to $org/$repo with $permission permission..."
response=$(gh api -X PUT /repos/$org/$repo/collaborators/$user -f permission=$permission 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
echo "✅ Successfully ensured $user has $permission permission on $org/$repo. (User may have been newly added or permission updated)"
else
# Check for specific error cases
if echo "$response" | grep -q "Not Found"; then
echo "❌ Error: Repository $org/$repo not found or insufficient permissions."
exit 1
else
echo "❌ Error adding $user to $org/$repo:"
echo "$response"
exit 1
fi
fi