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 if ':' not in mr.title:
280 title = f"{project.name}: {mr.title}"
283 'source_branch': branch,
284 'allow_collaboration': True,
285 'remove_source_branch': True,
286 'target_project_id': to_project.id,
287 'target_branch': MONOREPO_BRANCH,
290 'description': description,
294 fprint(f"-> Recreating MR '{bold(mr.title)}'...")
296 fprint(f"\nDry info:\n{new_mr_dict}\n")
298 new_mr = self.user_project.mergerequests.create(new_mr_dict)
299 fprint(f"{green(' OK')}\n", nested=False)
300 except gitlab.exceptions.GitlabCreateError as e:
301 fprint(f"{yellow('SKIPPED')} (An MR already exists)\n", nested=False)
304 fprint(f"-> Adding discussings from MR '{mr.title}'...")
306 fprint(f"{green(' OK')}\n", nested=False)
309 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
310 for issue in mr.closes_issues():
311 obj = {'body': f'Fixing MR moved to: {new_mr_url}'}
312 issue.discussions.create(obj)
314 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
315 for discussion in mr.discussions.list():
316 # FIXME notes = [n for n in discussion.attributes['notes'] if n['type'] is not None]
317 notes = [n for n in discussion.attributes['notes']]
321 new_discussion = None
323 note = discussion.notes.get(note['id'])
325 note_url = f"{mr_url}#note_{note.id}"
326 when = dateparse.parse(note.created_at).strftime('on %d, %b %Y')
327 body = f"**{note.author['name']} - {PING_SIGN}{note.author['username']} wrote [here]({note_url})** {when}:\n\n"
328 body += '\n'.join([l for l in note.body.split('\n')])
333 'resolvable': note.resolvable,
337 new_discussion.notes.create(obj)
339 new_discussion = new_mr.discussions.create(obj)
341 if not note.resolvable or note.resolved:
342 new_discussion.resolved = True
343 new_discussion.save()
345 fprint(f"{green(' OK')}\n", nested=False)
347 print(f"New MR available at: {bold(new_mr_url)}\n")
351 def push_branch(self, branch):
352 fprint(f"-> Pushing branch {branch} to remote {self.gl.user.username}...")
353 if self.git("push", "--no-verify", self.gl.user.username, branch,
354 interaction_message=f"pushing {branch} to {self.gl.user.username} with:\n "
355 f" `$git push {self.gl.user.username} {branch}`") == "SKIP":
356 fprint(yellow("'SKIPPED' (couldn't push)"), nested=False)
360 fprint(f"{green(' OK')}\n", nested=False)
364 def create_branch_for_mr(self, branch, project, mr):
365 remote_name = project.name + '-' + self.gl.user.username
366 remote_branch = f"{MONOREPO_REMOTE_NAME}/{MONOREPO_BRANCH}"
367 if self.use_branch_if_exists:
369 self.git("checkout", branch)
370 self.git("show", remote_branch + "..", call=True)
372 fprint("Dry run... not creating MR")
374 cont = input('\n Create MR [y/n]? ')
375 if cont.strip().lower() != 'y':
378 return self.push_branch(branch)
379 except subprocess.CalledProcessError as e:
382 self.git("remote", "add", remote_name,
383 f"{URL}{self.gl.user.username}/{project.name}.git", can_fail=True)
384 self.git("fetch", remote_name)
386 if self.git("checkout", remote_branch, "-b", branch,
387 interaction_message=f"checking out branch with `git checkout {remote_branch} -b {branch}`") == "SKIP":
388 fprint(bold(f"{red('SKIPPED')} (couldn't checkout)\n"), nested=False)
391 for commit in reversed([c for c in mr.commits()]):
392 if self.git("cherry-pick", commit.id,
393 interaction_message=f"cherry-picking {commit.id} onto {branch} with:\n "
394 f" `$ git cherry-pick {commit.id}`") == "SKIP":
395 fprint(f"{yellow('SKIPPED')} (couldn't cherry-pick).", nested=False)
396 self.git("cherry-pick", "--abort", can_fail=True)
399 self.git("show", remote_branch + "..", call=True)
401 fprint("Dry run... not creating MR\n")
403 cont = input('\n Create MR [y/n]? ')
404 if cont.strip().lower() != 'y':
405 fprint(f"{red('Cancelled')}\n", nested=False)
408 return self.push_branch(branch)
410 def move_mrs(self, from_projects, to_project):
412 for from_project in from_projects:
413 with nested(f'{bold(from_project.path_with_namespace)}'):
414 fprint(f'Fetching mrs')
415 mrs = [mr for mr in from_project.mergerequests.list(
416 all=True, author_id=self.gl.user.id) if mr.author['username'] == self.gl.user.username and mr.state == "opened"]
418 fprint(f"{yellow(' None')}\n", nested=False)
421 fprint(f"{green(' DONE')}\n", nested=False)
424 fprint(f'Moving {mr.source_branch} "{mr.title}": {URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}... ')
425 if mr.source_branch in self.skipped_branches:
426 print(f"{yellow('SKIPPED')} (blacklisted branch)")
428 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
431 with nested(f'{bold(from_project.path_with_namespace)}: {mr.iid}'):
432 new_mr = self.recreate_mr(from_project, to_project, mr)
436 f"{URL}{from_project.path_with_namespace}/merge_requests/{mr.iid}")
438 fprint(f"{green(' OK')}\n", nested=False)
440 self.close_mr(from_project, to_project, mr, new_mr)
442 fprint(f"\n{yellow('DONE')} with {from_project.path_with_namespace}\n\n", nested=False)
444 for mr in failed_mrs:
445 print(f"Didn't move MR: {mr}")
447 def close_mr(self, project, to_project, mr, new_mr):
449 new_mr_url = f"{URL}/{to_project.path_with_namespace}/-/merge_requests/{new_mr.iid}"
452 mr_url = f"{URL}/{project.path_with_namespace}/-/merge_requests/{mr.iid}"
453 cont = input(f'\n Close old MR {mr_url} "{bold(mr.title)}" ? [y/n]')
454 if cont.strip().lower() != 'y':
455 fprint(f"{yellow('Not closing old MR')}\n")
459 obj = {'body': f"Moved to: {new_mr_url}"}
461 ret = input(f"Write a comment to add while closing MR {mr.iid} '{bold(mr.title)}':\n\n").strip()
466 fprint(f"{bold('Dry run, not closing')}\n", nested=False)
469 mr.discussions.create(obj)
470 mr.state_event = 'close'
472 fprint(f'Old MR {mr_url} "{bold(mr.title)}" {yellow("CLOSED")}\n')
474 def setup_repo(self):
475 fprint(f"Setting up '{bold(ROOT_DIR)}'...")
478 out = self.git("status", "--porcelain")
480 fprint("\n" + red('Git repository is not clean:') + "\n```\n" + out + "\n```\n")
483 except Exception as e:
485 f"Git repository{ROOT_DIR} is not clean. Clean it up before running {sys.argv[0]}\n ({e})")
487 self.git('remote', 'add', MONOREPO_REMOTE_NAME,
488 MONOREPO_REMOTE, can_fail=True)
489 self.git('fetch', MONOREPO_REMOTE_NAME)
491 self.git('remote', 'add', self.gl.user.username,
492 f"git@gitlab.freedesktop.org:{self.gl.user.username}/gstreamer.git", can_fail=True)
493 self.git('fetch', self.gl.user.username,
494 interaction_message=f"Setup your fork of {URL}gstreamer/gstreamer as remote called {self.gl.user.username}")
495 fprint(f"{green(' OK')}\n", nested=False)
498 git_rename_limit = int(self.git("config", "merge.renameLimit"))
499 except subprocess.CalledProcessError:
501 if int(git_rename_limit) < 999999:
502 self.git_rename_limit = git_rename_limit
503 fprint("-> Setting git rename limit to 999999 so we can properly cherry-pick between repos")
504 self.git("config", "merge.renameLimit", "999999")
509 PARSER.parse_args(namespace=mover)
513 if __name__ == '__main__':