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",
54 action="store_true", default=False)
55 PARSER.add_argument("--list-mrs-only", action="store_true", default=False)
61 help="Configuration file to use. Can be used multiple times.",
68 "Which configuration section should "
69 "be used. If not defined, the default selection "
77 help="GStreamer module to move MRs for. All if none specified. Can be used multiple times.",
87 "Id of the MR to work on."
88 " One (and only one) module must be specified with `--module`."
105 'gst-editing-services',
115 'gst-rtsp-server': 1362,
116 'gstreamer-vaapi': 1359,
117 'gstreamer-sharp': 1358,
119 'gst-plugins-ugly': 1354,
120 'gst-plugins-good': 1353,
121 'gst-plugins-base': 1352,
122 'gst-plugins-bad': 1351,
125 'gst-integration-testsuites': 1348,
126 'gst-examples': 1347,
127 'gst-editing-services': 1346,
129 'gst-devtools': 1344,
134 # We do not want to deal with LFS
135 os.environ["GIT_LFS_SKIP_SMUDGE"] = "1"
138 log_depth = [] # type: T.List[str]
144 log_depth.append(name)
152 return f"\033[1m{text}\033[0m"
155 def green(text: str):
156 return f"\033[1;32m{text}\033[0m"
160 return f"\033[1;31m{text}\033[0m"
163 def yellow(text: str):
164 return f"\033[1;33m{text}\033[0m"
167 def fprint(msg, nested=True):
169 prepend = log_depth[-1] + ' | ' if nested else ''
173 print(prepend + msg, end="")
182 self.config_files = []
185 self.all_projects = []
186 self.skipped_branches = []
187 self.git_rename_limit = None
188 self.skip_on_failure = None
192 fprint("Logging into gitlab...")
195 gl = gitlab.Gitlab.from_config(self.gitlab, self.config_files)
196 fprint(f"{green(' OK')}\n", nested=False)
199 gitlab_api_token = os.environ.get('GITLAB_API_TOKEN')
201 gl = gitlab.Gitlab(URL, private_token=gitlab_api_token)
202 fprint(f"{green(' OK')}\n", nested=False)
205 session = requests.Session()
206 sign_in_page = session.get(SIGN_IN_URL).content.decode()
207 for line in sign_in_page.split('\n'):
208 m = re.search('name="authenticity_token" value="([^"]+)"', line)
217 fprint(f"{red('Unable to find the authenticity token')}\n")
221 ({'user[login]': 'login_or_email',
222 'user[password]': 'SECRET',
223 'authenticity_token': token}, LOGIN_URL),
224 ({'username': 'login_or_email',
225 'password': 'SECRET',
226 'authenticity_token': token}, LOGIN_URL_LDAP)]:
228 r = session.post(url, data=data)
229 if r.status_code != 200:
233 gl = gitlab.Gitlab(URL, api_version=4, session=session)
235 except gitlab.exceptions.GitlabAuthenticationError as e:
239 sys.exit(bold(f"{red('FAILED')}.\n\nPlease go to:\n\n"
240 ' https://gitlab.freedesktop.org/-/profile/personal_access_tokens\n\n'
241 f'and generate a token {bold("with read/write access to all but the registry")},'
242 ' then set it in the "GITLAB_API_TOKEN" environment variable:"'
243 f'\n\n $ GITLAB_API_TOKEN=<your token> {" ".join(sys.argv)}\n'))
245 def git(self, *args, can_fail=False, interaction_message=None, call=False, revert_operation=None):
253 return subprocess.check_output(["git"] + list(args), cwd=cwd,
254 stdin=subprocess.DEVNULL,
255 stderr=subprocess.STDOUT).decode()
256 except subprocess.CalledProcessError:
259 f"\n\n{bold(red('ERROR'))}: `git {' '.join(args)}` failed" + "\n", nested=False)
262 subprocess.call(["git"] + list(args), cwd=cwd)
264 except Exception as e:
265 if interaction_message:
266 if self.skip_on_failure:
268 output = getattr(e, "output", b"")
269 if output is not None:
270 out = output.decode()
275 f"Entering a shell in {cwd} to fix:\n\n"
276 f" {bold(interaction_message)}\n\n"
277 f"You should then exit with the following codes:\n\n"
278 f" - {bold('`exit 0`')}: once you have fixed the problem and we can keep moving the merge request\n"
279 f" - {bold('`exit 1`')}: {bold('retry')}: once you have let the repo in a state where the operation should be to retried\n"
280 f" - {bold('`exit 2`')}: to skip that merge request\n"
281 f" - {bold('`exit 3`')}: stop the script and abandon moving your MRs\n"
282 "\n```\n", nested=False)
285 shell = os.environ.get(
286 "COMSPEC", r"C:\WINDOWS\system32\cmd.exe")
288 shell = os.environ.get(
289 "SHELL", os.path.realpath("/bin/sh"))
290 subprocess.check_call(shell, cwd=cwd)
291 except subprocess.CalledProcessError as e:
292 if e.returncode == 1:
295 elif e.returncode == 2:
297 self.git(*revert_operation, can_fail=True)
299 elif e.returncode == 3:
301 self.git(*revert_operation, can_fail=True)
304 # Result of subshell does not really matter
307 return "User fixed it"
310 return "Failed but we do not care"
314 def cleanup_args(self):
317 sys.exit(f"{red(f'Merge request #{self.mr} specified without module')}\n\n"
318 f"{bold(' -> Use `--module` to specify which module the MR is from.')}")
320 self.modules = GST_PROJECTS
322 VALID_PROJECTS = GST_PROJECTS[1:]
323 for m in self.modules:
324 if m not in VALID_PROJECTS:
325 projects = '\n- '.join(VALID_PROJECTS)
327 f"{red(f'Unknown module {m}')}\nModules are:\n- {projects}")
328 if self.mr and len(self.modules) > 1:
329 sys.exit(f"{red(f'Merge request #{self.mr} specified but several modules where specified')}\n\n"
330 f"{bold(' -> Use `--module` only once to specify an merge request.')}")
331 self.modules.append(GST_PROJECTS[0])
335 self.gl = self.connect()
338 # Skip pre-commit hooks when migrating. Some users may have a
339 # different version of gnu indent and that can lead to cherry-pick
341 os.environ["GST_DISABLE_PRE_COMMIT_HOOKS"] = "1"
344 prevbranch = self.git(
345 "rev-parse", "--abbrev-ref", "HEAD", can_fail=True).strip()
347 fprint(bold(yellow("Not on a branch?\n")), indent=False)
353 from_projects, to_project = self.fetch_projects()
356 self.move_mrs(from_projects, to_project)
358 if self.git_rename_limit is not None:
359 self.git("config", "merge.renameLimit",
360 str(self.git_rename_limit))
362 fprint(f'Back to {prevbranch}\n')
363 self.git("checkout", prevbranch)
365 def fetch_projects(self):
366 fprint("Fetching projects... ")
367 self.all_projects = [proj for proj in self.gl.projects.list(
368 membership=1, all=True) if proj.name in self.modules]
371 self.user_project, = [p for p in self.all_projects
372 if p.namespace['path'] == self.gl.user.username
373 and p.name == MONOREPO_NAME]
376 f"{red(f'ERROR')}\n\nCould not find repository {self.gl.user.name}/{MONOREPO_NAME}")
377 fprint(f"{red(f'Got to https://gitlab.freedesktop.org/gstreamer/gstreamer/ and create a fork so we can move your Merge requests.')}")
379 fprint(f"{green(' OK')}\n", nested=False)
382 user_projects_name = [proj.name for proj in self.all_projects if proj.namespace['path']
383 == self.gl.user.username and proj.name in GST_PROJECTS]
384 for project, id in GST_PROJECTS_ID.items():
385 if project not in user_projects_name or project == 'gstreamer':
388 projects = [p for p in self.all_projects if p.id == id]
390 upstream_project = self.gl.projects.get(id)
392 upstream_project, = projects
395 from_projects.append(upstream_project)
397 fprint(f"\nMoving MRs from:\n")
398 fprint(f"----------------\n")
399 for p in from_projects:
400 fprint(f" - {bold(p.path_with_namespace)}\n")
402 to_project = self.gl.projects.get(GST_PROJECTS_ID['gstreamer'])
403 fprint(f"To: {bold(to_project.path_with_namespace)}\n\n")
405 return from_projects, to_project
407 def recreate_mr(self, project, to_project, mr):
408 branch = f"{project.name}-{mr.source_branch}"
409 if not self.create_branch_for_mr(branch, project, mr):
412 description = f"**Copied from {URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}**\n\n{mr.description}"
415 if ':' not in mr.title:
416 title = f"{project.name}: {mr.title}"
419 'source_branch': branch,
420 'allow_collaboration': True,
421 'remove_source_branch': True,
422 'target_project_id': to_project.id,
423 'target_branch': MONOREPO_BRANCH,
426 'description': description,
430 fprint(f"-> Recreating MR '{bold(mr.title)}'...")
432 fprint(f"\nDry info:\n{new_mr_dict}\n")
434 new_mr = self.user_project.mergerequests.create(new_mr_dict)
435 fprint(f"{green(' OK')}\n", nested=False)
436 except gitlab.exceptions.GitlabCreateError as e:
437 fprint(f"{yellow('SKIPPED')} (An MR already exists)\n", nested=False)
440 fprint(f"-> Adding discussings from MR '{mr.title}'...")
442 fprint(f"{green(' OK')}\n", nested=False)
445 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
446 for issue in mr.closes_issues():
447 obj = {'body': f'Fixing MR moved to: {new_mr_url}'}
448 issue.discussions.create(obj)
450 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
451 for discussion in mr.discussions.list():
452 # FIXME notes = [n for n in discussion.attributes['notes'] if n['type'] is not None]
453 notes = [n for n in discussion.attributes['notes']]
457 new_discussion = None
459 note = discussion.notes.get(note['id'])
461 note_url = f"{mr_url}#note_{note.id}"
462 when = dateparse.parse(
463 note.created_at).strftime('on %d, %b %Y')
464 body = f"**{note.author['name']} - {PING_SIGN}{note.author['username']} wrote [here]({note_url})** {when}:\n\n"
465 body += '\n'.join([line for line in note.body.split('\n')])
470 'resolvable': note.resolvable,
474 new_discussion.notes.create(obj)
476 new_discussion = new_mr.discussions.create(obj)
478 if not note.resolvable or note.resolved:
479 new_discussion.resolved = True
480 new_discussion.save()
482 fprint(f"{green(' OK')}\n", nested=False)
484 print(f"New MR available at: {bold(new_mr_url)}\n")
488 def push_branch(self, branch):
490 f"-> Pushing branch {branch} to remote {self.gl.user.username}...")
491 if self.git("push", "--no-verify", self.gl.user.username, branch,
492 interaction_message=f"pushing {branch} to {self.gl.user.username} with:\n "
493 f" `$git push {self.gl.user.username} {branch}`") == "SKIP":
494 fprint(yellow("'SKIPPED' (couldn't push)"), nested=False)
498 fprint(f"{green(' OK')}\n", nested=False)
502 def create_branch_for_mr(self, branch, project, mr):
503 remote_name = project.name + '-' + self.gl.user.username
504 remote_branch = f"{MONOREPO_REMOTE_NAME}/{MONOREPO_BRANCH}"
505 if self.use_branch_if_exists:
507 self.git("checkout", branch)
508 self.git("show", remote_branch + "..", call=True)
510 fprint("Dry run... not creating MR")
512 cont = input('\n Create MR [y/n]? ')
513 if cont.strip().lower() != 'y':
516 return self.push_branch(branch)
517 except subprocess.CalledProcessError as e:
520 self.git("remote", "add", remote_name,
521 f"{URL}{self.gl.user.username}/{project.name}.git", can_fail=True)
522 self.git("fetch", remote_name)
524 if self.git("checkout", remote_branch, "-b", branch,
525 interaction_message=f"checking out branch with `git checkout {remote_branch} -b {branch}`") == "SKIP":
527 bold(f"{red('SKIPPED')} (couldn't checkout)\n"), nested=False)
530 for commit in reversed([c for c in mr.commits()]):
531 if self.git("cherry-pick", commit.id,
532 interaction_message=f"cherry-picking {commit.id} onto {branch} with:\n "
533 f" `$ git cherry-pick {commit.id}`",
534 revert_operation=["cherry-pick", "--abort"]) == "SKIP":
536 f"{yellow('SKIPPED')} (couldn't cherry-pick).", nested=False)
539 self.git("show", remote_branch + "..", call=True)
541 fprint("Dry run... not creating MR\n")
543 cont = input('\n Create MR [y/n]? ')
544 if cont.strip().lower() != 'y':
545 fprint(f"{red('Cancelled')}\n", nested=False)
548 return self.push_branch(branch)
550 def move_mrs(self, from_projects, to_project):
553 for from_project in from_projects:
554 with nested(f'{bold(from_project.path_with_namespace)}'):
555 fprint(f'Fetching mrs')
556 mrs = [mr for mr in from_project.mergerequests.list(
557 all=True, author_id=self.gl.user.id) if mr.author['username'] == self.gl.user.username and mr.state == "opened"]
559 fprint(f"{yellow(' None')}\n", nested=False)
562 fprint(f"{green(' DONE')}\n", nested=False)
566 if self.mr != mr.iid:
570 f'Moving {mr.source_branch} "{mr.title}": {URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}... ')
571 if mr.source_branch in self.skipped_branches:
572 print(f"{yellow('SKIPPED')} (blacklisted branch)")
574 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
576 if self.list_mrs_only:
577 fprint("\n"f"List only: {yellow('SKIPPED')}\n")
580 with nested(f'{bold(from_project.path_with_namespace)}: {mr.iid}'):
581 new_mr = self.recreate_mr(from_project, to_project, mr)
585 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
587 fprint(f"{green(' OK')}\n", nested=False)
589 self.close_mr(from_project, to_project, mr, new_mr)
592 f"\n{yellow('DONE')} with {from_project.path_with_namespace}\n\n", nested=False)
594 if self.mr and not found_mr:
596 bold(red(f"\n==> Couldn't find MR {self.mr} in {self.modules[0]}\n")))
598 for mr in failed_mrs:
599 fprint(f"Didn't move MR: {mr}\n")
601 def close_mr(self, project, to_project, mr, new_mr):
603 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
606 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
607 cont = input(f'\n Close old MR {mr_url} "{bold(mr.title)}" ? [y/n]')
608 if cont.strip().lower() != 'y':
609 fprint(f"{yellow('Not closing old MR')}\n")
613 obj = {'body': f"Moved to: {new_mr_url}"}
616 f"Write a comment to add while closing MR {mr.iid} '{bold(mr.title)}':\n\n").strip()
621 fprint(f"{bold('Dry run, not closing')}\n", nested=False)
624 mr.discussions.create(obj)
625 mr.state_event = 'close'
628 f'Old MR {mr_url} "{bold(mr.title)}" {yellow("CLOSED")}\n')
630 def setup_repo(self):
631 fprint(f"Setting up '{bold(ROOT_DIR)}'...")
634 out = self.git("status", "--porcelain")
636 fprint("\n" + red('Git repository is not clean:')
637 + "\n```\n" + out + "\n```\n")
640 except Exception as e:
642 f"Git repository{ROOT_DIR} is not clean. Clean it up before running {sys.argv[0]}\n ({e})")
644 self.git('remote', 'add', MONOREPO_REMOTE_NAME,
645 MONOREPO_REMOTE, can_fail=True)
646 self.git('fetch', MONOREPO_REMOTE_NAME)
648 self.git('remote', 'add', self.gl.user.username,
649 f"git@gitlab.freedesktop.org:{self.gl.user.username}/gstreamer.git", can_fail=True)
650 self.git('fetch', self.gl.user.username,
651 interaction_message=f"Setup your fork of {URL}gstreamer/gstreamer as remote called {self.gl.user.username}")
652 fprint(f"{green(' OK')}\n", nested=False)
655 git_rename_limit = int(self.git("config", "merge.renameLimit"))
656 except subprocess.CalledProcessError:
658 if int(git_rename_limit) < 999999:
659 self.git_rename_limit = git_rename_limit
661 "-> Setting git rename limit to 999999 so we can properly cherry-pick between repos\n")
662 self.git("config", "merge.renameLimit", "999999")
667 PARSER.parse_args(namespace=mover)
671 if __name__ == '__main__':