-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitcommit
executable file
·292 lines (250 loc) · 9.72 KB
/
gitcommit
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
#!/usr/bin/env python3
# get the git difference
# git diff <local branch> <remote>/<remote branch>
# write output in temporary file
# if the user requests a force push:
# git push -f -u origin <branch>
# If a PR is provided then
# push the difference into the local repository and get the url
# write a comment into the PR with the diff:
# gh pr comment <PR> --body <url> -R <REPO>
#
import sys, git, os, argparse, subprocess, re, pathlib, shutil, json
from datetime import datetime
from command import Command
from util import prformat, fg, bg
dry_run = False
verbose = False
timeout = 1000
def gh_get_all_pr_users(pr, target, owner):
global dry_run
global verbose
cmd = Command('gh pr view %d -R %s --json reviews' %
(pr, target), verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to get users in PR %d" % (pr))
exit(1)
cmd = Command('gh pr view %d -R %s --json comments' %
(pr, target), verbose=verbose)
rc, output2 = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to get users in PR %d" % (pr))
exit(1)
jdata = json.loads(output)
users = []
for review in jdata['reviews']:
if review['author']['login'] != owner and '@'+review['author']['login'] not in users:
users.append('@'+review['author']['login'])
jdata = json.loads(output2)
for comment in jdata['comments']:
if comment['author']['login'] != owner and '@'+comment['author']['login'] not in users:
users.append('@'+comment['author']['login'])
return users
def gh_add_comment(url, pr, target, owner):
global dry_run
global verbose
users = ', '.join(gh_get_all_pr_users(pr, target, owner))
comment = users + "\n" \
"This is an automatically generated comment.\n" \
"The link below:\n" \
"%s\n" \
"Shows the updates in the new revision of this PR\n" \
% (url)
cmd = Command('gh pr comment %d -R %s -b "%s"'%
(pr, target, comment), fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to add comment to github PR %d" % (pr))
exit(1)
def generate_git_diff(repo, pr):
remote = repo.remote().name
local = repo.active_branch.name
date = datetime.now()
filename = "%d-%d-%d-%d-%d-%d-%d.%d.patch" % \
(date.year, date.month, date.day, date.hour,
date.minute, date.second, date.microsecond, pr)
filename = os.path.join("/", "tmp", filename)
cmd = Command("git diff %s/%s..%s" %
(remote, local, local), verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to generate a diff between %s and %s " % (remote, local))
exit(1)
if len(output) == 0:
prformat(fg.red, "No changes detected")
exit(0)
with open(filename, 'w') as f:
f.write(output)
f.write('\n')
return filename
def git_initialize_repo(fq_repo_name, repo_name):
cwd = os.getcwd()
tmpdir = os.path.join(os.path.sep, 'tmp')
if verbose:
prformat(fg.bold+fg.green, "changing dir to: %s" % (tmpdir))
if not dry_run:
os.chdir(tmpdir)
# check if this already exists from previous runs
if (os.path.isdir(os.path.join(tmpdir, repo_name))):
shutil.rmtree(repo_name)
cmd = Command("gh repo clone %s" % (fq_repo_name), fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to clone newly created repo")
exit(1)
path = os.path.join(tmpdir, repo_name)
if verbose:
prformat(fg.bold+fg.green, "changing dir to: %s" % (path))
if not dry_run:
os.chdir(path)
cmd = Command("git init", fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to initialize repo")
exit(1)
with open("README.md", 'w') as f:
f.write("This is an automatically created repo to track code changes\n")
cmd = Command("git add README.md", fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "failed to add README.md")
exit(1)
cmd = Command('git commit -m "first commit"', fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "failed to commit README.md")
exit(1)
cmd = Command("git branch -M main", fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "failed to create main branch")
exit(1)
try:
cmd = Command("git remote add origin https://github.com/%s.git" % (fq_repo_name),
fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
except:
pass
cmd = Command("git push -u origin main", fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to push origin upstream")
exit(1)
if not dry_run:
shutil.rmtree(os.path.join(tmpdir, repo_name))
if verbose:
prformat(fg.bold+fg.green, "removing " + repo_name)
os.chdir(cwd)
if verbose:
prformat(fg.bold+fg.green, "changing dir to: %s" % (cwd))
def gh_create_diff_repo():
# gh auth status
cmd = Command("gh auth status", verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed gh auth status")
exit(1)
l = output.split('\n')
username = None
for e in l:
if "Logged in to github.com as " in e:
a = [elem for elem in re.split(r'Logged in to github.com as | ', e) if len(elem) > 0]
username = a[1]
if not username:
prformat(fg.red, "couldn't find user name")
exit(1)
# gh repo list
cmd = Command("gh repo list", verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed gh repo list")
exit(1)
l = output.split('\n')
# check if gh_diff_<username> exists
repo_name = "gh_diff_"+username
fq_repo_name = username+'/'+"gh_diff_"+username
for e in l:
if fq_repo_name in e:
return fq_repo_name, repo_name, username
# gh repo create gh_diff_<username> --public -d "Repo for code difference"
cmd = Command('gh repo create %s --public -d "Repo for github code differecence"' % (repo_name),
fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to create %s", fq_repo_name)
exit(1)
git_initialize_repo(fq_repo_name, repo_name)
return fq_repo_name, repo_name, username
def gh_push_change(fname, un, fq_repo_name, repo_name, pr, keep):
repo_dir = os.path.join(os.path.sep, 'tmp', repo_name)
if (os.path.isdir(repo_dir)):
shutil.rmtree(repo_dir)
# clone the repository in /tmp
cmd = Command("gh repo clone %s %s" % (fq_repo_name, repo_dir),
fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to clone diff repo")
exit(1)
# cp the file in the repo
repo_dir = os.path.join(os.path.sep, 'tmp', repo_name)
pr_dir = os.path.join(repo_dir, "%d" % (pr))
if not dry_run:
pathlib.Path(pr_dir).mkdir(parents=True, exist_ok=True)
shutil.move(fname, os.path.join(pr_dir, os.path.basename(fname)))
elif verbose:
prformat(fg.green+fg.bold, "mkdir %s" % pr_dir)
prformat(fg.green+fg.bold, "mv %s %s" % (fname, pr_dir))
# git add and force push up
if not dry_run:
repo = git.Repo(os.path.join(repo_dir, ".git"))
repo.git.add(all = True)
repo.index.commit("Changes for PR-%d" % (pr))
origin = repo.remote(name = "origin")
origin.push()
if not keep:
shutil.rmtree(repo_dir)
url = "https://github.com/%s/blob/main/%d/%s" % (fq_repo_name, pr, os.path.basename(fname))
if verbose:
prformat(fg.green+fg.bold, "Path to patch: %s" % (url))
return url
def git_force_push(remote, branch):
global dry_run
global verbose
cmd = Command("git push -f -u %s %s" % (remote, branch), fake=dry_run, verbose=verbose)
rc, output = cmd.exec_cmd()
if rc:
prformat(fg.red, "Failed to commit changes")
exit(1)
def print_help(parser):
prformat(fg.red, "Always execute script from the top of a git repository")
parser.print_help()
if __name__ == '__main__':
argv = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pr", help = "Pull Request Number", type=int)
parser.add_argument("-R", "--repo", help = "Target Github repository")
parser.add_argument("-d", "--dry-run", help = "Do a dry run", action="store_true")
parser.add_argument("-v", "--verbose", help = "Verbose mode", action="store_true")
parser.add_argument("-k", "--keep", help = "Keep Patch", action="store_true")
parser.add_argument("-f", "--force", help = "Force Push Change", action="store_true")
#parser.add_argument("-k", "--keep", help = "Keep Patch", nargs='?', const=0, type=int)
if len(argv) == 0:
print_help(parser)
exit()
args = parser.parse_known_args()
repo = git.Repo('.git')
dry_run = args[0].dry_run
verbose = args[0].verbose
if args[0].pr == None:
exit(0)
if args[0].repo == None:
exit(0)
# generate difference between local branch and origin
diff_file = generate_git_diff(repo, args[0].pr)
fq_repo_name, repo_name, username = gh_create_diff_repo()
change_url = gh_push_change(diff_file, username, fq_repo_name, repo_name, args[0].pr, args[0].keep)
if args[0].force:
git_force_push(repo.remote().name, repo.active_branch.name)
gh_add_comment(change_url, args[0].pr, args[0].repo, username)