-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgitstack.py
executable file
·1872 lines (1578 loc) · 57.4 KB
/
gitstack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import argparse
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import urllib.request
from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import lru_cache, total_ordering
from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Union
log = logging.getLogger(__name__)
__version__ = "dev"
# in github release action, it will set this to the tag name which has a leading v
if __version__.startswith("v"):
__version__ = __version__[1:]
def print_err(*args):
pieces = " ".join([str(a) for a in args])
sys.stderr.write(pieces)
sys.stderr.write("\n")
def run(*args, **kwargs) -> str:
kwargs.setdefault("check", True)
kwargs.setdefault("capture_output", True)
silence = kwargs.pop("silence", False)
log.debug("run %s", args)
try:
stdout = subprocess.run(args, **kwargs).stdout
except subprocess.CalledProcessError as e:
if not silence and kwargs.get("capture_output"):
print_err("Error running: ", " ".join(args))
if e.stdout is not None:
print_err(e.stdout.decode("utf-8"))
if e.stderr is not None:
print_err(e.stderr.decode("utf-8"))
if silence or logging.root.getEffectiveLevel() <= logging.INFO:
raise
else:
sys.exit(e.returncode)
if stdout is None:
return ""
else:
return stdout.decode("utf-8").strip()
def gh(*args, **kwargs) -> str:
if shutil.which("gh") is None:
sys.stderr.write("Missing gh executable\n")
sys.exit(1)
return run("gh", *args, **kwargs)
def has_gh() -> bool:
proc = subprocess.run(
["gh", "auth", "status"],
capture_output=True,
check=False,
)
return proc.returncode == 0
def git_lines(*args, **kwargs) -> List[str]:
ret = run("git", *args, **kwargs)
if ret:
return ret.splitlines()
else:
return []
def exit_if_no_gh():
if not has_gh():
sys.stderr.write("gh cli missing or not authenticated\n")
sys.exit(1)
class Color:
BLUE = "\033[94m"
CYAN = "\033[96m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
@classmethod
def red(cls, text: str) -> str:
return cls.RED + text + cls.ENDC
@classmethod
def green(cls, text: str) -> str:
return cls.GREEN + text + cls.ENDC
@classmethod
def blue(cls, text: str) -> str:
return cls.BLUE + text + cls.ENDC
@classmethod
def yellow(cls, text: str) -> str:
return cls.YELLOW + text + cls.ENDC
@classmethod
def cyan(cls, text: str) -> str:
return cls.CYAN + text + cls.ENDC
@total_ordering
@dataclass
class Commit:
hash: str
timestamp: int
relative_time: str
branches: List[str]
subject: str
labeled: bool = False
def format(self) -> str:
pieces = [
Color.yellow(self.hash),
Color.cyan(self.relative_time),
]
local_branches = [b for b in self.branches if not b.startswith("origin/")]
if local_branches:
branches = ", ".join(
[
Color.red(b) + Color.GREEN if b == "HEAD" else b
for b in local_branches
]
)
pieces.append(Color.yellow("(") + Color.green(branches) + Color.yellow(")"))
pieces.append(self.subject)
return " ".join(pieces)
def __lt__(self, other: Any) -> bool:
if not isinstance(other, Commit):
raise NotImplementedError
return self.timestamp < other.timestamp
def __hash__(self) -> int:
return hash(self.hash)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Commit):
raise NotImplementedError
return self.timestamp == other.timestamp and self.hash == other.hash
class git:
@staticmethod
def switch_branch(branch_name: str) -> None:
run("git", "checkout", branch_name)
@staticmethod
def fetch() -> None:
run("git", "fetch")
@staticmethod
def reset(ref: str, hard: bool = False) -> None:
args = ["git", "reset"]
if hard:
args.append("--hard")
args.append(ref)
run(*args)
@staticmethod
def fast_forward(branch: str) -> None:
run("git", "merge", "--ff-only", branch)
@staticmethod
def commit(message: str) -> None:
run("git", "commit", "--allow-empty", "-m", message)
@staticmethod
def get_current_ref() -> str:
return run("git", "rev-parse", "@")
@staticmethod
def rev_parse(ref: str) -> Optional[str]:
try:
return run("git", "rev-parse", ref, silence=True)
except subprocess.CalledProcessError:
return None
@staticmethod
def list_branches(all: bool = False) -> Dict[str, str]:
"""Mapping of branch name to ref"""
ret = {}
args = ["branch", "--format=%(refname:short) %(objectname)"]
if all:
args.append("-a")
for b in git_lines(*args):
if b.startswith("(HEAD detached at"):
continue
name, ref = b.split()
ret[name] = ref
return ret
@staticmethod
def list_remote_branches() -> List[str]:
return [
b.strip()[7:]
for b in git_lines("branch", "-a", "--format=%(refname:short)")
if b.startswith("origin/")
]
@staticmethod
def log_detail(ref: str) -> Commit:
lines = git_lines("log", "-1", ref, "--format=#%h %at %ar (%D) %B")
return git._parse_log_detail(lines)[0]
@staticmethod
def log_range_detail(start: str, end: str) -> List[Commit]:
lines = git_lines("log", start + ".." + end, "--format=#%h %at %ar (%D) %B")
return git._parse_log_detail(lines)
@staticmethod
def _parse_log_detail(lines: List[str]) -> List[Commit]:
commits = []
commit = None
for line in lines:
match = re.match(r"^#(\w+) (\d+) (\d+ \w+ ago) \((.*)\) (.*)$", line)
if match:
if commit is not None:
commits.append(commit)
rel_time = match[3][:-4]
if match[4]:
branches = match[4].split(", ")
for i, branch in enumerate(branches):
if branch.startswith("HEAD ->"):
branches[i] = branch[8:]
branches.insert(0, "HEAD")
break
else:
branches = []
commit = Commit(match[1], int(match[2]), rel_time, branches, match[5])
elif line.startswith("prev-branch:") and commit is not None:
commit.labeled = True
if commit is not None:
commits.append(commit)
commits.reverse()
return commits
@staticmethod
def current_branch() -> Optional[str]:
branch = run("git", "branch", "--show-current")
if branch:
return branch
else:
return None
@staticmethod
def push(branch: str, force: bool = False) -> None:
git_args = ["push", "-u", "origin", branch]
if force:
git_args.insert(1, "--force-with-lease")
run("git", *git_args, capture_output=False)
@staticmethod
def get_containing_branches(ref: str) -> Dict[str, str]:
"""Returns a mapping of branch name to ref"""
ret = {}
for line in git_lines(
"branch", "--contains", ref, "--format=%(objectname),%(refname:short)"
):
ref, name = line.split(",", 1)
ret[name] = ref
return ret
@staticmethod
def create_branch(branch: str, start: Optional[str] = None) -> None:
if start is None:
start = git.get_main_branch()
run("git", "checkout", "-b", branch, start)
@staticmethod
def delete_branch(branch: str, force: bool = False) -> None:
flag = "-D" if force else "-d"
run("git", "branch", flag, branch)
@staticmethod
def rebase_onto(new_root: str, old_root: str, tip: str) -> None:
run("git", "rebase", "--onto", new_root, old_root, tip)
@staticmethod
def rebase(new_root: str, tip: str) -> None:
run("git", "rebase", new_root, tip)
@staticmethod
def delete_remote_branch(branch: str) -> None:
run("git", "push", "origin", "--delete", branch)
@staticmethod
@lru_cache(maxsize=None)
def get_main_branch() -> str:
proc = subprocess.run(
["git", "symbolic-ref", "refs/remotes/origin/HEAD"],
capture_output=True,
check=False,
)
if proc.returncode == 0:
return proc.stdout.decode("utf-8").split("/")[-1].strip()
return "master"
@staticmethod
def is_main_branch(branch: str) -> bool:
# HACK to also handle master-passing-tests
return branch.startswith(git.get_main_branch())
@staticmethod
def get_origin_main() -> str:
return "origin/" + git.get_main_branch()
@staticmethod
def exit_if_dirty():
output = run("git", "status", "--porcelain")
if output:
sys.stderr.write("Working directory is dirty\n")
sys.exit(1)
@staticmethod
def get_commit_message(ref: str) -> str:
return run("git", "log", "-1", "--format=%B", ref)
@staticmethod
def refs_between(ref1: str, ref2: str) -> List[str]:
"""
Exclusive on ref1, inclusive on ref2
Ordered from oldest to newest
"""
refs = git_lines("log", ref1 + "..." + ref2, "--format=%H")
refs.reverse()
return refs
@staticmethod
def merge_base(branch: str, ref2: Optional[str] = None) -> str:
if ref2 is None:
ref2 = git.get_origin_main()
return run("git", "merge-base", branch, ref2)
@staticmethod
def get_child_branches(ref: str) -> List[str]:
return [
b
for b in git_lines("branch", "--contains", ref, "--format=%(refname:short)")
if b != ref
]
@staticmethod
def label_commit(ref: str, label: "DiffLabel") -> Optional[str]:
message = git.get_commit_message(ref)
lines = [
line
for line in message.splitlines()
if not line.startswith("prev-branch:") and not line.startswith("prev-pr:")
]
# Make sure there's a blank line between the message and the labels
if lines[-1] != "":
lines.append("")
if label.prev_branch is not None:
lines.append("prev-branch: " + label.prev_branch)
if label.prev_pr is not None:
lines.append("prev-pr: " + label.prev_pr.as_str())
new_message = "\n".join(lines)
if message == new_message:
return None
cur_ref = git.current_branch() or git.get_current_ref()
git.switch_branch(ref)
run("git", "commit", "--allow-empty", "--amend", "-m", new_message)
new_ref = git.get_current_ref()
git.switch_branch(cur_ref)
return new_ref
@dataclass
class PullRequestLink:
number: Optional[int]
link: Optional[str]
def __init__(self, number: Optional[int], link: Optional[str]):
# You must specify exactly one of number or link
assert (number is None) != (link is None)
self.number = number
self.link = link
@classmethod
def from_num(cls, pr: Optional[int]) -> Optional["PullRequestLink"]:
if pr is None:
return None
return cls(pr, None)
@classmethod
def from_str(cls, s: str) -> "PullRequestLink":
if s.startswith("#"):
return cls(int(s[1:]), None)
elif s.isdigit():
return cls(int(s), None)
elif re.match(r"^https?://", s):
return cls(None, s)
else:
raise ValueError(
f"Invalid PR link. Expected PR number or link to another repo: {s}"
)
def as_str(self) -> str:
if self.number is not None:
return str(self.number)
else:
assert self.link is not None
return self.link
@dataclass
class DiffLabel:
prev_branch: Optional[str] = None
prev_pr: Optional[PullRequestLink] = None
@property
def is_empty(self) -> bool:
return self.prev_branch is None and self.prev_pr is None
@dataclass
class Branch:
name: str
num_commits: int
@property
def root(self) -> str:
if self.num_commits == 1:
return self.name
else:
return self.name + "~" + str(self.num_commits - 1)
@property
def tip(self) -> str:
return self.name
def __len__(self) -> int:
return self.num_commits
def __iter__(self):
for i in range(self.num_commits):
if i == self.num_commits - 1:
yield self.name
else:
yield self.name + "~" + str(self.num_commits - i - 1)
def __repr__(self) -> str:
return f"Branch({self.name}, {self.num_commits})"
def __hash__(self) -> int:
return hash(self.name)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Branch):
return False
return self.name == other.name
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def parse_markdown_table(body: str) -> Tuple[str, str]:
table = []
rest = []
lines = body.splitlines()
for i, line in enumerate(lines):
if line.startswith("|"):
table.append(line)
else:
rest = lines[i:]
break
return "\n".join(table), "\n".join(rest)
def make_markdown_table(data: List[Dict[str, str]], cols: List[str]) -> str:
max_width = [len(col) for col in cols]
for row in data:
for i, col in enumerate(cols):
max_width[i] = max(max_width[i], len(row[col]))
lines = [
"| "
+ " | ".join([col.center(max_width[i]) for i, col in enumerate(cols)])
+ " |",
"| " + " | ".join([max_width[i] * "-" for i in range(len(cols))]) + " |",
]
for row in data:
lines.append(
"| "
+ " | ".join([row[col].ljust(max_width[i]) for i, col in enumerate(cols)])
+ " |",
)
return "\n".join(lines)
PR_TITLE_RE = re.compile(r"^(\[\d+/\d+\])?\s*(WIP:)?\s*(.*)$")
class PullRequest:
def __init__(
self,
number: int,
title: str,
body: str,
url: str,
is_draft: bool,
repo_name: str,
):
match = PR_TITLE_RE.match(title)
assert match
self.number = number
self.raw_title = title
self.title = match[3]
self.raw_body = body
self.table, self.body = parse_markdown_table(body)
self.url = url
self.repo_name = repo_name
self.is_draft = is_draft
def __hash__(self) -> int:
return self.number
def __eq__(self, other) -> bool:
if not isinstance(other, PullRequest):
return False
return self.number == other.number
@classmethod
def from_ref(cls, num_or_branch: Union[str, int]) -> "PullRequest":
return cls.from_json(
json.loads(
gh(
"pr",
"view",
str(num_or_branch),
"--json",
"title,body,number,url,isDraft,headRepository",
)
)
)
@classmethod
def from_json(cls, data: Dict[str, Any]) -> "PullRequest":
return cls(
data["number"],
data["title"],
data["body"],
data["url"],
data["isDraft"],
data["headRepository"]["name"],
)
def parse_prev_prs_from_table(self) -> List["PullRequest"]:
"""Return all of the PR numbers in the list"""
ret: List["PullRequest"] = []
for line in self.table.splitlines():
# Skip lines until we reach the data rows
if not re.match(r"^\|\s*(\d+)\s*\|", line):
continue
pieces = line.split("|")
if len(pieces) < 3:
continue
pr_str = pieces[2].strip()
# If we have reached the current PR, return what we found so far
if pr_str.startswith(">"):
return ret
elif pr_str.startswith("#"):
ret.append(PullRequest.from_ref(int(pr_str[1:])))
else:
# Parse the URL out of a markdown link
match = re.match(r"^\[[^\]]*\]\((.*)\)$", pr_str)
if match:
ret.append(PullRequest.from_ref(match[1]))
return ret
@staticmethod
def get_title(index: int, total: int, title: str, is_draft: bool) -> str:
wip = "WIP: " if is_draft else ""
if total == 1:
return f"{wip}{title}"
else:
return f"[{index}/{total}] {wip}{title}"
def set_title(self, index: int, total: int, title: str) -> bool:
new_title = self.get_title(index, total, title, self.is_draft)
if new_title != self.raw_title:
gh("pr", "edit", self.url, "-t", new_title)
self.title = title
self.raw_title = new_title
return True
else:
return False
def set_draft(self, is_draft: bool) -> bool:
if is_draft == self.is_draft:
return False
args = ["pr", "ready", self.url]
if is_draft:
args.append("--undo")
gh(*args)
self.is_draft = is_draft
return True
def set_table(self, stack_prs: List["PullRequest"]) -> bool:
rows = []
for i, pr in enumerate(stack_prs):
title = pr.title
if pr.is_draft:
title = "WIP: " + title
row = {"Title": title, "": str(i + 1)}
if pr.url == self.url:
row["PR"] = f">{pr.number}"
elif pr.repo_name == self.repo_name:
row["PR"] = f"#{pr.number}"
else:
row["PR"] = f"[{pr.repo_name}#{pr.number}]({pr.url})"
rows.append(row)
table = make_markdown_table(rows, ["", "PR", "Title"])
if len(stack_prs) == 1:
table = ""
if table != self.table:
new_body = table + "\n" + self.body
gh("pr", "edit", self.url, "-b", new_body)
self.raw_body = new_body
self.table = table
return True
else:
return False
class Diff:
"""
An atomic unit in a stack
These correspond 1-to-1 with branches and with PRs, but they can exist without a
branch (if the branch has already been merged and deleted) or without a PR (if the
PR has not been created yet).
"""
def __init__(
self,
branch: Optional[Branch],
pr: Optional[PullRequest],
label: DiffLabel,
):
assert branch is not None or pr is not None
self.branch = branch
self.pr = pr
self.label = label
def get_label_for_diff(self) -> DiffLabel:
name = None if self.branch is None else self.branch.name
pr = self.pr.number if self.pr is not None else None
return DiffLabel(name, PullRequestLink.from_num(pr))
def add_label(self, label: DiffLabel) -> None:
if self.branch is None:
raise RuntimeError("Cannot add label to a diff without a branch")
children = git.get_child_branches(self.branch.name)
new_ref = git.label_commit(self.branch.root, label)
if new_ref is None:
return
old_tip = self.branch.tip
# Rebase the successive commits on top of the new ref
git.rebase_onto(new_ref, self.branch.root, self.branch.name)
# Rebase all child branches
new_root = self.branch.name
old_root = old_tip
for child in children:
old_branch_tip = git.rev_parse(child)
assert old_branch_tip is not None
git.rebase_onto(new_root, old_root, child)
new_root = child
old_root = old_branch_tip
@staticmethod
def parse_labels(ref: str) -> DiffLabel:
label = DiffLabel()
for line in git.get_commit_message(ref).splitlines()[1:]:
if line.startswith("prev-branch:"):
label.prev_branch = line.split(":")[1].strip()
elif line.startswith("prev-pr:"):
label.prev_pr = PullRequestLink.from_str(line.split(":", 1)[1].strip())
return label
@classmethod
def from_branch(cls, branch: str, tips: Dict[str, str]) -> "Diff":
refs = git.refs_between(git.merge_base(branch), branch)
# Find the most recent commit that has a label
for i, ref in enumerate(reversed(refs)):
label = Diff.parse_labels(ref)
if i > 0 and ref in tips:
# We've encountered another branch, so this must be an unlabeled diff
return cls(
Branch(branch, i),
pr=None,
label=DiffLabel(prev_branch=tips[ref]),
)
elif not label.is_empty:
return cls(Branch(branch, i + 1), pr=None, label=label)
return cls(Branch(branch, len(refs)), pr=None, label=DiffLabel())
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Diff):
return False
if self.branch is not None:
return self.branch == other.branch
else:
return self.pr == other.pr
def __hash__(self) -> int:
if self.branch is not None:
return hash(self.branch.name)
else:
assert self.pr is not None
return self.pr.number
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __repr__(self) -> str:
args = []
if self.branch is not None:
args.append(repr(self.branch))
if self.pr is not None:
args.append(f"#{self.pr}")
return f"Diff({', '.join(args)})"
class Stack:
def __init__(self, diffs: List[Diff]):
self._diffs = diffs
def local_diffs(self, before_branch: Optional[str] = None) -> List[Diff]:
ret = [d for d in self._diffs if d.branch is not None]
if before_branch is not None:
while ret[-1].branch is not None and ret[-1].branch.name != before_branch:
ret.pop()
return ret
def branches(self, before_branch: Optional[str] = None) -> List[Branch]:
return [
d.branch for d in self.local_diffs(before_branch) if d.branch is not None
]
def hydrate_prs(self, pr_map: Dict[str, PullRequest]) -> None:
for diff in self._diffs:
if diff.branch is not None:
pr = pr_map.get(diff.branch.name)
if pr is not None:
diff.pr = pr
# gh pr status doesn't show closed PRs, so we need to fetch them separately
any_new_prs = True
while any_new_prs:
any_new_prs = False
first_diff = self._diffs[0]
if first_diff.label.prev_pr:
diff = Diff(
None,
PullRequest.from_ref(first_diff.label.prev_pr.as_str()),
DiffLabel(),
)
any_new_prs = True
self._diffs.insert(0, diff)
elif first_diff.pr:
prev_prs = first_diff.pr.parse_prev_prs_from_table()
prev_diffs = [Diff(None, pr, DiffLabel()) for pr in prev_prs]
any_new_prs = bool(prev_diffs)
self._diffs = prev_diffs + self._diffs
def create_prs(
self, before_branch: Optional[str] = None, publish: bool = False
) -> List[Diff]:
total = len(self._diffs)
created = []
rel = git.get_main_branch()
repo_root = git.rev_parse("--show-toplevel")
assert repo_root is not None
body_file = os.path.join(repo_root, ".github", "PULL_REQUEST_TEMPLATE.md")
for i, diff in enumerate(self.local_diffs(before_branch)):
assert diff.branch is not None
if not diff.pr:
commit_line = (
git.get_commit_message(diff.branch.name).splitlines()[0].strip()
)
title = PullRequest.get_title(i + 1, total, commit_line, True)
args = [
"pr",
"create",
"--head",
diff.branch.name,
"-B",
rel,
"-t",
title,
]
if not publish:
args.append("-d")
if os.path.exists(body_file):
args.extend(["-F", body_file])
else:
args.extend(["-b", ""])
gh(*args, capture_output=False)
diff.pr = PullRequest.from_ref(diff.branch.name)
created.append(diff)
rel = diff.branch.name
return created
def update_prs(self, publish: bool = False) -> List[Diff]:
total = len(self._diffs)
updated = set()
# First update the titles and draft status
for i, diff in enumerate(self._diffs):
pr = diff.pr
if pr is None:
continue
# publish will only take effect when True. It will not unpublish a PR
if publish and pr.set_draft(False):
updated.add(diff)
if pr.set_title(i + 1, total, pr.title):
updated.add(diff)
# Now we have the authoritative list of PRs and titles, so we can update the
# markdown tables
pull_requests = [diff.pr for diff in self._diffs if diff.pr is not None]
for diff in self._diffs:
pr = diff.pr
if pr is not None and pr.set_table(pull_requests):
updated.add(diff)
return list(updated)
def get_diff_for_ref(self, ref: Optional[str] = None) -> Optional[Diff]:
if ref is None:
ref = "@"
branches = git.get_containing_branches(ref)
for diff in self._diffs:
if diff.branch is not None and diff.branch.name in branches:
return diff
return None
def get_prev_diff(self, diff: Diff) -> Optional[Diff]:
for i, d in enumerate(self._diffs):
if d == diff:
if i > 0:
return self._diffs[i - 1]
return None
def get_next_diff(self, diff: Diff) -> Optional[Diff]:
for i, d in enumerate(self._diffs):
if d == diff:
if i < len(self._diffs) - 1:
return self._diffs[i + 1]
return None
def rebase(self, target: Optional[str] = None):
original_branch = git.current_branch()
branches = self.branches()
if target is not None:
git.rebase(target, branches[0].name)
if not git.is_main_branch(target):
diff = next((d for d in self._diffs if d.branch == branches[0]), None)
assert diff is not None
diff.add_label(DiffLabel(prev_branch=target))
prev_branch = branches[0].name
for branch in branches[1:]:
if branch.name not in git.get_child_branches(prev_branch):
git.rebase_onto(prev_branch, branch.root + "^", branch.name)
prev_branch = branch.name
if original_branch is not None:
git.switch_branch(original_branch)
# delete branches that have been merged
if target is not None and git.is_main_branch(target):
cur = git.current_branch()
git.switch_branch(git.get_main_branch())
for branch in branches:
if git.merge_base(branch.name) == git.rev_parse(branch.name):
git.delete_branch(branch.name, force=True)
else:
break
if cur is not None and git.rev_parse(cur) is not None:
git.switch_branch(cur)
def split_diff_by_commits(self, diff: Diff) -> None:
assert diff in self._diffs
branch = diff.branch
if branch is None:
raise RuntimeError("Could not find branch for current diff")
start_diff_idx = self._diffs.index(diff)
if len(branch) > 1:
match = re.match(r"^(.*)\-(\d+)$", branch.name)
if match:
base_branch_name = match.group(1)
base_i = int(match.group(2))
else:
base_branch_name = branch.name
base_i = 1
refs = git.refs_between(branch.root, branch.name)
# Delete the existing branch name; it will be replaced by the new numbered branches
git.switch_branch(branch.root)
git.delete_branch(branch.name, force=True)
insert_idx = start_diff_idx
# Remove the diff we're splitting before adding its replacements
self._diffs.remove(diff)
# refs doesn't have the root commit, so we need to add it
refs.insert(0, "HEAD")
for i, ref in enumerate(refs):
new_branch_name = base_branch_name + "-" + str(base_i + i)
git.create_branch(new_branch_name, ref)
new_diff = Diff(
Branch(new_branch_name, 1),
pr=None,
label=DiffLabel(),
)
self._diffs.insert(insert_idx, new_diff)
insert_idx += 1
for i in range(len(branch)):
diff = self._diffs[start_diff_idx + i]
prev_diff = self.get_prev_diff(diff)
if prev_diff is None:
continue
prev_branch = prev_diff.branch
if prev_branch is None:
continue
diff.add_label(DiffLabel(prev_branch=prev_branch.name))
def print_simple(self) -> None:
pieces = []
for diff in self._diffs:
pieces.append(str(diff))
print(" -> ".join(pieces))
def print_branches(self) -> None:
cur = git.current_branch()
for branch in reversed(self.branches()):
if branch.name == cur:
print("*", branch.name)
else:
print(" ", branch.name)
def contains_ref(self, ref: Optional[str] = None) -> bool:
return self.get_diff_for_ref(ref) is not None
class Repo:
def __init__(self, stacks: List[Stack]):
self.stacks = stacks
def get_stack_for_ref(self, ref: Optional[str] = None) -> Optional[Stack]:
if ref is None:
ref = git.get_current_ref()
for stack in self.stacks:
if stack.contains_ref(ref):
return stack
return None
def load_prs(self) -> None:
prs = json.loads(
gh(
"pr",
"status",
"--json",
"title,body,number,headRefName,url,isDraft,headRepository",
silence=True,
)
)
pr_map: Dict[str, PullRequest] = {
pr["headRefName"]: PullRequest.from_json(pr) for pr in prs["createdBy"]
}
for stack in self.stacks:
stack.hydrate_prs(pr_map)
@classmethod
def load(cls) -> "Repo":
branches = git.list_branches()