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):
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 elif e.returncode == 3:
272 # Result of subshell does not really matter
275 return "User fixed it"
278 return "Failed but we do not care"
282 def cleanup_args(self):
285 sys.exit(f"{red(f'Merge request #{self.mr} specified without module')}\n\n"
286 f"{bold(' -> Use `--module` to specify which module the MR is from.')}")
288 self.modules = GST_PROJECTS
290 VALID_PROJECTS = GST_PROJECTS[1:]
291 for m in self.modules:
292 if m not in VALID_PROJECTS:
293 projects = '\n- '.join(VALID_PROJECTS)
294 sys.exit(f"{red(f'Unknown module {m}')}\nModules are:\n- {projects}")
295 if self.mr and len(self.modules) > 1:
296 sys.exit(f"{red(f'Merge request #{self.mr} specified but several modules where specified')}\n\n"
297 f"{bold(' -> Use `--module` only once to specify an merge request.')}")
298 self.modules.append(GST_PROJECTS[0])
302 self.gl = self.connect()
306 prevbranch = self.git("rev-parse", "--abbrev-ref", "HEAD", can_fail=True).strip()
308 fprint(bold(yellow("Not on a branch?\n")), indent=False)
314 from_projects, to_project = self.fetch_projects()
317 self.move_mrs(from_projects, to_project)
319 if self.git_rename_limit is not None:
320 self.git("config", "merge.renameLimit", str(self.git_rename_limit))
322 fprint(f'Back to {prevbranch}\n')
323 self.git("checkout", prevbranch)
325 def fetch_projects(self):
326 fprint("Fetching projects... ")
327 self.all_projects = [proj for proj in self.gl.projects.list(
328 membership=1, all=True) if proj.name in self.modules]
329 self.user_project, = [p for p in self.all_projects
330 if p.namespace['path'] == self.gl.user.username
331 and p.name == MONOREPO_NAME]
332 fprint(f"{green(' OK')}\n", nested=False)
334 from_projects = [proj for proj in self.all_projects if proj.namespace['path']
335 == NAMESPACE and proj.name != "gstreamer"]
336 fprint(f"\nMoving MRs from:\n")
337 fprint(f"----------------\n")
338 for p in from_projects:
339 fprint(f" - {bold(p.path_with_namespace)}\n")
341 to_project, = [p for p in self.all_projects if p.path_with_namespace ==
342 MOVING_NAMESPACE + "/gstreamer"]
344 fprint(f"To: {bold(to_project.path_with_namespace)}\n\n")
346 return from_projects, to_project
348 def recreate_mr(self, project, to_project, mr):
349 branch = f"{project.name}-{mr.source_branch}"
350 if not self.create_branch_for_mr(branch, project, mr):
353 description = f"**Copied from {URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}**\n\n{mr.description}"
356 if ':' not in mr.title:
357 title = f"{project.name}: {mr.title}"
360 'source_branch': branch,
361 'allow_collaboration': True,
362 'remove_source_branch': True,
363 'target_project_id': to_project.id,
364 'target_branch': MONOREPO_BRANCH,
367 'description': description,
371 fprint(f"-> Recreating MR '{bold(mr.title)}'...")
373 fprint(f"\nDry info:\n{new_mr_dict}\n")
375 new_mr = self.user_project.mergerequests.create(new_mr_dict)
376 fprint(f"{green(' OK')}\n", nested=False)
377 except gitlab.exceptions.GitlabCreateError as e:
378 fprint(f"{yellow('SKIPPED')} (An MR already exists)\n", nested=False)
381 fprint(f"-> Adding discussings from MR '{mr.title}'...")
383 fprint(f"{green(' OK')}\n", nested=False)
386 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
387 for issue in mr.closes_issues():
388 obj = {'body': f'Fixing MR moved to: {new_mr_url}'}
389 issue.discussions.create(obj)
391 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
392 for discussion in mr.discussions.list():
393 # FIXME notes = [n for n in discussion.attributes['notes'] if n['type'] is not None]
394 notes = [n for n in discussion.attributes['notes']]
398 new_discussion = None
400 note = discussion.notes.get(note['id'])
402 note_url = f"{mr_url}#note_{note.id}"
403 when = dateparse.parse(note.created_at).strftime('on %d, %b %Y')
404 body = f"**{note.author['name']} - {PING_SIGN}{note.author['username']} wrote [here]({note_url})** {when}:\n\n"
405 body += '\n'.join([l for l in note.body.split('\n')])
410 'resolvable': note.resolvable,
414 new_discussion.notes.create(obj)
416 new_discussion = new_mr.discussions.create(obj)
418 if not note.resolvable or note.resolved:
419 new_discussion.resolved = True
420 new_discussion.save()
422 fprint(f"{green(' OK')}\n", nested=False)
424 print(f"New MR available at: {bold(new_mr_url)}\n")
428 def push_branch(self, branch):
429 fprint(f"-> Pushing branch {branch} to remote {self.gl.user.username}...")
430 if self.git("push", "--no-verify", self.gl.user.username, branch,
431 interaction_message=f"pushing {branch} to {self.gl.user.username} with:\n "
432 f" `$git push {self.gl.user.username} {branch}`") == "SKIP":
433 fprint(yellow("'SKIPPED' (couldn't push)"), nested=False)
437 fprint(f"{green(' OK')}\n", nested=False)
441 def create_branch_for_mr(self, branch, project, mr):
442 remote_name = project.name + '-' + self.gl.user.username
443 remote_branch = f"{MONOREPO_REMOTE_NAME}/{MONOREPO_BRANCH}"
444 if self.use_branch_if_exists:
446 self.git("checkout", branch)
447 self.git("show", remote_branch + "..", call=True)
449 fprint("Dry run... not creating MR")
451 cont = input('\n Create MR [y/n]? ')
452 if cont.strip().lower() != 'y':
455 return self.push_branch(branch)
456 except subprocess.CalledProcessError as e:
459 self.git("remote", "add", remote_name,
460 f"{URL}{self.gl.user.username}/{project.name}.git", can_fail=True)
461 self.git("fetch", remote_name)
463 if self.git("checkout", remote_branch, "-b", branch,
464 interaction_message=f"checking out branch with `git checkout {remote_branch} -b {branch}`") == "SKIP":
465 fprint(bold(f"{red('SKIPPED')} (couldn't checkout)\n"), nested=False)
468 for commit in reversed([c for c in mr.commits()]):
469 if self.git("cherry-pick", commit.id,
470 interaction_message=f"cherry-picking {commit.id} onto {branch} with:\n "
471 f" `$ git cherry-pick {commit.id}`") == "SKIP":
472 fprint(f"{yellow('SKIPPED')} (couldn't cherry-pick).", nested=False)
473 self.git("cherry-pick", "--abort", can_fail=True)
476 self.git("show", remote_branch + "..", call=True)
478 fprint("Dry run... not creating MR\n")
480 cont = input('\n Create MR [y/n]? ')
481 if cont.strip().lower() != 'y':
482 fprint(f"{red('Cancelled')}\n", nested=False)
485 return self.push_branch(branch)
487 def move_mrs(self, from_projects, to_project):
490 for from_project in from_projects:
491 with nested(f'{bold(from_project.path_with_namespace)}'):
492 fprint(f'Fetching mrs')
493 mrs = [mr for mr in from_project.mergerequests.list(
494 all=True, author_id=self.gl.user.id) if mr.author['username'] == self.gl.user.username and mr.state == "opened"]
496 fprint(f"{yellow(' None')}\n", nested=False)
499 fprint(f"{green(' DONE')}\n", nested=False)
503 if self.mr != mr.iid:
506 fprint(f'Moving {mr.source_branch} "{mr.title}": {URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}... ')
507 if mr.source_branch in self.skipped_branches:
508 print(f"{yellow('SKIPPED')} (blacklisted branch)")
510 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
513 with nested(f'{bold(from_project.path_with_namespace)}: {mr.iid}'):
514 new_mr = self.recreate_mr(from_project, to_project, mr)
518 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
520 fprint(f"{green(' OK')}\n", nested=False)
522 self.close_mr(from_project, to_project, mr, new_mr)
524 fprint(f"\n{yellow('DONE')} with {from_project.path_with_namespace}\n\n", nested=False)
526 if self.mr and not found_mr:
527 sys.exit(bold(red(f"\n==> Couldn't find MR {self.mr} in {self.modules[0]}\n")))
529 for mr in failed_mrs:
530 fprint(f"Didn't move MR: {mr}\n")
532 def close_mr(self, project, to_project, mr, new_mr):
534 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
537 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
538 cont = input(f'\n Close old MR {mr_url} "{bold(mr.title)}" ? [y/n]')
539 if cont.strip().lower() != 'y':
540 fprint(f"{yellow('Not closing old MR')}\n")
544 obj = {'body': f"Moved to: {new_mr_url}"}
546 ret = input(f"Write a comment to add while closing MR {mr.iid} '{bold(mr.title)}':\n\n").strip()
551 fprint(f"{bold('Dry run, not closing')}\n", nested=False)
554 mr.discussions.create(obj)
555 mr.state_event = 'close'
557 fprint(f'Old MR {mr_url} "{bold(mr.title)}" {yellow("CLOSED")}\n')
559 def setup_repo(self):
560 fprint(f"Setting up '{bold(ROOT_DIR)}'...")
563 out = self.git("status", "--porcelain")
565 fprint("\n" + red('Git repository is not clean:') + "\n```\n" + out + "\n```\n")
568 except Exception as e:
570 f"Git repository{ROOT_DIR} is not clean. Clean it up before running {sys.argv[0]}\n ({e})")
572 self.git('remote', 'add', MONOREPO_REMOTE_NAME,
573 MONOREPO_REMOTE, can_fail=True)
574 self.git('fetch', MONOREPO_REMOTE_NAME)
576 self.git('remote', 'add', self.gl.user.username,
577 f"git@gitlab.freedesktop.org:{self.gl.user.username}/gstreamer.git", can_fail=True)
578 self.git('fetch', self.gl.user.username,
579 interaction_message=f"Setup your fork of {URL}gstreamer/gstreamer as remote called {self.gl.user.username}")
580 fprint(f"{green(' OK')}\n", nested=False)
583 git_rename_limit = int(self.git("config", "merge.renameLimit"))
584 except subprocess.CalledProcessError:
586 if int(git_rename_limit) < 999999:
587 self.git_rename_limit = git_rename_limit
588 fprint("-> Setting git rename limit to 999999 so we can properly cherry-pick between repos\n")
589 self.git("config", "merge.renameLimit", "999999")
594 PARSER.parse_args(namespace=mover)
598 if __name__ == '__main__':