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)
59 help="Configuration file to use. Can be used multiple times.",
66 "Which configuration section should "
67 "be used. If not defined, the default selection "
75 help="GStreamer module to move MRs for. All if none specified. Can be used multiple times.",
85 "Id of the MR to work on."
86 " One (and only one) module must be specified with `--module`."
103 'gst-editing-services',
105 'gst-integration-testsuites',
112 # We do not want to deal with LFS
113 os.environ["GIT_LFS_SKIP_SMUDGE"] = "1"
116 log_depth = [] # type: T.List[str]
121 log_depth.append(name)
128 return f"\033[1m{text}\033[0m"
130 def green(text: str):
131 return f"\033[1;32m{text}\033[0m"
134 return f"\033[1;31m{text}\033[0m"
136 def yellow(text: str):
137 return f"\033[1;33m{text}\033[0m"
139 def fprint(msg, nested=True):
141 prepend = log_depth[-1] + ' | ' if nested else ''
145 print(prepend + msg, end="")
154 self.config_files = []
157 self.all_projects = []
158 self.skipped_branches = []
159 self.git_rename_limit = None
160 self.skip_on_failure = None
164 fprint("Logging into gitlab...")
167 gl = gitlab.Gitlab.from_config(self.gitlab, self.config_files)
168 fprint(f"{green(' OK')}\n", nested=False)
171 gitlab_api_token = os.environ.get('GITLAB_API_TOKEN')
173 gl = gitlab.Gitlab(URL, private_token=gitlab_api_token)
174 fprint(f"{green(' OK')}\n", nested=False)
177 session = requests.Session()
178 sign_in_page = session.get(SIGN_IN_URL).content.decode()
179 for l in sign_in_page.split('\n'):
180 m = re.search('name="authenticity_token" value="([^"]+)"', l)
189 fprint(f"{red('Unable to find the authenticity token')}\n")
194 ({'user[login]': 'login_or_email',
195 'user[password]': 'SECRET',
196 'authenticity_token': token}, LOGIN_URL),
197 ({'username': 'login_or_email',
198 'password': 'SECRET',
199 'authenticity_token': token}, LOGIN_URL_LDAP)]:
201 r = session.post(url, data=data)
202 if r.status_code != 200:
206 gl = gitlab.Gitlab(URL, api_version=4, session=session)
208 except gitlab.exceptions.GitlabAuthenticationError as e:
212 sys.exit(bold(f"{red('FAILED')}.\n\nPlease go to:\n\n"
213 ' https://gitlab.freedesktop.org/-/profile/personal_access_tokens\n\n'
214 f'and generate a token {bold("with read/write access to all but the registry")},'
215 ' then set it in the "GITLAB_API_TOKEN" environment variable:"'
216 f'\n\n $ GITLAB_API_TOKEN=<your token> {" ".join(sys.argv)}\n'))
218 def git(self, *args, can_fail=False, interaction_message=None, call=False, revert_operation=None):
226 return subprocess.check_output(["git"] + list(args), cwd=cwd,
227 stdin=subprocess.DEVNULL,
228 stderr=subprocess.STDOUT).decode()
231 fprint(f"\n\n{bold(red('ERROR'))}: `git {' '.join(args)}` failed" + "\n", nested=False)
234 subprocess.call(["git"] + list(args), cwd=cwd)
236 except Exception as e:
237 if interaction_message:
238 if self.skip_on_failure:
240 output = getattr(e, "output", b"")
241 if output is not None:
242 out = output.decode()
247 f"Entering a shell in {cwd} to fix:\n\n"
248 f" {bold(interaction_message)}\n\n"
249 f"You should then exit with the following codes:\n\n"
250 f" - {bold('`exit 0`')}: once you have fixed the problem and we can keep moving the merge request\n"
251 f" - {bold('`exit 1`')}: {bold('retry')}: once you have let the repo in a state where the operation should be to retried\n"
252 f" - {bold('`exit 2`')}: to skip that merge request\n"
253 f" - {bold('`exit 3`')}: stop the script and abandon moving your MRs\n"
254 "\n```\n", nested=False)
257 shell = os.environ.get(
258 "COMSPEC", r"C:\WINDOWS\system32\cmd.exe")
260 shell = os.environ.get(
261 "SHELL", os.path.realpath("/bin/sh"))
262 subprocess.check_call(shell, cwd=cwd)
263 except subprocess.CalledProcessError as e:
264 if e.returncode == 1:
267 elif e.returncode == 2:
269 self.git(*revert_operation, can_fail=True)
271 elif e.returncode == 3:
273 self.git(*revert_operation, can_fail=True)
276 # Result of subshell does not really matter
279 return "User fixed it"
282 return "Failed but we do not care"
286 def cleanup_args(self):
289 sys.exit(f"{red(f'Merge request #{self.mr} specified without module')}\n\n"
290 f"{bold(' -> Use `--module` to specify which module the MR is from.')}")
292 self.modules = GST_PROJECTS
294 VALID_PROJECTS = GST_PROJECTS[1:]
295 for m in self.modules:
296 if m not in VALID_PROJECTS:
297 projects = '\n- '.join(VALID_PROJECTS)
298 sys.exit(f"{red(f'Unknown module {m}')}\nModules are:\n- {projects}")
299 if self.mr and len(self.modules) > 1:
300 sys.exit(f"{red(f'Merge request #{self.mr} specified but several modules where specified')}\n\n"
301 f"{bold(' -> Use `--module` only once to specify an merge request.')}")
302 self.modules.append(GST_PROJECTS[0])
306 self.gl = self.connect()
310 prevbranch = self.git("rev-parse", "--abbrev-ref", "HEAD", can_fail=True).strip()
312 fprint(bold(yellow("Not on a branch?\n")), indent=False)
318 from_projects, to_project = self.fetch_projects()
321 self.move_mrs(from_projects, to_project)
323 if self.git_rename_limit is not None:
324 self.git("config", "merge.renameLimit", str(self.git_rename_limit))
326 fprint(f'Back to {prevbranch}\n')
327 self.git("checkout", prevbranch)
329 def fetch_projects(self):
330 fprint("Fetching projects... ")
331 self.all_projects = [proj for proj in self.gl.projects.list(
332 membership=1, all=True) if proj.name in self.modules]
335 self.user_project, = [p for p in self.all_projects
336 if p.namespace['path'] == self.gl.user.username
337 and p.name == MONOREPO_NAME]
339 fprint(f"{red(f'ERROR')}\n\nCould not find repository {self.gl.user.name}/{MONOREPO_NAME}")
340 fprint(f"{red(f'Got to https://gitlab.freedesktop.org/gstreamer/gstreamer/ and create a fork so we can move your Merge requests.')}")
342 fprint(f"{green(' OK')}\n", nested=False)
344 from_projects = [proj for proj in self.all_projects if proj.namespace['path']
345 == NAMESPACE and proj.name != "gstreamer"]
346 fprint(f"\nMoving MRs from:\n")
347 fprint(f"----------------\n")
348 for p in from_projects:
349 fprint(f" - {bold(p.path_with_namespace)}\n")
351 to_project, = [p for p in self.all_projects if p.path_with_namespace ==
352 MOVING_NAMESPACE + "/gstreamer"]
354 fprint(f"To: {bold(to_project.path_with_namespace)}\n\n")
356 return from_projects, to_project
358 def recreate_mr(self, project, to_project, mr):
359 branch = f"{project.name}-{mr.source_branch}"
360 if not self.create_branch_for_mr(branch, project, mr):
363 description = f"**Copied from {URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}**\n\n{mr.description}"
366 if ':' not in mr.title:
367 title = f"{project.name}: {mr.title}"
370 'source_branch': branch,
371 'allow_collaboration': True,
372 'remove_source_branch': True,
373 'target_project_id': to_project.id,
374 'target_branch': MONOREPO_BRANCH,
377 'description': description,
381 fprint(f"-> Recreating MR '{bold(mr.title)}'...")
383 fprint(f"\nDry info:\n{new_mr_dict}\n")
385 new_mr = self.user_project.mergerequests.create(new_mr_dict)
386 fprint(f"{green(' OK')}\n", nested=False)
387 except gitlab.exceptions.GitlabCreateError as e:
388 fprint(f"{yellow('SKIPPED')} (An MR already exists)\n", nested=False)
391 fprint(f"-> Adding discussings from MR '{mr.title}'...")
393 fprint(f"{green(' OK')}\n", nested=False)
396 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
397 for issue in mr.closes_issues():
398 obj = {'body': f'Fixing MR moved to: {new_mr_url}'}
399 issue.discussions.create(obj)
401 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
402 for discussion in mr.discussions.list():
403 # FIXME notes = [n for n in discussion.attributes['notes'] if n['type'] is not None]
404 notes = [n for n in discussion.attributes['notes']]
408 new_discussion = None
410 note = discussion.notes.get(note['id'])
412 note_url = f"{mr_url}#note_{note.id}"
413 when = dateparse.parse(note.created_at).strftime('on %d, %b %Y')
414 body = f"**{note.author['name']} - {PING_SIGN}{note.author['username']} wrote [here]({note_url})** {when}:\n\n"
415 body += '\n'.join([l for l in note.body.split('\n')])
420 'resolvable': note.resolvable,
424 new_discussion.notes.create(obj)
426 new_discussion = new_mr.discussions.create(obj)
428 if not note.resolvable or note.resolved:
429 new_discussion.resolved = True
430 new_discussion.save()
432 fprint(f"{green(' OK')}\n", nested=False)
434 print(f"New MR available at: {bold(new_mr_url)}\n")
438 def push_branch(self, branch):
439 fprint(f"-> Pushing branch {branch} to remote {self.gl.user.username}...")
440 if self.git("push", "--no-verify", self.gl.user.username, branch,
441 interaction_message=f"pushing {branch} to {self.gl.user.username} with:\n "
442 f" `$git push {self.gl.user.username} {branch}`") == "SKIP":
443 fprint(yellow("'SKIPPED' (couldn't push)"), nested=False)
447 fprint(f"{green(' OK')}\n", nested=False)
451 def create_branch_for_mr(self, branch, project, mr):
452 remote_name = project.name + '-' + self.gl.user.username
453 remote_branch = f"{MONOREPO_REMOTE_NAME}/{MONOREPO_BRANCH}"
454 if self.use_branch_if_exists:
456 self.git("checkout", branch)
457 self.git("show", remote_branch + "..", call=True)
459 fprint("Dry run... not creating MR")
461 cont = input('\n Create MR [y/n]? ')
462 if cont.strip().lower() != 'y':
465 return self.push_branch(branch)
466 except subprocess.CalledProcessError as e:
469 self.git("remote", "add", remote_name,
470 f"{URL}{self.gl.user.username}/{project.name}.git", can_fail=True)
471 self.git("fetch", remote_name)
473 if self.git("checkout", remote_branch, "-b", branch,
474 interaction_message=f"checking out branch with `git checkout {remote_branch} -b {branch}`") == "SKIP":
475 fprint(bold(f"{red('SKIPPED')} (couldn't checkout)\n"), nested=False)
478 for commit in reversed([c for c in mr.commits()]):
479 if self.git("cherry-pick", commit.id,
480 interaction_message=f"cherry-picking {commit.id} onto {branch} with:\n "
481 f" `$ git cherry-pick {commit.id}`",
482 revert_operation=["cherry-pick", "--abort"]) == "SKIP":
483 fprint(f"{yellow('SKIPPED')} (couldn't cherry-pick).", nested=False)
486 self.git("show", remote_branch + "..", call=True)
488 fprint("Dry run... not creating MR\n")
490 cont = input('\n Create MR [y/n]? ')
491 if cont.strip().lower() != 'y':
492 fprint(f"{red('Cancelled')}\n", nested=False)
495 return self.push_branch(branch)
497 def move_mrs(self, from_projects, to_project):
500 for from_project in from_projects:
501 with nested(f'{bold(from_project.path_with_namespace)}'):
502 fprint(f'Fetching mrs')
503 mrs = [mr for mr in from_project.mergerequests.list(
504 all=True, author_id=self.gl.user.id) if mr.author['username'] == self.gl.user.username and mr.state == "opened"]
506 fprint(f"{yellow(' None')}\n", nested=False)
509 fprint(f"{green(' DONE')}\n", nested=False)
513 if self.mr != mr.iid:
516 fprint(f'Moving {mr.source_branch} "{mr.title}": {URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}... ')
517 if mr.source_branch in self.skipped_branches:
518 print(f"{yellow('SKIPPED')} (blacklisted branch)")
520 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
523 with nested(f'{bold(from_project.path_with_namespace)}: {mr.iid}'):
524 new_mr = self.recreate_mr(from_project, to_project, mr)
528 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
530 fprint(f"{green(' OK')}\n", nested=False)
532 self.close_mr(from_project, to_project, mr, new_mr)
534 fprint(f"\n{yellow('DONE')} with {from_project.path_with_namespace}\n\n", nested=False)
536 if self.mr and not found_mr:
537 sys.exit(bold(red(f"\n==> Couldn't find MR {self.mr} in {self.modules[0]}\n")))
539 for mr in failed_mrs:
540 fprint(f"Didn't move MR: {mr}\n")
542 def close_mr(self, project, to_project, mr, new_mr):
544 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
547 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
548 cont = input(f'\n Close old MR {mr_url} "{bold(mr.title)}" ? [y/n]')
549 if cont.strip().lower() != 'y':
550 fprint(f"{yellow('Not closing old MR')}\n")
554 obj = {'body': f"Moved to: {new_mr_url}"}
556 ret = input(f"Write a comment to add while closing MR {mr.iid} '{bold(mr.title)}':\n\n").strip()
561 fprint(f"{bold('Dry run, not closing')}\n", nested=False)
564 mr.discussions.create(obj)
565 mr.state_event = 'close'
567 fprint(f'Old MR {mr_url} "{bold(mr.title)}" {yellow("CLOSED")}\n')
569 def setup_repo(self):
570 fprint(f"Setting up '{bold(ROOT_DIR)}'...")
573 out = self.git("status", "--porcelain")
575 fprint("\n" + red('Git repository is not clean:') + "\n```\n" + out + "\n```\n")
578 except Exception as e:
580 f"Git repository{ROOT_DIR} is not clean. Clean it up before running {sys.argv[0]}\n ({e})")
582 self.git('remote', 'add', MONOREPO_REMOTE_NAME,
583 MONOREPO_REMOTE, can_fail=True)
584 self.git('fetch', MONOREPO_REMOTE_NAME)
586 self.git('remote', 'add', self.gl.user.username,
587 f"git@gitlab.freedesktop.org:{self.gl.user.username}/gstreamer.git", can_fail=True)
588 self.git('fetch', self.gl.user.username,
589 interaction_message=f"Setup your fork of {URL}gstreamer/gstreamer as remote called {self.gl.user.username}")
590 fprint(f"{green(' OK')}\n", nested=False)
593 git_rename_limit = int(self.git("config", "merge.renameLimit"))
594 except subprocess.CalledProcessError:
596 if int(git_rename_limit) < 999999:
597 self.git_rename_limit = git_rename_limit
598 fprint("-> Setting git rename limit to 999999 so we can properly cherry-pick between repos\n")
599 self.git("config", "merge.renameLimit", "999999")
604 PARSER.parse_args(namespace=mover)
608 if __name__ == '__main__':