mergify-cli 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: mergify-cli
3
+ Version: 0.1.1
4
+ Summary:
5
+ Author: Mehdi Abaakouk
6
+ Author-email: sileht@mergify.com
7
+ Requires-Python: >=3.10
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Requires-Dist: httpx (>=0.20.0)
12
+ Requires-Dist: rich (>=10.11.0)
@@ -0,0 +1,651 @@
1
+ #
2
+ # Copyright © 2021 Mergify SAS
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ # not use this file except in compliance with the License. You may obtain
6
+ # a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ # License for the specific language governing permissions and limitations
14
+ # under the License.
15
+
16
+
17
+ import argparse
18
+ import asyncio
19
+ import importlib.metadata
20
+ import os
21
+ import re
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import typing
26
+ from urllib import parse
27
+
28
+ import httpx
29
+ import rich
30
+ import rich.console
31
+
32
+
33
+ try:
34
+ VERSION = importlib.metadata.version("mrgfy")
35
+ except ImportError:
36
+ # https://pyoxidizer.readthedocs.io/en/stable/oxidized_importer_behavior_and_compliance.html#importlib-metadata-compatibility
37
+ VERSION = "0.1"
38
+
39
+ CHANGEID_RE = re.compile(r"Change-Id: (I[0-9a-z]{40})")
40
+ READY_FOR_REVIEW_TEMPLATE = 'mutation { markPullRequestReadyForReview(input: { pullRequestId: "%s" }) { clientMutationId } }'
41
+ DRAFT_TEMPLATE = 'mutation { convertPullRequestToDraft(input: { pullRequestId: "%s" }) { clientMutationId } }'
42
+ console = rich.console.Console(log_path=False, log_time=False)
43
+
44
+ DEBUG = False
45
+ DRAFT = False
46
+
47
+
48
+ def check_for_graphql_errors(response: httpx.Response) -> None:
49
+ data = response.json()
50
+ if "errors" in data:
51
+ console.print(f"url: {response.request.url}", style="red")
52
+ console.print(f"data: {response.request.content.decode()}", style="red")
53
+ if "errors" in data:
54
+ console.print(
55
+ "\n".join(f"* {e.get('message') or e}" for e in data["errors"]),
56
+ style="red",
57
+ )
58
+ sys.exit(1)
59
+
60
+
61
+ def check_for_status(response: httpx.Response) -> None:
62
+ if response.status_code < 400:
63
+ return
64
+
65
+ if response.status_code < 500:
66
+ data = response.json()
67
+ console.print(f"url: {response.request.url}", style="red")
68
+ console.print(f"data: {response.request.content.decode()}", style="red")
69
+ console.print(
70
+ f"HTTPError {response.status_code}: {data['message']}", style="red"
71
+ )
72
+ if "errors" in data:
73
+ console.print(
74
+ "\n".join(f"* {e.get('message') or e}" for e in data["errors"]),
75
+ style="red",
76
+ )
77
+ sys.exit(1)
78
+
79
+ response.raise_for_status()
80
+
81
+
82
+ async def git(args: str) -> str:
83
+ if DEBUG:
84
+ console.print(f"[purple]DEBUG: running: git {args} [/]")
85
+ proc = await asyncio.create_subprocess_shell(
86
+ f"git {args}",
87
+ stdout=asyncio.subprocess.PIPE,
88
+ stderr=asyncio.subprocess.STDOUT,
89
+ )
90
+ stdout, _ = await proc.communicate()
91
+ if proc.returncode != 0:
92
+ console.log(f"fail to run `git {args}`:", style="red")
93
+ console.log(f"{stdout.decode()}", style="red")
94
+ sys.exit(1)
95
+ return stdout.decode().strip()
96
+
97
+
98
+ def get_slug(url: str) -> tuple[str, str]:
99
+ parsed = parse.urlparse(url)
100
+ if parsed.netloc == "":
101
+ # Probably ssh
102
+ _, _, path = parsed.path.partition(":")
103
+ else:
104
+ path = parsed.path[1:].rstrip("/")
105
+
106
+ user, repo = path.split("/", 1)
107
+ if repo.endswith(".git"):
108
+ repo = repo[:-4]
109
+ return user, repo
110
+
111
+
112
+ async def do_setup() -> None:
113
+ hooks_dir = (await git("rev-parse --git-path hooks")).strip()
114
+ installed_hook_file = os.path.join(hooks_dir, "commit-msg")
115
+
116
+ new_hook_file = str(
117
+ importlib.resources.files(__package__).joinpath("hooks/commit-msg")
118
+ )
119
+
120
+ if os.path.exists(installed_hook_file):
121
+ with open(installed_hook_file) as f:
122
+ data_installed = f.read()
123
+ with open(new_hook_file) as f:
124
+ data_new = f.read()
125
+ if data_installed != data_new:
126
+ console.print(
127
+ f"error: {installed_hook_file} differ from mergify_cli hook",
128
+ style="red",
129
+ )
130
+ sys.exit(1)
131
+
132
+ else:
133
+ console.log("Installation of git commit-msg hook")
134
+ shutil.copy(new_hook_file, installed_hook_file)
135
+ os.chmod(installed_hook_file, 0o755)
136
+
137
+
138
+ class GitRef(typing.TypedDict):
139
+ ref: str
140
+
141
+
142
+ class HeadRef(typing.TypedDict):
143
+ sha: str
144
+
145
+
146
+ class PullRequest(typing.TypedDict):
147
+ html_url: str
148
+ number: str
149
+ title: str
150
+ head: HeadRef
151
+ state: str
152
+ draft: bool
153
+ node_id: str
154
+
155
+
156
+ ChangeId = typing.NewType("ChangeId", str)
157
+ KnownChangeIDs = typing.NewType("KnownChangeIDs", dict[ChangeId, PullRequest | None])
158
+
159
+
160
+ async def get_changeid_and_pull(
161
+ client: httpx.AsyncClient, user: str, stack_prefix: str, ref: GitRef
162
+ ) -> tuple[ChangeId, PullRequest | None]:
163
+ branch = ref["ref"][len("refs/heads/") :]
164
+ changeid = ChangeId(branch[len(stack_prefix) + 1 :])
165
+ r = await client.get("pulls", params={"head": f"{user}:{branch}", "state": "open"})
166
+ check_for_status(r)
167
+ pulls = [
168
+ p for p in typing.cast(list[PullRequest], r.json()) if p["state"] == "open"
169
+ ]
170
+ if len(pulls) > 1:
171
+ raise RuntimeError(f"More than 1 pull found with this head: {branch}")
172
+ if pulls:
173
+ return changeid, pulls[0]
174
+ return changeid, None
175
+
176
+
177
+ Change = typing.NewType("Change", tuple[ChangeId, str, str, str])
178
+
179
+
180
+ async def get_local_changes(
181
+ commits: list[str],
182
+ stack_prefix: str,
183
+ known_changeids: KnownChangeIDs,
184
+ ) -> list[Change]:
185
+ changes = []
186
+ for commit in commits:
187
+ message = await git(f"log -1 --format='%b' {commit}")
188
+ title = await git(f"log -1 --format='%s' {commit}")
189
+ changeids = CHANGEID_RE.findall(message)
190
+ if not changeids:
191
+ console.print(
192
+ f"`Change-Id:` line is missing on commit {commit}",
193
+ style="red",
194
+ )
195
+ sys.exit(1)
196
+ changeid = ChangeId(changeids[-1])
197
+ changes.append(Change((changeid, commit, title, message)))
198
+ pull = known_changeids.get(changeid)
199
+ if pull is None:
200
+ action = "to create"
201
+ url = f"<{stack_prefix}/{changeid}>"
202
+ commit_info = commit[-7:]
203
+ else:
204
+ url = pull["html_url"]
205
+ head_commit = commit[-7:]
206
+ commit_info = head_commit
207
+ if DRAFT is not pull["draft"]:
208
+ if DRAFT:
209
+ action = "ready_for_review -> draft"
210
+ else:
211
+ action = "draft -> ready_for_review"
212
+ elif pull["head"]["sha"][-7:] != head_commit:
213
+ action = "to update"
214
+ commit_info = f"{pull['head']['sha'][-7:]} -> {head_commit}"
215
+ else:
216
+ action = "nothing"
217
+
218
+ console.log(
219
+ f"* [yellow]\\[{action}][/] '[red]{commit_info}[/] - [b]{title}[/] {url} - {changeid}"
220
+ )
221
+
222
+ return changes
223
+
224
+
225
+ async def get_changeids_to_delete(
226
+ changes: list[Change], known_changeids: KnownChangeIDs
227
+ ) -> set[ChangeId]:
228
+ changeids_to_delete = set(known_changeids.keys()) - {
229
+ changeid for changeid, commit, title, message in changes
230
+ }
231
+ for changeid in changeids_to_delete:
232
+ pull = known_changeids.get(changeid)
233
+ if pull:
234
+ console.log(
235
+ f"* [red]\\[to delete][/] '[red]{pull['head']['sha'][-7:]}[/] - [b]{pull['title']}[/] {pull['html_url']} - {changeid}"
236
+ )
237
+ else:
238
+ console.log(
239
+ f"* [red]\\[to delete][/] '[red].......[/] - [b]<missing pull request>[/] - {changeid}"
240
+ )
241
+ return changeids_to_delete
242
+
243
+
244
+ async def create_or_update_comments(
245
+ client: httpx.AsyncClient, pulls: list[PullRequest]
246
+ ) -> None:
247
+ first_line = "This pull request is part of a stack:\n"
248
+ body = first_line
249
+ for pull in pulls:
250
+ body += f"1. {pull['title']} ([#{pull['number']}]({pull['html_url']}))\n"
251
+
252
+ for pull in pulls:
253
+ r = await client.get(f"issues/{pull['number']}/comments")
254
+ check_for_status(r)
255
+ for comment in r.json():
256
+ if comment["body"].startswith(first_line):
257
+ if comment["body"] != body:
258
+ await client.patch(comment["url"], json={"body": body})
259
+ break
260
+ else:
261
+ await client.post(f"issues/{pull['number']}/comments", json={"body": body})
262
+
263
+
264
+ async def create_or_update_stack(
265
+ client: httpx.AsyncClient,
266
+ stacked_base_branch: str,
267
+ stacked_dest_branch: str,
268
+ changeid: ChangeId,
269
+ commit: str,
270
+ title: str,
271
+ message: str,
272
+ known_changeids: KnownChangeIDs,
273
+ ) -> tuple[PullRequest, str]:
274
+ if changeid in known_changeids:
275
+ pull = known_changeids.get(changeid)
276
+ with console.status(
277
+ f"* updating stacked branch `{stacked_dest_branch}` ({commit[-7:]}) - {pull['html_url'] if pull else '<stack branch without associated pull>'})"
278
+ ):
279
+ r = await client.patch(
280
+ f"git/refs/heads/{stacked_dest_branch}",
281
+ json={"sha": commit, "force": True},
282
+ )
283
+ else:
284
+ with console.status(
285
+ f"* creating stacked branch `{stacked_dest_branch}` ({commit[-7:]})"
286
+ ):
287
+ r = await client.post(
288
+ "git/refs",
289
+ json={"ref": f"refs/heads/{stacked_dest_branch}", "sha": commit},
290
+ )
291
+
292
+ check_for_status(r)
293
+
294
+ pull = known_changeids.get(changeid)
295
+ if pull and pull["head"]["sha"] == commit:
296
+ if DRAFT is not pull["draft"]:
297
+ action = await check_and_update_pull_status(client, pull)
298
+ else:
299
+ action = "nothing"
300
+ elif pull:
301
+ action = "updated"
302
+ with console.status(
303
+ f"* updating pull request `{title}` (#{pull['number']}) ({commit[-7:]})"
304
+ ):
305
+ r = await client.patch(
306
+ f"pulls/{pull['number']}",
307
+ json={
308
+ "title": title,
309
+ "body": message,
310
+ "head": stacked_dest_branch,
311
+ "base": stacked_base_branch,
312
+ },
313
+ )
314
+ check_for_status(r)
315
+ pull = typing.cast(PullRequest, r.json())
316
+ if DRAFT is not pull["draft"]:
317
+ action = await check_and_update_pull_status(client, pull)
318
+ else:
319
+ action = "created"
320
+ with console.status(
321
+ f"* creating stacked pull request `{title}` ({commit[-7:]})"
322
+ ):
323
+ r = await client.post(
324
+ "pulls",
325
+ json={
326
+ "title": title,
327
+ "body": message,
328
+ "draft": DRAFT,
329
+ "head": stacked_dest_branch,
330
+ "base": stacked_base_branch,
331
+ },
332
+ )
333
+ check_for_status(r)
334
+ pull = typing.cast(PullRequest, r.json())
335
+ return pull, action
336
+
337
+
338
+ async def check_and_update_pull_status(
339
+ client: httpx.AsyncClient, pull: PullRequest
340
+ ) -> str:
341
+ if DRAFT:
342
+ action = "draft"
343
+ template = DRAFT_TEMPLATE
344
+ else:
345
+ action = "ready_for_review"
346
+ template = READY_FOR_REVIEW_TEMPLATE
347
+
348
+ r = await client.post(
349
+ "https://api.github.com/graphql",
350
+ headers={
351
+ "Accept": "application/vnd.github.v4.idl",
352
+ "User-Agent": f"mergify_cli/{VERSION}",
353
+ "Authorization": client.headers["Authorization"],
354
+ },
355
+ json={"query": template % pull["node_id"]},
356
+ )
357
+ check_for_status(r)
358
+ check_for_graphql_errors(r)
359
+
360
+ return action
361
+
362
+
363
+ async def delete_stack(
364
+ client: httpx.AsyncClient,
365
+ stack_prefix: str,
366
+ changeid: ChangeId,
367
+ known_changeids: KnownChangeIDs,
368
+ ) -> None:
369
+ r = await client.delete(
370
+ f"git/refs/heads/{stack_prefix}/{changeid}",
371
+ )
372
+ check_for_status(r)
373
+ pull = known_changeids[changeid]
374
+ if pull:
375
+ console.log(
376
+ f"* [red]\\[deleted][/] '[red]{pull['head']['sha'][-7:]}[/] - [b]{pull['title']}[/] {pull['html_url']} - {changeid}"
377
+ )
378
+ else:
379
+ console.log(
380
+ f"* [red]\\[deleted][/] '[red].......[/] - [b]<branch {stack_prefix}/{changeid}>[/] - {changeid}"
381
+ )
382
+
383
+
384
+ async def log_httpx_request(request: httpx.Request) -> None:
385
+ console.print(
386
+ f"[purple]DEBUG: request: {request.method} {request.url} - Waiting for response[/]"
387
+ )
388
+
389
+
390
+ async def log_httpx_response(response: httpx.Response) -> None:
391
+ request = response.request
392
+ console.print(
393
+ f"[purple]DEBUG: response: {request.method} {request.url} - Status {response.status_code}[/]"
394
+ )
395
+
396
+
397
+ def get_trunk(trunk: str | None = None) -> tuple[str, str]:
398
+ if not trunk:
399
+ try:
400
+ trunk = (
401
+ subprocess.check_output(
402
+ "git config --get mergify-cli.stack-trunk", shell=True
403
+ )
404
+ .decode()
405
+ .strip()
406
+ )
407
+ except subprocess.CalledProcessError:
408
+ trunk = ""
409
+
410
+ if not trunk:
411
+ console.log("[red] mergify-cli stack-trunk is not defined [/]")
412
+ console.log(
413
+ "[yellow] Setting it using : `git config --add mergify-cli.stack-trunk origin/branch-name` [/]"
414
+ )
415
+ console.log("[yellow] or use param : --trunk origin/branch-names [/]")
416
+ sys.exit(1)
417
+
418
+ result = trunk.split("/", maxsplit=1)
419
+ if len(result) != 2:
420
+ console.log(
421
+ "[red] mergify-cli stack-trunk is not well formated. It must be origin/branch-name [/]"
422
+ )
423
+ console.log(
424
+ "[yellow] Setting it using : `git config --add mergify-cli.stack-trunk origin/branch-name` [/]"
425
+ )
426
+ console.log("[yellow] or use param : --trunk origin/branch-names [/]")
427
+ sys.exit(1)
428
+
429
+ return result[0], result[1]
430
+
431
+
432
+ async def main(
433
+ token: str,
434
+ next_only: bool,
435
+ branch_prefix: str,
436
+ dry_run: bool,
437
+ trunk: str | None = None,
438
+ ) -> None:
439
+ os.chdir((await git("rev-parse --show-toplevel")).strip())
440
+ dest_branch = await git("rev-parse --abbrev-ref HEAD")
441
+
442
+ remote, base_branch = get_trunk(trunk)
443
+
444
+ user, repo = get_slug(await git(f"config --get remote.{remote}.url"))
445
+
446
+ if base_branch == dest_branch:
447
+ console.log("[red] base branch and destination branch are the same [/]")
448
+ sys.exit(1)
449
+
450
+ stack_prefix = f"{branch_prefix}/{dest_branch}"
451
+
452
+ if not dry_run:
453
+ with console.status(
454
+ f"Rebasing branch `{dest_branch}` on `{remote}/{base_branch}`...",
455
+ ):
456
+ await git(f"pull --rebase {remote} {base_branch}")
457
+ console.log(f"branch `{dest_branch}` rebased on `{remote}/{base_branch}`")
458
+
459
+ with console.status(
460
+ f"Pushing branch `{dest_branch}` to `{remote}/{dest_branch}`...",
461
+ ):
462
+ await git(f"push -f {remote} {dest_branch}:{stack_prefix}/aio")
463
+ console.log(f"branch `{dest_branch}` pushed to `{remote}/{dest_branch}` ")
464
+
465
+ base_commit_sha = await git(f"merge-base --fork-point {remote}/{base_branch}")
466
+ if not base_commit_sha:
467
+ console.log(
468
+ f"Common commit between `{remote}/{base_branch}` and `{dest_branch}` branches not found",
469
+ style="red",
470
+ )
471
+ sys.exit(1)
472
+
473
+ commits = [
474
+ commit
475
+ for commit in reversed(
476
+ (await git(f"log --format='%H' {base_commit_sha}..{dest_branch}")).split(
477
+ "\n"
478
+ )
479
+ )
480
+ if commit.strip()
481
+ ]
482
+
483
+ known_changeids = KnownChangeIDs({})
484
+
485
+ if DEBUG:
486
+ event_hooks = {"request": [log_httpx_request], "response": [log_httpx_response]}
487
+ else:
488
+ event_hooks = {}
489
+
490
+ async with httpx.AsyncClient(
491
+ base_url=f"https://api.github.com/repos/{user}/{repo}/",
492
+ headers={
493
+ "Accept": "application/vnd.github.v3+json",
494
+ "User-Agent": f"mergify_cli/{VERSION}",
495
+ "Authorization": f"token {token}",
496
+ },
497
+ event_hooks=event_hooks, # type: ignore[arg-type]
498
+ ) as client:
499
+ with console.status("Retrieving latest pushed stacks"):
500
+ r = await client.get(f"git/matching-refs/heads/{stack_prefix}/")
501
+ check_for_status(r)
502
+ refs = typing.cast(list[GitRef], r.json())
503
+
504
+ tasks = [
505
+ asyncio.create_task(
506
+ get_changeid_and_pull(client, user, stack_prefix, ref)
507
+ )
508
+ for ref in refs
509
+ if not ref["ref"].endswith("/aio")
510
+ ]
511
+ if tasks:
512
+ done, _ = await asyncio.wait(tasks)
513
+ for task in done:
514
+ known_changeids.update(dict([await task]))
515
+
516
+ with console.status("Preparing stacked branches..."):
517
+ console.log("Stacked pull request plan:", style="green")
518
+ changes = await get_local_changes(commits, stack_prefix, known_changeids)
519
+ changeids_to_delete = await get_changeids_to_delete(
520
+ changes, known_changeids
521
+ )
522
+
523
+ if dry_run:
524
+ console.log("[orange]Finished (dry-run mode) :tada:[/]")
525
+ sys.exit(0)
526
+
527
+ console.log("New stacked pull request:", style="green")
528
+ stacked_base_branch = base_branch
529
+ pulls: list[PullRequest] = []
530
+ continue_create_or_update = True
531
+ for changeid, commit, title, message in changes:
532
+ depends_on = ""
533
+ if pulls:
534
+ depends_on = f"\n\nDepends-On: #{pulls[-1]['number']}"
535
+ stacked_dest_branch = f"{stack_prefix}/{changeid}"
536
+ if continue_create_or_update:
537
+ pull, action = await create_or_update_stack(
538
+ client,
539
+ stacked_base_branch,
540
+ stacked_dest_branch,
541
+ changeid,
542
+ commit,
543
+ title,
544
+ message + depends_on,
545
+ known_changeids,
546
+ )
547
+ pulls.append(pull)
548
+ else:
549
+ action = "skipped"
550
+ pull = known_changeids.get(changeid) or PullRequest(
551
+ {
552
+ "title": "<not yet created>",
553
+ "html_url": "<no-yet-created>",
554
+ "number": "-1",
555
+ "node_id": "na",
556
+ "draft": True,
557
+ "state": "",
558
+ "head": {"sha": ""},
559
+ }
560
+ )
561
+
562
+ console.log(
563
+ f"* [blue]\\[{action}][/] '[red]{commit[-7:]}[/] - [b]{pull['title']}[/] {pull['html_url']} - {changeid}"
564
+ )
565
+ stacked_base_branch = stacked_dest_branch
566
+ if continue_create_or_update and next_only:
567
+ continue_create_or_update = False
568
+
569
+ with console.status("Updating comments..."):
570
+ await create_or_update_comments(client, pulls)
571
+ console.log("[green]Comments updated")
572
+
573
+ with console.status("Deleting unused branches..."):
574
+ delete_tasks = [
575
+ asyncio.create_task(
576
+ delete_stack(client, stack_prefix, changeid, known_changeids)
577
+ )
578
+ for changeid in changeids_to_delete
579
+ ]
580
+ if delete_tasks:
581
+ await asyncio.wait(delete_tasks)
582
+
583
+ console.log("[green]Finished :tada:[/]")
584
+
585
+
586
+ def GitHubToken(v: str) -> str:
587
+ if not v:
588
+ raise ValueError
589
+ return v
590
+
591
+
592
+ def get_default_branch_prefix() -> str:
593
+ try:
594
+ result = subprocess.check_output(
595
+ "git config --get mergify-cli.stack-branch-prefix", shell=True
596
+ )
597
+ except subprocess.CalledProcessError:
598
+ result = b""
599
+
600
+ return result.decode().strip() or "mergify_cli"
601
+
602
+
603
+ def get_default_token() -> str:
604
+ token = os.environ.get("GITHUB_TOKEN", "")
605
+ if not token:
606
+ token = subprocess.check_output("gh auth token", shell=True).decode().strip()
607
+ if DEBUG:
608
+ console.print(f"[purple]DEBUG: token: {token}[/]")
609
+ return token
610
+
611
+
612
+ def cli() -> None:
613
+ global DEBUG
614
+ global DRAFT
615
+ parser = argparse.ArgumentParser(description="mrgfy")
616
+ parser.add_argument("--debug", action="store_true")
617
+ parser.add_argument("--setup", action="store_true")
618
+ parser.add_argument("--dry-run", "-n", action="store_true")
619
+ parser.add_argument("--next-only", "-x", action="store_true")
620
+ parser.add_argument("--draft", "-d", action="store_true")
621
+ parser.add_argument("--trunk", "-t")
622
+ parser.add_argument(
623
+ "--branch-prefix",
624
+ default=get_default_branch_prefix(),
625
+ help="branch prefix used to create stacked PR",
626
+ )
627
+ parser.add_argument(
628
+ "--token",
629
+ default=get_default_token(),
630
+ type=GitHubToken,
631
+ help="GitHub personal access token",
632
+ )
633
+ args = parser.parse_args()
634
+ if args.debug:
635
+ DEBUG = True
636
+
637
+ if args.draft:
638
+ DRAFT = True
639
+
640
+ if args.setup:
641
+ asyncio.run(do_setup())
642
+ else:
643
+ asyncio.run(
644
+ main(
645
+ args.token,
646
+ args.next_only,
647
+ args.branch_prefix,
648
+ args.dry_run,
649
+ args.trunk,
650
+ )
651
+ )
@@ -0,0 +1,63 @@
1
+ #!/bin/sh
2
+ # Based on Gerrit Code Review 3.1.3
3
+ #
4
+ # Part of Gerrit Code Review (https://www.gerritcodereview.com/)
5
+ #
6
+ # Copyright (C) 2009 The Android Open Source Project
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ # avoid [[ which is not POSIX sh.
21
+ if test "$#" != 1 ; then
22
+ echo "$0 requires an argument."
23
+ exit 1
24
+ fi
25
+
26
+ if test ! -f "$1" ; then
27
+ echo "file does not exist: $1"
28
+ exit 1
29
+ fi
30
+
31
+ # Do not create a change id if requested
32
+ #if test "false" = "`git config --bool --get gerrit.createChangeId`" ; then
33
+ # exit 0
34
+ #fi
35
+
36
+ # $RANDOM will be undefined if not using bash, so don't use set -u
37
+ random=$( (whoami ; hostname ; date; cat $1 ; echo $RANDOM) | git hash-object --stdin)
38
+ dest="$1.tmp.${random}"
39
+
40
+ trap 'rm -f "${dest}"' EXIT
41
+
42
+ if ! git stripspace --strip-comments < "$1" > "${dest}" ; then
43
+ echo "cannot strip comments from $1"
44
+ exit 1
45
+ fi
46
+
47
+ if test ! -s "${dest}" ; then
48
+ echo "file is empty: $1"
49
+ exit 1
50
+ fi
51
+
52
+ # Avoid the --in-place option which only appeared in Git 2.8
53
+ # Avoid the --if-exists option which only appeared in Git 2.15
54
+ if ! git -c trailer.ifexists=doNothing interpret-trailers \
55
+ --trailer "Change-Id: I${random}" < "$1" > "${dest}" ; then
56
+ echo "cannot insert change-id line in $1"
57
+ exit 1
58
+ fi
59
+
60
+ if ! mv "${dest}" "$1" ; then
61
+ echo "cannot mv ${dest} to $1"
62
+ exit 1
63
+ fi
@@ -0,0 +1,18 @@
1
+ #
2
+ # Copyright © 2021 Mergify SAS
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ # not use this file except in compliance with the License. You may obtain
6
+ # a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ # License for the specific language governing permissions and limitations
14
+ # under the License.
15
+
16
+
17
+ def test_noop() -> None:
18
+ pass
@@ -0,0 +1,81 @@
1
+ [tool.poetry]
2
+ name = "mergify_cli"
3
+ version = "0.1.1"
4
+ description = ""
5
+ authors = ["Mehdi Abaakouk <sileht@mergify.com>"]
6
+
7
+
8
+ [tool.poetry.dependencies]
9
+ python = ">=3.10"
10
+ httpx = ">=0.20.0"
11
+ rich = ">=10.11.0"
12
+
13
+ [tool.poetry.group.dev.dependencies]
14
+ mypy = {version = ">=0.930"}
15
+ mypy-extensions = "^1.0.0"
16
+ black = "^23.7.0"
17
+ ruff = "^0.0.277"
18
+ pytest = {version = ">=6.2.5"}
19
+ poethepoet = "^0.21.0"
20
+
21
+ [tool.poetry.scripts]
22
+ mergify = 'mergify_cli:cli'
23
+
24
+ [tool.poe]
25
+ include = ["poe.toml"]
26
+
27
+ [tool.black]
28
+ target-version = ['py311']
29
+
30
+ [tool.mypy]
31
+ strict = true
32
+ warn_unreachable = true
33
+ exclude = [".venv"]
34
+ files = ["mergify_cli"]
35
+ show_error_codes = true
36
+
37
+ [tool.ruff]
38
+ line-length = 88
39
+ target-version = "py311"
40
+ select = [
41
+ "E", "W", "F", "I", "A", "B", "Q",
42
+ "C4", "T10", "ISC", "ICN", "BLE",
43
+ "G", "RSE", "TID", "TRY", "PLE", "UP",
44
+ "RUF", "RET",
45
+ # FIXME(sileht): very interresting, but require easy manual code change
46
+ # "DTZ", "ARG", "TCH", "COM",
47
+ # FIXME(sileht): doctring/rst-docstring like
48
+ # "D"
49
+ ]
50
+
51
+ ignore = [
52
+ # NOTE(sileht): line-length is up to black
53
+ "E501",
54
+ # NOTE(sileht): we prefer using exc_info=True
55
+ "G201", "TRY200", "TRY400",
56
+ # NOTE(sileht): "Unnecessary parentheses on raised exception", this breaks
57
+ # isinstance on exception
58
+ "RSE102",
59
+ # NOTE(sileht): No exception with message set via __init__
60
+ "TRY003", "TRY301",
61
+ # NOTE(sileht): built-in shadow, interresting but to raise an error for
62
+ # TypedDict/NamedTuple with key named like builtin, so it's useless
63
+ "A003",
64
+ # NOTE(sileht): This enforce usage of raise ... from ...
65
+ "B904",
66
+ # FIXME(sileht): Convert some exception -> TypeError
67
+ "TRY004",
68
+ # FIXME(sileht): very interresting, ruff BLE is far better that flake8-blind-except
69
+ "BLE001",
70
+ # NOTE(sileht): looks buggy
71
+ "RET508"
72
+ ]
73
+
74
+ [tool.ruff.isort]
75
+ force-single-line = true
76
+ force-sort-within-sections = true
77
+ lines-after-imports = 2
78
+ known-first-party = ["mergify_cli"]
79
+
80
+ [tool.ruff.flake8-tidy-imports]
81
+ ban-relative-imports = "all"