3 from urllib.parse import urlparse
4 from contextlib import contextmanager
10 except ModuleNotFoundError:
11 print("========================================================================", file=sys.stderr)
12 print("ERROR: Install python-gitlab with `python3 -m pip install python-gitlab dateutil`", file=sys.stderr)
13 print("========================================================================", file=sys.stderr)
17 from dateutil import parser as dateparse
18 except ModuleNotFoundError:
19 print("========================================================================", file=sys.stderr)
20 print("ERROR: Install dateutil with `python3 -m pip install dateutil`", file=sys.stderr)
21 print("========================================================================", file=sys.stderr)
28 ROOT_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
30 URL = "https://gitlab.freedesktop.org/"
31 SIGN_IN_URL = URL + 'sign_in'
32 LOGIN_URL = URL + 'users/sign_in'
33 LOGIN_URL_LDAP = URL + '/users/auth/ldapmain/callback'
35 MONOREPO_REMOTE_NAME = 'origin'
36 NAMESPACE = "gstreamer"
37 MONOREPO_NAME = 'gstreamer'
38 MONOREPO_REMOTE = URL + f'{NAMESPACE}/{MONOREPO_NAME}'
39 MONOREPO_BRANCH = 'main'
41 MOVING_NAMESPACE = NAMESPACE
43 PARSER = argparse.ArgumentParser(
44 description="Move merge request from old GStreamer module to the new"
45 "GStreamer 'monorepo'.\n"
46 " All your pending merge requests from all GStreamer modules will"
47 " be moved the the mono repository."
49 PARSER.add_argument("--skip-branch", action="store", nargs="*",
50 help="Ignore MRs for branches which match those names.", dest="skipped_branches")
51 PARSER.add_argument("--skip-on-failure", action="store_true", default=False)
52 PARSER.add_argument("--dry-run", "-n", action="store_true", default=False)
53 PARSER.add_argument("--use-branch-if-exists", action="store_true", default=False)
67 'gst-editing-services',
69 'gst-integration-testsuites',
76 # We do not want to deal with LFS
77 os.environ["GIT_LFS_SKIP_SMUDGE"] = "1"
80 log_depth = [] # type: T.List[str]
85 log_depth.append(name)
92 return f"\033[1m{text}\033[0m"
95 return f"\033[1;32m{text}\033[0m"
98 return f"\033[1;31m{text}\033[0m"
100 def yellow(text: str):
101 return f"\033[1;33m{text}\033[0m"
103 def fprint(msg, nested=True):
105 prepend = log_depth[-1] + ' | ' if nested else ''
109 print(prepend + msg, end="")
116 self.gl = self.connect()
118 self.all_projects = []
119 self.skipped_branches = []
120 self.git_rename_limit = None
121 self.skip_on_failure = None
125 fprint("Logging into gitlab...")
126 gitlab_api_token = os.environ.get('GITLAB_API_TOKEN')
129 gl = gitlab.Gitlab(URL, private_token=gitlab_api_token)
130 fprint(f"{green(' OK')}\n", nested=False)
133 session = requests.Session()
134 sign_in_page = session.get(SIGN_IN_URL).content.decode()
135 for l in sign_in_page.split('\n'):
136 m = re.search('name="authenticity_token" value="([^"]+)"', l)
145 fprint(f"{red('Unable to find the authenticity token')}\n")
150 ({'user[login]': 'login_or_email',
151 'user[password]': 'SECRET',
152 'authenticity_token': token}, LOGIN_URL),
153 ({'username': 'login_or_email',
154 'password': 'SECRET',
155 'authenticity_token': token}, LOGIN_URL_LDAP)]:
157 r = session.post(url, data=data)
158 if r.status_code != 200:
162 gl = gitlab.Gitlab(URL, api_version=4, session=session)
164 except gitlab.exceptions.GitlabAuthenticationError as e:
168 sys.exit(bold(f"{red('FAILED')}.\n\nPlease go to:\n\n"
169 ' https://gitlab.freedesktop.org/-/profile/personal_access_tokens\n\n'
170 f'and generate a token {bold("with read/write access to all but the registry")},'
171 ' then set it in the "GITLAB_API_TOKEN" environment variable:"'
172 f'\n\n $ GITLAB_API_TOKEN=<your token> {" ".join(sys.argv)}\n'))
174 def git(self, *args, can_fail=False, interaction_message=None, call=False):
182 return subprocess.check_output(["git"] + list(args), cwd=cwd,
183 stdin=subprocess.DEVNULL,
184 stderr=subprocess.STDOUT).decode()
187 fprint(f"\n\n{bold(red('ERROR'))}: `git {' '.join(args)}` failed" + "\n", nested=False)
190 subprocess.call(["git"] + list(args), cwd=cwd)
192 except Exception as e:
193 if interaction_message:
194 if self.skip_on_failure:
196 output = getattr(e, "output", b"")
197 if output is not None:
198 out = output.decode()
203 f"Entering a shell in {cwd} to fix:\n\n"
204 f" {bold(interaction_message)}\n\n"
205 f"You should then exit with the following codes:\n\n"
206 f" - {bold('`exit 0`')}: once you have fixed the problem and we can keep moving the merge request\n"
207 f" - {bold('`exit 1`')}: {bold('retry')}: once you have let the repo in a state where the operation should be to retried\n"
208 f" - {bold('`exit 2`')}: to skip that merge request\n"
209 f" - {bold('`exit 3`')}: stop the script and abandon moving your MRs\n"
210 "\n```\n", nested=False)
213 shell = os.environ.get(
214 "COMSPEC", r"C:\WINDOWS\system32\cmd.exe")
216 shell = os.environ.get(
217 "SHELL", os.path.realpath("/bin/sh"))
218 subprocess.check_call(shell, cwd=cwd)
219 except subprocess.CalledProcessError as e:
220 if e.returncode == 1:
223 elif e.returncode == 2:
225 elif e.returncode == 3:
228 # Result of subshell does not really matter
231 return "User fixed it"
234 return "Failed but we do not care"
242 from_projects, to_project = self.fetch_projects()
245 self.move_mrs(from_projects, to_project)
247 if self.git_rename_limit is not None:
248 self.git("config", "merge.renameLimit", str(self.git_rename_limit))
250 def fetch_projects(self):
251 fprint("Fetching projects... ")
252 self.all_projects = [proj for proj in self.gl.projects.list(
253 membership=1, all=True) if proj.name in GST_PROJECTS]
254 self.user_project, = [p for p in self.all_projects if p.namespace['path'] == self.gl.user.username and p.name == MONOREPO_NAME]
255 fprint(f"{green(' OK')}\n", nested=False)
257 from_projects = [proj for proj in self.all_projects if proj.namespace['path']
258 == NAMESPACE and proj.name != "gstreamer"]
259 fprint(f"\nMoving MRs from:\n")
260 fprint(f"----------------\n")
261 for p in from_projects:
262 fprint(f" - {bold(p.path_with_namespace)}\n")
264 to_project, = [p for p in self.all_projects if p.path_with_namespace ==
265 MOVING_NAMESPACE + "/gstreamer"]
267 fprint(f"To: {bold(to_project.path_with_namespace)}\n\n")
269 return from_projects, to_project
271 def recreate_mr(self, project, to_project, mr):
272 branch = f"{project.name}-{mr.source_branch}"
273 if not self.create_branch_for_mr(branch, project, mr):
276 description = f"**Copied from {URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}**\n\n{mr.description}"
279 'source_branch': branch,
280 'allow_collaboration': True,
281 'remove_source_branch': True,
282 'target_project_id': to_project.id,
283 'target_branch': MONOREPO_BRANCH,
286 'description': description,
290 fprint(f"-> Recreating MR '{bold(mr.title)}'...")
292 fprint(f"\nDry info:\n{new_mr_dict}\n")
294 new_mr = self.user_project.mergerequests.create(new_mr_dict)
295 fprint(f"{green(' OK')}\n", nested=False)
296 except gitlab.exceptions.GitlabCreateError as e:
297 fprint(f"{yellow('SKIPPED')} (An MR already exists)\n", nested=False)
300 fprint(f"-> Adding discussings from MR '{mr.title}'...")
302 fprint(f"{green(' OK')}\n", nested=False)
305 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
306 for issue in mr.closes_issues():
307 obj = {'body': f'Fixing MR moved to: {new_mr_url}'}
308 issue.discussions.create(obj)
310 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
311 for discussion in mr.discussions.list():
312 # FIXME notes = [n for n in discussion.attributes['notes'] if n['type'] is not None]
313 notes = [n for n in discussion.attributes['notes']]
317 new_discussion = None
319 note = discussion.notes.get(note['id'])
321 note_url = f"{mr_url}#note_{note.id}"
322 when = dateparse.parse(note.created_at).strftime('on %d, %b %Y')
323 body = f"**{note.author['name']} - {PING_SIGN}{note.author['username']} wrote [here]({note_url})** {when}:\n\n"
324 body += '\n'.join([l for l in note.body.split('\n')])
329 'resolvable': note.resolvable,
333 new_discussion.notes.create(obj)
335 new_discussion = new_mr.discussions.create(obj)
337 if not note.resolvable or note.resolved:
338 new_discussion.resolved = True
339 new_discussion.save()
341 fprint(f"{green(' OK')}\n", nested=False)
343 print(f"New MR available at: {bold(new_mr_url)}\n")
347 def push_branch(self, branch):
348 fprint(f"-> Pushing branch {branch} to remote {self.gl.user.username}...")
349 if self.git("push", "--no-verify", self.gl.user.username, branch,
350 interaction_message=f"pushing {branch} to {self.gl.user.username} with:\n "
351 f" `$git push {self.gl.user.username} {branch}`") == "SKIP":
352 fprint(yellow("'SKIPPED' (couldn't push)"), nested=False)
356 fprint(f"{green(' OK')}\n", nested=False)
360 def create_branch_for_mr(self, branch, project, mr):
361 remote_name = project.name + '-' + self.gl.user.username
362 remote_branch = f"{MONOREPO_REMOTE_NAME}/{MONOREPO_BRANCH}"
363 if self.use_branch_if_exists:
365 self.git("checkout", branch)
366 self.git("show", remote_branch + "..", call=True)
368 fprint("Dry run... not creating MR")
370 cont = input('\n Create MR [y/n]? ')
371 if cont.strip().lower() != 'y':
374 return self.push_branch(branch)
375 except subprocess.CalledProcessError as e:
378 self.git("remote", "add", remote_name,
379 f"{URL}{self.gl.user.username}/{project.name}.git", can_fail=True)
380 self.git("fetch", remote_name)
382 if self.git("checkout", remote_branch, "-b", branch,
383 interaction_message=f"checking out branch with `git checkout {remote_branch} -b {branch}`") == "SKIP":
384 fprint(bold(f"{red('SKIPPED')} (couldn't checkout)\n"), nested=False)
387 for commit in reversed([c for c in mr.commits()]):
388 if self.git("cherry-pick", commit.id,
389 interaction_message=f"cherry-picking {commit.id} onto {branch} with:\n "
390 f" `$ git cherry-pick {commit.id}`") == "SKIP":
391 fprint(f"{yellow('SKIPPED')} (couldn't cherry-pick).", nested=False)
392 self.git("cherry-pick", "--abort", can_fail=True)
395 self.git("show", remote_branch + "..", call=True)
397 fprint("Dry run... not creating MR\n")
399 cont = input('\n Create MR [y/n]? ')
400 if cont.strip().lower() != 'y':
401 fprint(f"{red('Cancelled')}\n", nested=False)
404 return self.push_branch(branch)
406 def move_mrs(self, from_projects, to_project):
408 for from_project in from_projects:
409 with nested(f'{bold(from_project.path_with_namespace)}'):
410 fprint(f'Fetching mrs')
411 mrs = [mr for mr in from_project.mergerequests.list(
412 all=True, author_id=self.gl.user.id) if mr.author['username'] == self.gl.user.username and mr.state == "opened"]
414 fprint(f"{yellow(' None')}\n", nested=False)
417 fprint(f"{green(' DONE')}\n", nested=False)
420 fprint(f'Moving {mr.source_branch} "{mr.title}": {URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}... ')
421 if mr.source_branch in self.skipped_branches:
422 print(f"{yellow('SKIPPED')} (blacklisted branch)")
424 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
427 with nested(f'{bold(from_project.path_with_namespace)}: {mr.iid}'):
428 new_mr = self.recreate_mr(from_project, to_project, mr)
432 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
434 fprint(f"{green(' OK')}\n", nested=False)
436 self.close_mr(from_project, to_project, mr, new_mr)
438 fprint(f"\n{yellow('DONE')} with {from_project.path_with_namespace}\n\n", nested=False)
440 for mr in failed_mrs:
441 print(f"Didn't move MR: {mr}")
443 def close_mr(self, project, to_project, mr, new_mr):
445 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
448 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
449 cont = input(f'\n Close old MR {mr_url} "{bold(mr.title)}" ? [y/n]')
450 if cont.strip().lower() != 'y':
451 fprint(f"{yellow('Not closing old MR')}\n")
455 obj = {'body': f"Moved to: {new_mr_url}"}
457 ret = input(f"Write a comment to add while closing MR {mr.iid} '{bold(mr.title)}':\n\n").strip()
462 fprint(f"{bold('Dry run, not closing')}\n", nested=False)
465 mr.discussions.create(obj)
466 mr.state_event = 'close'
468 fprint(f'Old MR {mr_url} "{bold(mr.title)}" {yellow("CLOSED")}\n')
470 def setup_repo(self):
471 fprint(f"Setting up '{bold(ROOT_DIR)}'...")
474 out = self.git("status", "--porcelain")
476 fprint("\n" + red('Git repository is not clean:') + "\n```\n" + out + "\n```\n")
479 except Exception as e:
481 f"Git repository{ROOT_DIR} is not clean. Clean it up before running {sys.argv[0]}\n ({e})")
483 self.git('remote', 'add', MONOREPO_REMOTE_NAME,
484 MONOREPO_REMOTE, can_fail=True)
485 self.git('fetch', MONOREPO_REMOTE_NAME)
487 self.git('remote', 'add', self.gl.user.username,
488 f"git@gitlab.freedesktop.org:{self.gl.user.username}/gstreamer.git", can_fail=True)
489 self.git('fetch', self.gl.user.username,
490 interaction_message=f"Setup your fork of {URL}gstreamer/gstreamer as remote called {self.gl.user.username}")
491 fprint(f"{green(' OK')}\n", nested=False)
494 git_rename_limit = int(self.git("config", "merge.renameLimit"))
495 except subprocess.CalledProcessError:
497 if int(git_rename_limit) < 999999:
498 self.git_rename_limit = git_rename_limit
499 fprint("-> Setting git rename limit to 999999 so we can properly cherry-pick between repos")
500 self.git("config", "merge.renameLimit", "999999")
505 PARSER.parse_args(namespace=mover)
509 if __name__ == '__main__':