-
Notifications
You must be signed in to change notification settings - Fork 0
/
bulkupdate.py
203 lines (190 loc) · 9.78 KB
/
bulkupdate.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
import os
import shutil
import subprocess
import json
import requests
import sys
import time
if len(sys.argv) > 1:
configfilename = sys.argv[1]
else:
configfilename = 'config.json'
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), configfilename)) as json_file:
config = json.load(json_file)
if 'secrets_file' in config:
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), config['secrets_file'])) as secrets_json_file:
secrets_config = json.load(secrets_json_file)
config['review_user'] = secrets_config['review_user'] if 'review_user' not in config else config['review_user']
config['review_token'] = secrets_config['review_token'] if 'review_token' not in config else config['review_token']
def main():
prs = []
first = True
repopath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'repos')
filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files')
os.chdir(repopath)
repo_count = [repo_info['repository'] for repo_info in config['repositories']]
repositories = [{**repo_info, 'count': repo_count.count(repo_info['repository'])} for repo_info in config['repositories']]
for repository_dict in repositories:
if not first and 'sleeptime' in config:
print('Sleeping')
time.sleep(config['sleeptime'] * 60)
else:
first = False
repository = repository_dict['repository']
source_branch = repository_dict['source_branch']
if ('force_branch_suffix' in config and config['force_branch_suffix'] is True) or repository_dict['count'] > 1:
dest_branch = f"{config['dest_branch']}-{source_branch}"
else:
dest_branch = config['dest_branch']
org = repository.split('/')[0]
repo = repository.split('/')[1]
shallowclone = repository_dict['shallowclone'] if 'shallowclone' in repository_dict else False
if not os.path.exists(os.path.join(repopath, org)):
os.makedirs(os.path.join(repopath, org))
if os.path.exists(os.path.join(repopath, org, repo)):
os.chdir(os.path.join(repopath, org, repo))
run(['git', 'reset', '--hard', 'HEAD'])
else:
os.chdir(os.path.join(repopath, org))
if shallowclone == True:
run(['git', 'clone', '--depth', '1', f"https://github.com/{org}/{repo}.git"])
else:
run(['git', 'clone', f"https://github.com/{org}/{repo}.git"])
os.chdir(os.path.join(repopath, org, repo))
if shallowclone == True and config['existingbranch'] == True:
run(['git', 'config', '--add', 'remote.origin.fetch', f"+refs/heads/{dest_branch}:refs/remotes/origin/{dest_branch}"])
if 'repoprune' in config and config['repoprune'] == True:
run(['git', 'fetch', '--prune'])
else:
run(['git', 'fetch'])
run(['git', 'checkout', source_branch])
run(['git', 'pull'])
if config['existingbranch'] == False:
run(['git', 'checkout', '-b', dest_branch])
else:
run(['git', 'checkout', dest_branch])
run(['git', 'pull'])
if config['updatebranch'] == True:
run(['git', 'merge', source_branch, '-S', '-m', f"Merge branch {source_branch} into {dest_branch}"])
for f in config['files']:
if f['versioned'] and 'version' in repository_dict:
local_filepath = os.path.join(filepath, repository_dict['version'], f['filename'])
else:
local_filepath = os.path.join(filepath, f['filename'])
remote_filepath = os.path.join(repopath, org, repo, f['filedir'], f['filename'])
if f['action'] == 'copy':
if not os.path.exists(os.path.join(repopath, org, repo, f['filedir'])):
os.makedirs(os.path.join(repopath, org, repo, f['filedir']))
shutil.copyfile(local_filepath, remote_filepath)
elif f['action'] == 'remove':
run(['rm', '-rf', remote_filepath])
elif f['action'] == 'edit':
try:
shutil.copyfile(remote_filepath, local_filepath)
except:
print('FAILED TO COPY FILE - DOES NOT EXIST')
input(f"Hit Enter when done editing {f['filename']} ")
shutil.copyfile(local_filepath, remote_filepath)
elif f['action'] == 'reset':
run(['git', 'checkout', f"origin/{source_branch}", remote_filepath])
run(['git', 'add', remote_filepath])
if config['existingbranch'] == False:
run(['git', 'commit', '-S', '-m', config['msg'], '--no-verify'])
else:
run(['git', 'commit', '-S', '-m', config['msg'], '--no-verify', '--allow-empty'])
if config['existingbranch'] == False:
run(['git', 'push', '--set-upstream', 'origin', dest_branch])
else:
run(['git', 'push'])
if config['createpr'] == True:
prtitle = config['pr_info']['title'] if 'title' in config['pr_info'] and config['pr_info']['title'] != '' else config['msg']
proptions = ['--title', prtitle, '--body', f"{config['pr_info']['description']}\n\nCreated by henrygriffiths/bulk-update", '-H', dest_branch, '-B', source_branch, '-R', repository]
if config['pr_info']['merge'] == 'draft':
proptions += ['--draft']
prnum = run(['gh', 'pr', 'create'] + proptions, returnoutput = True)
try:
prnum = prnum.split('https://github.com/')[1].split('/pull/')[1].strip()
if config['pr_info']['mergedelay'] in ['none', 'wait']:
merge(org, repo, prnum, config)
else:
prs.append({'org': org, 'repo': repo, 'prnum': prnum})
except:
pass
if config['pr_info']['mergedelay'] == 'wait':
merged = False
while merged == False:
try:
time.sleep(60*1)
pr_state = json.loads(run(['gh', 'pr', 'view', prnum, '--json', 'state'], returnoutput = True))['state']
if pr_state == 'MERGED':
merged = True
print('Merged', merged)
except:
print('Failure')
pass
if shallowclone == True and ('repoprune' in config and config['repoprune'] == True) and config['existingbranch'] == True:
run(['git', 'config', '--unset', 'remote.origin.fetch', f"refs/heads/{dest_branch}:refs/remotes/origin/{dest_branch}"])
run(['git', 'branch', '-d', '-r', f"origin/{dest_branch}"])
os.chdir(repopath)
if config['createpr'] == True and config['pr_info']['mergedelay'] in ['after', 'afterinput']:
if config['pr_info']['mergedelay'] == 'afterinput':
input('Press enter when ready to merge')
for pr in prs:
os.chdir(os.path.join(repopath, pr['org'], pr['repo']))
merge(pr['org'], pr['repo'], pr['prnum'], config)
os.chdir(repopath)
os.chdir(os.path.dirname(os.path.realpath(__file__)))
def merge(org, repo, prnum, config):
try:
if config['pr_info']['merge'] != 'skip':
if 'review_user' in config and 'review_token' in config:
requests.post(f"https://api.github.com/repos/{org}/{repo}/pulls/{prnum}/reviews", data = json.dumps({'event': 'APPROVE'}), headers = {'Accept': 'application/vnd.github.v3+json'}, auth = (config['review_user'], config['review_token']))
prurl = f"https://github.com/{org}/{repo}/pull/{prnum}"
deleteflag = [] if 'cleanup' in config['pr_info'] and config['pr_info']['cleanup'] == False else ['-d']
if config['pr_info']['merge'] == 'merge':
run(['gh', 'pr', 'merge', prurl, '-m'] + deleteflag)
elif config['pr_info']['merge'] == 'automerge':
run(['gh', 'pr', 'merge', prurl, '-m', '--auto'] + deleteflag)
elif config['pr_info']['merge'] == 'rebase':
run(['gh', 'pr', 'merge', prurl, '-r'] + deleteflag)
elif config['pr_info']['merge'] == 'autorebase':
run(['gh', 'pr', 'merge', prurl, '-r', '--auto'] + deleteflag)
elif config['pr_info']['merge'] == 'squash':
run(['gh', 'pr', 'merge', prurl, '-s'] + deleteflag)
elif config['pr_info']['merge'] == 'autosquash':
run(['gh', 'pr', 'merge', prurl, '-s', '--auto'] + deleteflag)
elif config['pr_info']['merge'] == 'skip':
pass
except:
print(f"Failure Merging {prurl}")
def run(args, returnoutput = False):
while True:
try:
for x in range(10):
if x <= 9:
try:
sp = subprocess.run(args, text = True, check = True, capture_output = returnoutput)
if returnoutput:
print(sp.stdout)
return sp.stdout
except:
time.sleep(pow(x * 2, 2))
else:
sp = subprocess.run(args, text = True, check = True, capture_output = returnoutput)
if returnoutput:
print(sp.stdout)
return sp.stdout
except:
while True:
print(f"Running {' '.join(args)} Failed.")
result = input('(R)etry or (C)ontinue? : ')
if result.lower() == 'r':
break
elif result.lower() == 'c':
try:
return sp.stderr
except:
print('FAILED TO RETURN ERROR')
return
if __name__ == '__main__':
main()