forked from fastai/fastai
/
fastai-make-pr-branch-py
333 lines (254 loc) · 10.8 KB
/
fastai-make-pr-branch-py
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
#!/usr/bin/env python3
"""
This program will checkout a forked version of the original repository, sync it with the original, create a new branch and set it up for a PR.
usage:
{me} auth user_name repo_name new_branch_name
parameters:
auth: ssh or https (use ssh if your github account is setup to use ssh
user: your github username
repo: repository name to fork/use
branch: name of the branch to create
example:
{me} ssh my-github-username fastai new-feature-branch
notes:
- if the original repository has been already forked, it'll be done by the program (it will ask you for your github password)
- if the program is run from a directory that already contains a checked out git repository that matches the parameters, it will re-use it instead of making a new checkout
- if the requested branch already exists it'll reuse it
- if the master is out of sync with the original master it'll sync it first
"""
import argparse
import os
from os.path import basename, exists
from pathlib import Path
import re
import sys
from subprocess import call, PIPE, Popen
from textwrap import dedent
PY3 = sys.version_info >= (3, 0)
ME = basename(sys.argv[0])
ORIG_USER_NAME = 'fastai'
ENV_VAR = 'GITHUB_TOKEN'
def main():
check_token()
args = parse_args()
was_already_forked = fork_if_needed(args)
need_clone = clone_is_needed(args.url)
if need_clone:
clone(args.url, args.path)
run_after_git_clone()
track_upstream(strip_token(args.orig_repo_url))
if was_already_forked:
sync_with_master(args)
create_branch(args.new_branch_name)
set_upstream(args.new_branch_name)
print_instructions(args, need_clone)
def parse_args():
parser = SysExitArgumentParser(usage=__doc__.format(me=ME))
parser.add_argument(
'auth',
metavar='AUTH', choices={'https'}, # no ssh support for now
help='ssh or https (use ssh if your github account is setup to use ssh)'
)
parser.add_argument(
'user_name',
metavar='USER',
help='your github username'
)
parser.add_argument(
'repo_name',
metavar='REPO',
help='repository name to fork/use'
)
parser.add_argument(
'new_branch_name',
metavar='BR',
help='name of the branch to create'
)
parser.add_argument(
'-orig', '--orig-user-name',
metavar='ORIG', required=False, default=ORIG_USER_NAME,
help='name of original repository user (default: %(default)s)'
)
args = parser.parse_args()
args.token = os.environ[ENV_VAR]
args.prefix = f'https://{args.token}@github.com'
# support token access only
# if args.auth == 'ssh':
# args.prefix = f'git@github.com:'
# else:
# args.prefix = f'https://{args.token}@github.com/'
args.path = f'{args.repo_name}-{args.new_branch_name}'
args.url = f'{args.prefix}{args.user_name}/{args.repo_name}.git'
args.orig_repo_url = f'{args.prefix}{args.orig_user_name}/{args.repo_name}.git'
return args
def check_curl_is_available():
"Check if curl is available and terminate the script if it isn't."
try:
call(['curl'], stdout=PIPE, stderr=PIPE)
except FileNotFoundError:
print(f"{ME} requires 'curl' but it's not installed. Aborting.")
sys.exit(1)
def check_token():
if ENV_VAR not in os.environ:
print(dedent('''
*** WARNING! ***
The HTTPS authentication method requires to explicitly enter your Github user's credentials.
Unfortunately, up to the moment the tool doesn't support secured credentials entering. Therefore,
you need to have a GITHUB_TOKEN environment variable set to use HTTPS authentication method.
Please use the following instruction to setup token, or switch to SSH.
1. Create an access token:
https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line
2. Copy the token and save it as an environment variable:
$ echo "export GITHUB_TOKEN=<your-token>" >> ~/.bashrc
$ source ~/.bashrc
3. Now the token is used for an access.
Also, if you would like to help to improve this tool and enable the possibility to safely
enter the credentials, please submit a PR! Check the following discussion to know more:
https://forums.fast.ai/t/port-fastai-make-pr-branch-from-bash-to-python/29853/28
*** WARNING! ***
'''))
sys.exit(1)
def fork_if_needed(args):
"Fork the repo if it hasn't been forked yet."
url, user, orig, repo = args.url, args.user_name, args.orig_user_name, args.repo_name
print('\n\n*** Checking if we need to fork')
if run_and_check_success(f'git ls-remote {url} >/dev/null 2>&1'):
print(f'{url} is already forked')
return True
else:
print(f"{url} doesn't exist - need to fork")
check_curl_is_available()
creds = user if args.auth == 'ssh' else f'{user}:{args.token}'
run(f"curl -u {creds} https://api.github.com/repos/{orig}/{repo}/forks -d ''")
return False
def clone_is_needed(url):
"Support an already existing checkout if it matches the desired parameters, but only if it's not dirty."
if not exists('.git'):
return True
print('detected current dir to be a git repository')
output = run_and_read_all('git status -s')
if output:
print('git status is not clean, not going to re-use the current checkout')
return True
cur_url = run_and_read_all('git config --get remote.origin.url')
if cur_url != url:
return True
print('already on the right repo, going to re-use the current checkout')
return False
def clone(url, path):
"Clone `url` into `path`."
print(f'\n\n*** Cloning {url} to {path}')
run(f'git clone {url} {path}')
os.chdir(path)
print(f'cd {path}')
def run_after_git_clone():
"Run fastai's tools/run-after-git-clone if exists."
tool = Path("tools")/"run-after-git-clone"
if tool.exists():
print(f'\n\n*** run {tool}')
run(f'{sys.executable} {tool}')
def track_upstream(orig_repo_url):
"Setup this fork to track the upstream."
print('\n\n*** Setting up this fork to track the upstream')
run(f"git remote add upstream {orig_repo_url} || echo 'already exists'")
run('git remote -v')
def sync_with_master(args):
"Sync the forked repo master with the upstream master if it hasn't been just forked."
user, repo = args.user_name, args.repo_name
print(f'\n\n*** Syncing {user}/master with {args.orig_user_name}/master')
run('git fetch upstream')
run('git checkout master')
# XXX: this will fail if the user was committing directly to their forked `master` branch is
ok = run_and_check_success('git merge --no-edit upstream/master')
if not ok:
run('git merge --abort')
print(dedent(f'''
Error: {user}/{repo}/master can't be merged with {args.orig_user_name}/{repo}/master.
You must merge manually, or reset {user}/{repo}/master.
See: https://docs-dev.fast.ai/git.html#how-to-reset-your-forked-master-branch
Aborting."
'''), file=sys.stderr)
sys.exit(1)
run('git push')
print('Done')
def create_branch(new_branch_name):
print(f"\n\n*** Creating '{new_branch_name}' branch and setting its upstream for an easy push")
if run_and_check_success(f'git show-branch {new_branch_name} >/dev/null 2>&1'):
print(f'{new_branch_name} already exists, switching to it')
run(f'git checkout {new_branch_name}')
else:
print(f"{new_branch_name} doesn't yet exist, creating")
run(f'git checkout -b {new_branch_name}')
print(f'{new_branch_name} branch was successfully created')
def set_upstream(branch):
print(f"\n\n*** Set this {branch}'s upstream to simplify push and alikes")
run(f'git push --set-upstream origin {branch}')
def print_instructions(args, need_clone):
switch_command = f'cd {args.path}' if need_clone else 'cd .'
print(dedent(f'''
Next do:
1. Switch to the branch dir, unless you're already there:
{switch_command}
2. Validate you're on the right repo/branch by pasting the following into your bash:
echo on repo: $(git config --get remote.origin.url | sed 's|^.*//||; s/.*@//; s/[^:/]\+[:/]//; s/.git$//') branch: $(git branch | sed -n '/\* /s///p')
3. And do your work.
4. When you're done:
git add <newfiles> # if you added new files
git commit -a # if you want to commit all modified/added files
git push # push files into {args.new_branch_name}
5. Then go to:
https://github.com/{args.user_name}/{args.repo_name}/tree/{args.new_branch_name}
review your changes and when you're happy with what you see, submit your PR.
While it's very good to review your PR on github before submitting it, if you want to use a CLI solution,
there are several solutions to choose from:
* https://github.com/github/hub"
* https://github.com/jd/git-pull-request"
* https://github.com/jehiah/git-open-pull"
* https://www.npmjs.com/package/pullr"
'''))
def strip_token(url):
"Removes HTTPS token part from the URL string."
return re.sub("[\d\w]+@github.com", "github.com", url)
# --------------
# Shell wrappers
# --------------
# some ideas are taken from:
#
# https://github.com/pytorch/pytorch/blob/master/torch/utils/collect_env.py
#
class SysExitArgumentParser(argparse.ArgumentParser):
def error(self, message):
print(self.usage)
sys.exit(1)
def run(command):
print(f'running: {command}')
rc, out, err = run_and_return_output(command)
if rc != 0:
print(err)
sys.exit(1)
if out.strip():
print(out)
# (devforfu): Would it be better to replace with a different implementation?
#
# https://forums.fast.ai/t/port-fastai-make-pr-branch-from-bash-to-python/29853/20
#
def run_and_return_output(command):
"Returns (return-code, stdout, stderr)."
p = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
out, err = p.communicate()
rc = p.returncode
if PY3 and out: out = out.decode("utf-8")
if PY3 and err: err = err.decode("utf-8")
return rc, out.strip(), err.strip()
def run_and_read_all(command):
"Runs command using run_lambda; reads and returns entire output if rc is 0."
rc, out, _ = run_and_return_output(command)
if rc is not 0:
return None
return out
def run_and_check_success(command):
print(f'running: {command}')
rc, _, _ = run_and_return_output(command)
return rc == 0
if __name__ == '__main__':
main()