forked from allevaton/starterupper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.sh
412 lines (369 loc) · 14.7 KB
/
github.sh
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/bin/bash
source utility.sh
# Github non-interactive functions
# ---------------------------------------------------------------------
# Helpers
# Invoke a Github API method requiring authorization using curl
Github_invoke() {
local method=$1; shift
local url=$1; shift
local data=$1;
local header="Authorization: token $(git config --global github.token)"
curl -i --request "$method" -H "$header" -d "$data" "https://api.github.com$url" 2> /dev/null
}
# Queries
# Is the name available on Github?
Github_nameAvailable() {
local username="$1"
local result="$(curl -i https://api.github.com/users/$username 2> /dev/null)"
if [[ -z $(echo $result | grep "HTTP/1.1 200 OK") ]]; then
Utility_success
else
Utility_fail
fi
}
# A valid Github username is not available, by definition
Github_validUsername() {
local username="$1"
# If the name is legit, ...
if [[ $(Utility_nonEmptyValueMatchesRegex "$username" "^[0-9a-zA-Z][0-9a-zA-Z-]*$") ]]; then
# And unavailable, ...
if [[ ! $(Github_nameAvailable $username) ]]; then
# It's valid
Utility_success
else
Utility_fail
fi
else
# Otherwise, it's not valid
Utility_fail
fi
}
# Are we logged into Github?
Github_loggedIn() {
if [[ -n "$(git config --global github.token)" ]]; then
Utility_success
else
Utility_fail
fi
}
# Did the user add their email to the Github account?
Github_emailAdded() {
local email="$1"
local emails="$(Github_invoke GET "/user/emails" "" | tr '\n}[]{' ' \n ')"
if [[ -z $(echo "$emails" | grep "$email") ]]; then
Utility_fail
else
Utility_success
fi
}
# Did the user verify their email with Github?
Github_emailVerified() {
local email="$1"
local emails="$(Github_invoke GET "/user/emails" "" | tr '\n}[]{' ' \n ')"
if [[ -z $(echo "$emails" | grep "$email" | grep "verified...true") ]]; then
Utility_fail
else
Utility_success
fi
}
# What plan does the user have?
Github_plan() {
Github_invoke GET /user '' \
| sed -n -e '/[\"]plan[\"]/,${p}' \
| grep -E "[\"]name[\"]" \
| sed -e 's/ *[\"]name[\"]: [\"]\(.*\)[\"].*/\1/' \
| tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'
}
# Is the user's plan upgraded?
Github_upgradedPlan() {
local plan="$(Github_plan)"
# If we got nothing back, we're not authenticated
if [[ -z "$plan" ]]; then
Utility_fail
# If we got something back, and it's not the free plan, we're good
elif [[ "$plan" != "free" ]]; then
Utility_success
# The free plan won't cut it
else
Utility_fail
fi
}
# start -> logged_in -> added email -> verified email -> upgraded account
Github_accountStatus() {
local email="$(User_getEmail)"
if [[ ! $(Github_loggedIn) ]]; then
printf "start"
elif [[ ! $(Github_emailAdded "$email") ]]; then
printf "logged_in"
elif [[ ! $(Github_emailVerified "$email") ]]; then
printf "added_email"
elif [[ ! $(Github_upgradedPlan) ]]; then
printf "verified_email"
else
printf "upgraded"
fi
}
# Commands
# Log out of Github
Github_logout() {
git config --global --unset github.login
git config --global --unset github.token
}
# Add email to Github account, if not already added
# Even though this adds email programmatically, Github will not send a verification email.
Github_addEmail() {
local email="$1"
if [[ ! $(Github_emailAdded "$email") ]]; then
Github_invoke POST "/user/emails" "[\"$email\"]" > /dev/null
fi
}
# Github CLI-interactive functions
# ---------------------------------------------------------------------
Github_hasAccount() {
local hasAccount="n"
# If we don't have their github login, ...
if [[ -z "$(git config --global github.login)" ]]; then
# Ask if they're on github yet
read -p "Do you have a Github account (yes or No [default])? " hasAccount < /dev/tty
# Let's assume that they don't by default
if [[ $hasAccount != [Yy]* ]]; then
Utility_fail
else
Utility_success
fi
else
Utility_success
fi
}
# Ask the user if they have an account yet, and guide them through onboarding
Github_join() {
local hasAccount="n"
# If we don't have their github login, ...
if [[ -z "$(git config --global github.login)" ]]; then
# Ask if they're on github yet
read -p "Do you have a Github account (yes or No [default])? " hasAccount < /dev/tty
echo -e "\e[1;37;41mIMPORTANT\e[0m: Before we proceed, you need to complete ALL of these steps:"
# Let's assume that they don't by default
if [[ $hasAccount != [Yy]* ]]; then
echo "1. Join Github, using $(User_getEmail) as your email address."
echo "2. Open your email inbox and verify your school email address."
echo "3. Request an individual student educational discount."
echo ""
echo "Press enter to join Github."
Interactive_fileOpen "https://github.com/join"
else
echo "1. Share and verify your school email address with Github."
echo "2. Request an individual student educational discount."
echo ""
fi
Github_verifyEmail
Github_getDiscount
fi
}
# Set the Github username, if not already set
Github_setUsername() {
Github_join
if [[ -z "$(git config --global github.token)" ]]; then
Interactive_setValue "github.login" "$(Host_getUsername "github")" "Github_validUsername" "Github username" "\nNOTE: Usernames are case-sensitive. See: https://github.com"
fi
}
# Attempt to login to Github
Github_authorize() {
local password="$1"; shift
local code="$1"
read -r -d '' json <<-EOF
{
"scopes": ["repo", "public_repo", "user", "write:public_key", "user:email"],
"note": "starterupper $(date --iso-8601=seconds)"
}
EOF
curl -i -u $(Host_getUsername "github"):$password -H "X-GitHub-OTP: $code" -d "$json" https://api.github.com/authorizations 2> /dev/null
}
# Idea: refactor to use interactive_setValue instead.
# Acquire authentication token and store in github.token
Github_authenticate() {
# Don't bother if we already got the authentication token
if [[ -n "$(git config --global github.token)" ]]; then
return 0
fi
local token="HTTP/1.1 401 Unauthorized"
local code=''
local password=''
# As long as we're unauthorized, ...
while [[ ! -z "$(echo $token | grep "HTTP/1.1 401 Unauthorized" )" ]]; do
# Ask for a password
if [[ -z "$password" ]]; then
read -s -p "Enter Github password (not shown or saved): " password < /dev/tty
echo # We need this, otherwise it'll look bad
fi
# Generate authentication token request
token=$(Github_authorize "$password" "$code")
# If we got a bad credential, we need to reset the password and try again
if [[ ! -z $(echo $token | grep "Bad credential") ]]; then
echo -e "\e[1;37;41mERROR\e[0m: Incorrect password for user $(Host_getUsername "github"). Please wait."
password=''
sleep 1
fi
# If the user has two-factor authentication, ask for it.
if [[ ! -z $(echo $token | grep "two-factor" ) ]]; then
read -p "Enter Github two-factor authentication code: " code < /dev/tty
fi
done
# By now, we're authenticated, ...
if [[ ! -z $(echo $token | grep "HTTP/... 20." ) ]]; then
# So, extract the token and store it in github.token
token=$(echo $token | tr '"' '\n' | grep -E '[0-9a-f]{40}')
git config --global github.token "$token"
echo "Authenticated!"
# Or something really bad happened, in which case, github.token will remain unset...
else
# When bad things happen, degrade gracefully.
echo -n -e "\e[1;37;41mERROR\e[0m: "
echo "$token" | grep "HTTP/..."
echo
echo "I encountered a problem and need your help to finish these setup steps:"
echo
echo "1. Update your Github profile to include your full name."
echo "2. Create private repository $REPO on Github."
echo "3. Add $INSTRUCTOR_GITHUB as a collaborator."
echo "4. Share your public SSH key with Github."
echo "5. Push to your private repository."
echo
fi
}
# Share full name with Github
Github_setFullName() {
local fullName="$(User_getFullName)"
# If authentication failed, degrade gracefully
if [[ -z $(git config --global github.token) ]]; then
echo "Press enter to open https://github.com/settings/profile to update your Github profile."
echo "On that page, enter your full name. $(Interactive_paste "$fullName" "your full name")"
echo "Then, click Update profile."
Interactive_fileOpen "https://github.com/settings/profile"
# Otherwise, use the API
else
echo "Updating Github profile information..."
Github_invoke PATCH "/user" "{\"name\": \"$fullName\"}" > /dev/null
fi
}
# Share the public key
Github_sharePublicKey() {
local githubLogin="$(Host_getUsername "github")"
# If authentication failed, degrade gracefully
if [[ -z "$(git config --global github.token)" ]]; then
echo "Press enter to open https://github.com/settings/ssh to share your public SSH key with Github."
echo "On that page, click Add SSH Key, then enter these details:"
echo "Title: $(hostname)"
echo "Key: $(Interactive_paste "$(SSH_getPublicKey)" "your public SSH key")"
Interactive_fileOpen "https://github.com/settings/ssh"
# Otherwise, use the API
else
# Check if public key is shared
local publickeyShared=$(curl -i https://api.github.com/users/$githubLogin/keys 2> /dev/null)
# If not shared, share it
if [[ -z $(echo "$publickeyShared" | grep $(SSH_getPublicKey | sed -e 's/ssh-rsa \(.*\)=.*/\1/')) ]]; then
echo "Sharing public key..."
Github_invoke POST "/user/keys" "{\"title\": \"$(hostname)\", \"key\": \"$(SSH_getPublicKey)\"}" > /dev/null
fi
fi
# Test SSH connection on default port (22)
if [[ ! $(SSH_connected "github.com") ]]; then
echo "Your network has blocked port 22; trying port 443..."
printf "Host github.com\n Hostname ssh.github.com\n Port 443\n" >> ~/.ssh/config
# Test SSH connection on port 443
if [[ ! $(SSH_connected "github.com") ]]; then
echo "WARNING: Your network has blocked SSH."
ssh_works=false
fi
fi
}
# Create a private repository on Github
Github_createPrivateRepo() {
# If authentication failed, degrade gracefully
if [[ -z "$(git config --global github.token)" ]]; then
Github_manualCreatePrivateRepo
return 0
fi
local githubLogin="$(Host_getUsername "github")"
# Don't create a private repo if it already exists
if [[ -z $(Github_invoke GET "/repos/$githubLogin/$REPO" "" | grep "Not Found") ]]; then
return 0
fi
echo "Creating private repository $githubLogin/$REPO on Github..."
local result="$(Github_invoke POST "/user/repos" "{\"name\": \"$REPO\", \"private\": true}")"
if [[ ! -z $(echo $result | grep "HTTP/... 4.." ) ]]; then
echo -n -e "\e[1;37;41mERROR\e[0m: "
echo "Unable to create private repository."
echo
echo "Troubleshooting:"
echo "* Make sure you have verified your school email address."
echo "* Apply for the individual student educational discount if you haven't already done so."
echo "* If you were already a Github user, free up some private repositories."
echo
Github_verifyEmail
Github_getDiscount
Github_manualCreatePrivateRepo
fi
}
# Add a collaborator
Github_addCollaborator() {
local githubLogin="$(Host_getUsername "github")"
# If authentication failed, degrade gracefully
if [[ -z "$(git config --global github.token)" ]]; then
echo "Press enter to open https://github.com/$githubLogin/$REPO/settings/collaboration to add $1 as a collaborator."
echo "$(Interactive_paste "$1" "$1")"
echo "Click Add collaborator."
Interactive_fileOpen "https://github.com/$githubLogin/$REPO/settings/collaboration"
# Otherwise, use the API
else
echo "Adding $1 as a collaborator..."
Github_invoke PUT "/repos/$githubLogin/$REPO/collaborators/$1" "" > /dev/null
fi
}
# Clean up everything but the repo (BEWARE!)
Github_clean() {
echo "Delete starterupper-script under Personal access tokens"
Interactive_fileOpen "https://github.com/settings/applications"
sed -i s/.*github.com.*// ~/.ssh/known_hosts
git config --global --unset user.name
git config --global --unset user.email
git config --global --unset github.login
git config --global --unset github.token
rm -f ~/.ssh/id_rsa*
}
# Add collaborators
Github_addCollaborators() {
cd ~/$REPO
for repository in $(Github_invoke GET "/user/repos?type=member\&sort=created\&page=1\&per_page=100" "" | grep "full_name.*$REPO" | sed s/.*full_name....// | sed s/..$//); do
git remote add ${repository%/*} [email protected]:$repository.git 2> /dev/null
done
git fetch --all
}
# Deprecate these
# Create a private repository manually
Github_manualCreatePrivateRepo() {
echo "Press enter to open https://github.com/new to create private repository $REPO on Github."
echo "On that page, for Repository name, enter: $REPO. $(Interactive_paste "$REPO" "the repository name")"
echo "Then, select Private and click Create Repository (DON'T tinker with other settings)."
Interactive_fileOpen "https://github.com/new"
}
# Ask user to verify email
Github_verifyEmail() {
echo "Press enter to open https://github.com/settings/emails to add your school email address."
echo "Open your email inbox and wait a minute for an email from Github."
echo "Follow its instructions: click the link in the email and click Confirm."
echo "$(Interactive_paste $(User_getEmail) "your school email")"
Interactive_fileOpen "https://github.com/settings/emails"
}
# Ask the user to get the discount
Github_getDiscount() {
echo "Press enter to open https://education.github.com/discount_requests/new to request an individual student educational discount from Github."
Interactive_fileOpen "https://education.github.com/discount_requests/new"
}
# Github_plan
# Hmm, deep screen sandboxing mode will run a command twice. This is bad.
# Github_authenticate
# Github_addEmail "[email protected]"
# echo $(Github_emailAdded "[email protected]")
# echo $(Github_emailVerified "[email protected]")