Repository navigation
Expand file tree
/
Copy pathtest_native_stack.py
More file actions
1359 lines (1190 loc) · 57.5 KB
/
Copy pathtest_native_stack.py
File metadata and controls
1359 lines (1190 loc) · 57.5 KB
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 python3
from __future__ import annotations
import os
import re
import shutil
import tempfile
from contextlib import contextmanager
from dataclasses import replace
from itertools import pairwise
from pathlib import Path
from typing import Any, TYPE_CHECKING
from unittest import main, mock, TestCase
from github_utils import GHGraphQLError
from gitutils import _check_output, GitRepo
from native_stack import (
_landed_in,
_trunk_landings,
build_native_stack_commits,
build_native_stack_rebase,
find_stack_dependents,
get_native_stack,
get_native_stack_landing_prs,
GH_GET_PR_STACK_QUERY,
NativeStack,
NativeStackError,
PULL_REQUEST_RESOLVED,
push_branches,
stack_dependencies_line,
StackEntry,
)
if TYPE_CHECKING:
from collections.abc import Iterator
ORG = "pytorch"
PROJECT = "pytorch"
TRUNK = "main"
# Keeps the developer's git config (signing, hooks, default branch) out of the
# temporary repositories. HOME and XDG_CONFIG_HOME are pointed at the temporary
# directory too, as git reads the global ignore and attributes files from there even
# with GIT_CONFIG_GLOBAL set.
GIT_ENV = {
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
# Only local paths: a push or fetch of the code under test can never reach GitHub
"GIT_ALLOW_PROTOCOL": "file",
"GIT_AUTHOR_NAME": "PR Author",
"GIT_AUTHOR_EMAIL": "author@example.com",
"GIT_COMMITTER_NAME": "PR Author",
"GIT_COMMITTER_EMAIL": "author@example.com",
}
BOT_NAME = "PyTorch MergeBot"
BOT_EMAIL = "pytorchmergebot@users.noreply.github.com"
TRUNK_REF = f"refs/remotes/origin/{TRUNK}"
# Path -> new content, or None to delete the file
FileChanges = dict[str, str | None]
def pr_url(number: int, host: str = "github.com") -> str:
return f"https://{host}/{ORG}/{PROJECT}/pull/{number}"
def landing_message(url: str, body: str = "Summary") -> str:
return (
f"Change\n\n{body}\n\n{PULL_REQUEST_RESOLVED}{url}\n"
"Approved by: https://github.com/reviewer\n"
)
def revert_message(url: str, sha: str) -> str:
return (
f'Revert "Change"\n\nThis reverts commit {sha}.\n\n'
f"Reverted {url} on behalf of https://github.com/reverter due to broken trunk\n"
)
def manual_revert_message(sha: str, number: int = 700) -> str:
"""The landed message of revert PR `number`, opened by hand from `git revert`: it
reverts commit `sha` without naming the PR it reverts"""
return landing_message(pr_url(number), f"This reverts commit {sha}.")
def author(number: int) -> str:
return f"Author {number} <author{number}@example.com>"
def make_entry(
position: int,
number: int,
head_ref: str,
head_oid: str,
base_ref: str,
closed: bool = False,
) -> StackEntry:
return StackEntry(
position=position,
number=number,
closed=closed,
head_ref=head_ref,
head_oid=head_oid,
base_ref=base_ref,
)
def with_entry(stack: NativeStack, index: int, **changes: Any) -> NativeStack:
entries = list(stack.entries)
entries[index] = replace(entries[index], **changes)
return replace(stack, entries=tuple(entries))
def gql_node(entry: StackEntry) -> dict[str, Any]:
return {
"position": entry.position,
"pullRequest": {
"number": entry.number,
"title": f"PR {entry.number}",
"state": "CLOSED" if entry.closed else "OPEN",
"closed": entry.closed,
"merged": False,
"headRefName": entry.head_ref,
"headRefOid": entry.head_oid,
"baseRefName": entry.base_ref,
"baseRefOid": "0" * 40,
},
}
def gql_stack(
nodes: list[Any], total_count: int | None = None, has_next_page: bool = False
) -> dict[str, Any]:
total = len(nodes) if total_count is None else total_count
stack = {
"size": total,
"baseRefName": TRUNK,
"entries": {
"totalCount": total,
"pageInfo": {"hasNextPage": has_next_page},
"nodes": nodes,
},
}
return {"data": {"repository": {"pullRequest": {"stack": stack}}}}
GQL_ENTRIES = (
make_entry(1, 198532, "user/capture", "1" * 40, TRUNK, closed=True),
make_entry(2, 198534, "user/inductor", "2" * 40, "user/capture"),
make_entry(3, 198536, "user/tests", "3" * 40, "user/inductor"),
)
GQL_NODES = [gql_node(entry) for entry in GQL_ENTRIES]
@mock.patch("native_stack.gh_graphql")
class TestGetNativeStack(TestCase):
def assertRejected(self, gql: Any, response: dict[str, Any]) -> None:
gql.return_value = response
message = r"Could not read all \d+ PRs in the stack of PR #198534"
with self.assertRaisesRegex(NativeStackError, message):
get_native_stack(ORG, PROJECT, 198534)
def test_returns_none_without_stack(self, gql: Any) -> None:
gql.return_value = {"data": {"repository": {"pullRequest": {"stack": None}}}}
self.assertIsNone(get_native_stack(ORG, PROJECT, 199613))
gql.assert_called_once_with(
GH_GET_PR_STACK_QUERY, owner=ORG, name=PROJECT, number=199613
)
def test_parses_stack(self, gql: Any) -> None:
gql.return_value = gql_stack(GQL_NODES)
self.assertEqual(
get_native_stack(ORG, PROJECT, 198534),
NativeStack(base_ref=TRUNK, entries=GQL_ENTRIES),
)
gql.assert_called_once_with(
GH_GET_PR_STACK_QUERY, owner=ORG, name=PROJECT, number=198534
)
def test_sorts_entries_by_position(self, gql: Any) -> None:
gql.return_value = gql_stack([GQL_NODES[i] for i in (2, 0, 1)])
self.assertEqual(
get_native_stack(ORG, PROJECT, 198534),
NativeStack(base_ref=TRUNK, entries=GQL_ENTRIES),
)
def test_rejects_more_than_one_page(self, gql: Any) -> None:
self.assertRejected(gql, gql_stack(GQL_NODES, has_next_page=True))
def test_rejects_total_count_mismatch(self, gql: Any) -> None:
self.assertRejected(gql, gql_stack(GQL_NODES[:2], total_count=3))
def test_rejects_null_node(self, gql: Any) -> None:
self.assertRejected(gql, gql_stack([GQL_NODES[0], None, GQL_NODES[2]]))
def test_rejects_null_pull_request(self, gql: Any) -> None:
node = {"position": 2, "pullRequest": None}
self.assertRejected(gql, gql_stack([GQL_NODES[0], node, GQL_NODES[2]]))
def test_graphql_errors_are_reported_without_the_query(self, gql: Any) -> None:
errors = [{"message": "Field 'stack' doesn't exist"}, {"message": "Timeout"}]
response = {"errors": errors}
gql.side_effect = GHGraphQLError(f"{GH_GET_PR_STACK_QUERY} failed", response)
message = r"^GraphQL errors: Field 'stack' doesn't exist; Timeout$"
with self.assertRaisesRegex(NativeStackError, message):
get_native_stack(ORG, PROJECT, 198534)
def test_query_requests_parsed_fields(self, gql: Any) -> None:
for field in (
"$owner",
"$name",
"$number",
"stack",
"baseRefName",
"totalCount",
"hasNextPage",
"position",
"closed",
"headRefName",
"headRefOid",
):
self.assertIn(field, GH_GET_PR_STACK_QUERY)
class GitTestCase(TestCase):
"""A bare origin, a developer clone that pushes to it and a stale bot clone"""
def setUp(self) -> None:
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
home = {"HOME": tmp.name, "XDG_CONFIG_HOME": tmp.name}
env = mock.patch.dict(os.environ, {**GIT_ENV, **home})
env.start()
self.addCleanup(env.stop)
# GIT_DIR, GIT_INDEX_FILE, ... (exported e.g. inside git hooks) would make the
# commands below write into another repository.
for var in _check_output(["git", "rev-parse", "--local-env-vars"]).split():
os.environ.pop(var, None)
origin = os.path.join(tmp.name, "origin.git")
bot = os.path.join(tmp.name, "bot")
self.dev = os.path.join(tmp.name, "dev")
self.files = 0
self.git("init", "-q", "--bare", "-b", TRUNK, origin, cwd=tmp.name)
self.git("init", "-q", "-b", TRUNK, self.dev, cwd=tmp.name)
self.git("remote", "add", "origin", origin)
self.root = self.commit("Initial commit")
self.git("push", "-q", "origin", TRUNK)
# Cloned before any stack branch exists, so the code under test must fetch.
self.git("clone", "-q", origin, bot, cwd=tmp.name)
self.repo = GitRepo(bot, remote="origin")
def git(self, *args: str, cwd: str | None = None) -> str:
return _check_output(["git", "-C", cwd or self.dev, *args]).strip()
def commit(self, message: str, files: FileChanges | None = None) -> str:
if files is None:
self.files += 1
files = {f"file{self.files}.txt": f"{self.files}\n"}
for name, content in files.items():
if content is None:
Path(self.dev, name).unlink()
else:
Path(self.dev, name).write_text(content)
self.git("add", "-A")
self.git("commit", "-q", "-m", message)
return self.git("rev-parse", "HEAD")
def add_commits(
self, branch: str, count: int = 1, files: FileChanges | None = None
) -> str:
self.git("checkout", "-q", branch)
for _ in range(count):
self.commit(f"Update {branch}", files)
self.git("push", "-q", "origin", branch)
return self.git("rev-parse", "HEAD")
def push_branch(
self, branch: str, base: str, count: int = 1, files: FileChanges | None = None
) -> str:
self.git("branch", branch, base)
return self.add_commits(branch, count, files)
def push_stack(
self,
branches: tuple[str, ...] = ("user/a", "user/b", "user/c"),
trunk: str = TRUNK,
commits: int = 1,
changes: tuple[FileChanges, ...] | None = None,
) -> NativeStack:
entries: list[StackEntry] = []
base = trunk
for position, branch in enumerate(branches, start=1):
files = None if changes is None else changes[position - 1]
head = self.push_branch(branch, base, commits, files)
entries.append(make_entry(position, 100 + position, branch, head, base))
base = branch
return NativeStack(base_ref=trunk, entries=tuple(entries))
def landing_prs(
self, stack: NativeStack, target: int
) -> list[tuple[StackEntry, str]]:
return get_native_stack_landing_prs(
self.repo, ORG, PROJECT, stack, target, TRUNK
)
def merge_into(self, branch: str, other: str) -> str:
self.git("checkout", "-q", branch)
self.git("merge", "-q", "--no-ff", "-m", f"Merge {other}", other)
self.git("push", "-q", "origin", branch)
return self.git("rev-parse", "HEAD")
def rebase(self, branch: str, *args: str) -> str:
self.git("rebase", "-q", *args, branch)
self.git("push", "-q", "-f", "origin", branch)
return self.git("rev-parse", "HEAD")
def land(self, entry: StackEntry, body: str = "Summary") -> str:
self.git("checkout", "-q", TRUNK)
self.git("merge", "-q", "--squash", entry.head_ref)
self.git("commit", "-q", "-m", landing_message(pr_url(entry.number), body))
self.git("push", "-q", "origin", TRUNK)
return self.git("rev-parse", "HEAD")
def revert(self, entry: StackEntry, sha: str) -> str:
self.git("checkout", "-q", TRUNK)
self.git("revert", "--no-commit", sha)
self.git("commit", "-q", "-m", revert_message(pr_url(entry.number), sha))
self.git("push", "-q", "origin", TRUNK)
return self.git("rev-parse", "HEAD")
class TestLandedIn(GitTestCase):
def find(self, url: str) -> str | None:
return _landed_in(GitRepo(self.dev), url, TRUNK, TRUNK)
def test_finds_newest_landing_commit(self) -> None:
landed = self.commit(landing_message(pr_url(1234)))
self.commit(landing_message(pr_url(4321)))
self.assertEqual(self.find(pr_url(1234)), landed)
def test_pr_number_must_match_exactly(self) -> None:
self.commit(landing_message(pr_url(12345)))
self.assertIsNone(self.find(pr_url(1234)))
self.assertIsNone(self.find(pr_url(123456)))
def test_lines_quoted_in_a_body_are_not_landings(self) -> None:
quoted = landing_message(pr_url(1234))
self.commit(landing_message(pr_url(4321), quoted))
self.assertIsNone(self.find(pr_url(1234)))
landed = self.commit(landing_message(pr_url(1234)))
quoting = self.commit(landing_message(pr_url(5678), quoted))
self.assertEqual(self.find(pr_url(1234)), landed)
self.assertEqual(self.find(pr_url(5678)), quoting)
def test_only_lf_ends_a_line(self) -> None:
# Co-authored-by lines, which follow the bot's lines, hold author names
quoted = f"{PULL_REQUEST_RESOLVED}{pr_url(4321)}"
for separator in ("\r", "\u2028"):
with self.subTest(separator=separator):
name = f"Name{separator}{quoted}{separator}Name"
message = landing_message(pr_url(1234))
coauthor = f"Co-authored-by: {name} <co@example.com>"
landed = self.commit(f"{message}\n{coauthor}\n")
self.assertEqual(self.find(pr_url(1234)), landed)
self.assertIsNone(self.find(pr_url(4321)))
def test_landed_then_reverted(self) -> None:
landed = self.commit(landing_message(pr_url(1234)))
self.commit(revert_message(pr_url(1234), landed))
self.assertIsNone(self.find(pr_url(1234)))
def test_landed_then_reverted_by_a_revert_pr_opened_by_hand(self) -> None:
landed = self.commit(landing_message(pr_url(1234)))
self.commit(manual_revert_message(landed))
self.assertIsNone(self.find(pr_url(1234)))
def test_relanded_after_revert(self) -> None:
landed = self.commit(landing_message(pr_url(1234)))
self.commit(revert_message(pr_url(1234), landed))
relanded = self.commit(landing_message(pr_url(1234)))
self.commit("Unrelated change")
self.assertEqual(self.find(pr_url(1234)), relanded)
def test_revert_line_needs_exactly_the_sha_at_the_start_of_a_line(self) -> None:
landed = self.commit(landing_message(pr_url(1234)))
lines = (
f"This reverts commit {landed}0.\n"
f"This reverts commit {landed[:10]}.\n"
f" This reverts commit {landed}.\n"
f"> This reverts commit {landed}.\n"
)
self.commit(f"Revert\n\n{lines}")
self.assertEqual(self.find(pr_url(1234)), landed)
class TestTrunkLandings(GitTestCase):
def push_landing(self, number: int) -> str:
landed = self.commit(landing_message(pr_url(number)))
self.git("push", "-q", "origin", TRUNK)
self.git("fetch", "-q", "origin", cwd=self.repo.repo_dir)
return landed
def read(self, number: int) -> tuple[list[str], list[str]]:
"""The landings of PR `number` on the bot's trunk, and the revisions that
`git log` read to find them"""
with mock.patch.object(self.repo, "_run_git", wraps=self.repo._run_git) as run:
landings = _trunk_landings(self.repo, pr_url(number), TRUNK_REF)
logs = [call.args for call in run.call_args_list if call.args[0] == "log"]
return landings, [args[-2] for args in logs]
def test_reads_the_history_once_then_only_the_commits_added_since(self) -> None:
first = self.push_landing(101)
self.assertEqual(self.read(101), ([first], [first]))
other = self.push_landing(102)
second = self.push_landing(101)
self.assertEqual(self.read(101), ([second, first], [f"{first}..{second}"]))
self.assertEqual(self.read(101), ([second, first], [f"{second}..{second}"]))
self.assertEqual(self.read(102), ([other], [second]))
NOT_LANDED = r"PR #101 is closed but not landed on main, or it was reverted"
REBASE = re.escape(
"Rebase the stack onto main with `@pytorchbot rebase -b main` and try again."
)
class TestGetNativeStackLandingPrs(GitTestCase):
def assertRefused(self, stack: NativeStack, target: int, message: str) -> None:
with self.assertRaisesRegex(NativeStackError, message):
self.landing_prs(stack, target)
def test_lands_open_entries_up_to_target(self) -> None:
stack = self.push_stack()
a, b, c = stack.entries
self.assertEqual(
self.landing_prs(stack, c.number),
[(a, self.root), (b, a.head_oid), (c, b.head_oid)],
)
self.assertEqual(
self.landing_prs(stack, b.number), [(a, self.root), (b, a.head_oid)]
)
self.assertEqual(self.landing_prs(stack, a.number), [(a, self.root)])
def test_landed_entry_below_uses_live_branch_tip(self) -> None:
stack = self.push_stack()
self.land(stack.entries[0])
a_head = self.merge_into("user/a", TRUNK)
b_head = self.merge_into("user/b", "user/a")
c_head = self.merge_into("user/c", "user/b")
stack = with_entry(stack, 0, closed=True)
stack = with_entry(with_entry(stack, 1, head_oid=b_head), 2, head_oid=c_head)
_, b, c = stack.entries
self.assertEqual(self.landing_prs(stack, c.number), [(b, a_head), (c, b_head)])
def test_bottom_entry_merged_trunk_and_upper_entry_merged_it(self) -> None:
stack = self.push_stack(("user/a", "user/b"))
trunk = self.add_commits(TRUNK)
a_head = self.merge_into("user/a", TRUNK)
b_head = self.merge_into("user/b", "user/a")
stack = with_entry(with_entry(stack, 0, head_oid=a_head), 1, head_oid=b_head)
a, b = stack.entries
self.assertEqual(self.landing_prs(stack, b.number), [(a, trunk), (b, a_head)])
def test_refuses_unsupported_stacks_without_running_git(self) -> None:
entries = (
make_entry(1, 101, "user/a", "1" * 40, TRUNK),
make_entry(2, 102, "user/b", "2" * 40, "user/a"),
make_entry(3, 103, "user/c", "3" * 40, "user/b"),
)
stack = NativeStack(base_ref=TRUNK, entries=entries)
other_trunk = replace(stack, base_ref=VIABLE_STRICT)
ghstack = with_entry(stack, 0, head_ref="gh/someone/7/head")
based = r"#103 is in a stack based on viable/strict, but only stacks based on"
bottom = (
r"PR #101 is at the bottom of the stack, so its base must be the stack's "
r"trunk \(main\), not user/other"
)
middle = r"PR #{} targets {} instead of {}, the branch of PR #{} below it"
mixed = (
r"^PR #101 is a ghstack PR, and the bot does not support stacks that mix "
r"ghstack PRs with other PRs; unstack the other PRs$"
)
below_open = r"^PR #102 is closed, but PR #101 below it is still open$"
chains = (
(0, "user/other", bottom),
(1, "user/other", middle.format(102, "user/other", "user/a", 101)),
(1, TRUNK, middle.format(102, TRUNK, "user/a", 101)),
(2, "user/other", middle.format(103, "user/other", "user/b", 102)),
)
refused = [
(with_entry(stack, index, base_ref=base), 103, message)
for index, base, message in chains
]
refused += [
(other_trunk, 103, f"{based} main can be merged$"),
(stack, 999, r"^PR #999 is not in the stack$"),
(with_entry(stack, 2, closed=True), 103, r"^PR #103 is closed$"),
(with_entry(stack, 1, closed=True), 103, below_open),
(ghstack, 101, mixed),
(with_entry(ghstack, 0, closed=True), 103, mixed),
]
opened = r"^PR #101 is opened from viable/strict, so rebasing it would push to"
rebase_refused = (
(other_trunk, 103, TRUNK, f"{based} main can be rebased$"),
(with_entry(stack, 0, head_ref=VIABLE_STRICT), 101, VIABLE_STRICT, opened),
)
with mock.patch.object(self.repo, "_run_git", side_effect=AssertionError):
for refused_stack, target, message in refused:
with self.subTest(target=target, message=message):
self.assertRefused(refused_stack, target, message)
for refused_stack, target, onto, message in rebase_refused:
with self.subTest(target=target, onto=onto, message=message):
with self.assertRaisesRegex(NativeStackError, message):
build_native_stack_rebase(
self.repo, ORG, PROJECT, refused_stack, target, TRUNK, onto
)
def test_refuses_entry_below_target_landed_then_reverted(self) -> None:
stack = self.push_stack()
a, b, c = stack.entries
closed = with_entry(stack, 0, closed=True)
landed = self.land(a)
self.assertEqual(
self.landing_prs(closed, c.number), [(b, a.head_oid), (c, b.head_oid)]
)
self.revert(a, landed)
self.assertRefused(closed, c.number, NOT_LANDED)
def test_refuses_open_entry_that_already_landed(self) -> None:
stack = self.push_stack()
a, b, c = stack.entries
for entry in (a, c):
with self.subTest(landed=entry.number):
landed = self.land(entry)
message = rf"PR #{entry.number} already landed but is still open"
self.assertRefused(stack, c.number, message)
self.revert(entry, landed)
self.assertEqual(
self.landing_prs(stack, c.number),
[(a, self.root), (b, a.head_oid), (c, b.head_oid)],
)
def test_refuses_landed_entry_branch_with_commits_that_never_landed(self) -> None:
stack = self.push_stack(("user/a", "user/b"))
self.land(stack.entries[0])
extra = self.add_commits("user/a")
b_head = self.rebase("user/b", "user/a")
stack = with_entry(with_entry(stack, 0, closed=True), 1, head_oid=b_head)
message = (
"PR #101 is closed, but its branch has commits that never landed on "
f"main: {extra}"
)
self.assertRefused(stack, 102, message)
def test_refuses_deleted_branch_of_landed_entry(self) -> None:
stack = self.push_stack(("user/a", "user/b"))
a, b = stack.entries
self.land(a)
stack = with_entry(stack, 0, closed=True)
self.assertEqual(self.landing_prs(stack, b.number), [(b, a.head_oid)])
self.git("push", "-q", "origin", "--delete", a.head_ref)
message = r"^Could not fetch main and the commits of PRs #101, #102: "
self.assertRefused(stack, b.number, message)
def test_refuses_lower_entry_updated_while_preparing_the_merge(self) -> None:
stack = self.push_stack(("user/a",))
self.push_branch("user/a-next", "user/a")
b_head = self.push_branch("user/b", "user/a-next")
b = make_entry(2, 102, "user/b", b_head, "user/a")
stack = replace(stack, entries=(*stack.entries, b))
self.git("push", "-q", "origin", "user/a-next:user/a")
message = r"PR #101 was updated while preparing the merge"
self.assertRefused(stack, b.number, message)
def test_refuses_lower_entry_updated_after_upper_entry(self) -> None:
stack = self.push_stack()
stack = with_entry(stack, 0, head_oid=self.add_commits("user/a"))
expected = rf"^PR #102 is not based on the tip of user/a\. {REBASE}$"
for target in (102, 103):
with self.subTest(target=target):
self.assertRefused(stack, target, expected)
def test_refuses_upper_entry_that_merged_trunk(self) -> None:
stack = self.push_stack()
a, b, _ = stack.entries
self.add_commits(TRUNK)
self.assertEqual(
self.landing_prs(stack, b.number), [(a, self.root), (b, a.head_oid)]
)
stack = with_entry(stack, 1, head_oid=self.merge_into("user/b", TRUNK))
expected = (
r"^PR #102 contains main commits that user/a does not have\. "
rf"{REBASE}$"
)
self.assertRefused(stack, b.number, expected)
def merge_into_stack(self, stack: NativeStack, base: str) -> NativeStack:
"""Merges `base` into the branch of the bottom PR of `stack`, that branch
into the next one and so on, as a rebase with merge commits does"""
for index, entry in enumerate(stack.entries):
head = self.merge_into(entry.head_ref, base)
stack = with_entry(stack, index, head_oid=head)
base = entry.head_ref
return stack
def test_refuses_bottom_pr_whose_merge_base_has_its_landing(self) -> None:
stack = self.push_stack()
a, _, c = stack.entries
landed = self.land(a)
self.revert(a, landed)
# As a rebase onto a viable/strict that has the landing but not the revert
stack = self.merge_into_stack(stack, landed)
message = (
rf"^PR #101 landed in {landed}, which its merge base with main still "
rf"has, so its changes would not land again\. {REBASE}$"
)
self.assertRefused(stack, c.number, message)
stack = self.merge_into_stack(stack, TRUNK)
landing = [entry.number for entry, _ in self.landing_prs(stack, c.number)]
self.assertEqual(landing, [101, 102, 103])
def test_refuses_upper_pr_whose_base_has_its_landing(self) -> None:
stack = self.push_stack()
_, b, c = stack.entries
landed = self.land(b)
self.revert(b, landed)
stack = self.merge_into_stack(stack, landed)
message = (
rf"^PR #102 landed in {landed}, which user/a still has, so its changes "
rf"would not land again\. {REBASE}$"
)
for target in (102, 103):
with self.subTest(target=target):
self.assertRefused(stack, target, message)
stack = self.merge_into_stack(stack, TRUNK)
landing = [entry.number for entry, _ in self.landing_prs(stack, c.number)]
self.assertEqual(landing, [101, 102, 103])
class TestBuildNativeStackCommits(GitTestCase):
def setUp(self) -> None:
super().setUp()
self.origin = self.git("remote", "get-url", "origin")
self.bot_git("config", "user.name", BOT_NAME)
self.bot_git("config", "user.email", BOT_EMAIL)
def bot_git(self, *args: str) -> str:
return self.git(*args, cwd=self.repo.repo_dir)
def repo_state(self) -> list[str]:
state = [
self.bot_git(*args)
for args in (
("symbolic-ref", "HEAD"),
("rev-parse", "HEAD"),
("for-each-ref",),
("ls-files", "--stage"),
("status", "--porcelain", "--untracked-files=all"),
)
]
return state + [self.git("for-each-ref", cwd=self.origin)]
def build(
self,
stack: NativeStack,
target: int,
commits: list[tuple[str, str]] | None = None,
) -> list[str]:
"""Builds the commits landing `target` and returns them oldest first, after
checking that they form a linear history on trunk and that neither the bot
clone (HEAD, refs, index, worktree) nor the origin changed."""
landing = self.landing_prs(stack, target)
base = self.repo.rev_parse(TRUNK_REF)
if commits is None:
commits = [
(author(entry.number), landing_message(pr_url(entry.number)))
for entry, _ in landing
]
before = self.repo_state()
try:
# trymerge.yml only sets user.name and user.email; these variables would
# override them and an author given through git config.
with mock.patch.dict(os.environ):
for var in GIT_ENV:
if var.startswith(("GIT_AUTHOR_", "GIT_COMMITTER_")):
del os.environ[var]
last = build_native_stack_commits(self.repo, base, landing, commits)
finally:
self.assertEqual(self.repo_state(), before)
built = [last]
for _ in landing:
parents = self.bot_git("log", "-1", "--format=%P", built[0]).split()
self.assertEqual(len(parents), 1, f"{built[0]} has parents {parents}")
built.insert(0, parents[0])
self.assertEqual(built.pop(0), base)
return built
def tree(self, rev: str) -> str:
return self.bot_git("rev-parse", f"{rev}^{{tree}}")
def files_at(self, rev: str) -> dict[str, str]:
lines = self.bot_git("ls-tree", "-r", rev).splitlines()
return {path: meta.split()[2] for meta, path in (x.split("\t") for x in lines)}
def show(self, rev: str, path: str) -> str:
return self.repo._run_git("show", f"{rev}:{path}")
def message(self, commit: str) -> str:
return self.repo._run_git("cat-file", "commit", commit).partition("\n\n")[2]
def diffs(self, *revs: str) -> list[str]:
return [self.bot_git("diff", old, new) for old, new in pairwise(revs)]
def assertTrunkPlusHeads(self, built: list[str], heads: list[str]) -> None:
trunk = self.files_at(TRUNK_REF)
self.assertEqual(
[self.files_at(commit) for commit in built],
[{**trunk, **self.files_at(head)} for head in heads],
)
def test_reproduces_heads_on_unmoved_trunk(self) -> None:
stack = self.push_stack()
for count in (1, 2, 3):
with self.subTest(target=100 + count):
built = self.build(stack, 100 + count)
heads = [entry.head_oid for entry in stack.entries[:count]]
self.assertEqual(
[self.tree(commit) for commit in built],
[self.tree(head) for head in heads],
)
def test_applies_prs_on_top_of_moved_trunk(self) -> None:
stack = self.push_stack(commits=2)
self.add_commits(TRUNK, 2)
built = self.build(stack, 103)
self.assertTrunkPlusHeads(built, [entry.head_oid for entry in stack.entries])
def test_lands_only_prs_above_landed_pr(self) -> None:
stack = self.push_stack(commits=2)
a, b, c = stack.entries
self.land(a)
built = self.build(with_entry(stack, 0, closed=True), 103)
expected = self.diffs(a.head_oid, b.head_oid, c.head_oid)
self.assertEqual(self.diffs(TRUNK_REF, *built), expected)
def test_upper_pr_undoes_part_of_lower_pr(self) -> None:
stack = self.push_stack(
("user/a", "user/b"),
changes=(
{"shared.txt": "keep\ndrop\n", "gone.txt": "gone\n"},
{"shared.txt": "keep\n", "gone.txt": None},
),
)
self.add_commits(TRUNK)
built = self.build(stack, 102)
self.assertTrunkPlusHeads(built, [entry.head_oid for entry in stack.entries])
self.assertEqual(self.show(built[1], "shared.txt"), "keep\n")
def test_lower_branches_advanced_by_merge_commits(self) -> None:
stack = self.push_stack(("user/a", "user/b"))
self.add_commits(TRUNK)
a_head = self.merge_into("user/a", TRUNK)
b_head = self.merge_into("user/b", "user/a")
self.add_commits(TRUNK)
stack = with_entry(with_entry(stack, 0, head_oid=a_head), 1, head_oid=b_head)
self.assertTrunkPlusHeads(self.build(stack, 102), [a_head, b_head])
def test_refuses_pr_conflicting_with_trunk(self) -> None:
stack = self.push_stack(
("user/a", "user/b"), changes=({"file1.txt": "a\n"}, {"b.txt": "b\n"})
)
self.add_commits(TRUNK, files={"file1.txt": "trunk\n"})
with self.assertRaisesRegex(NativeStackError, r"#101\b"):
self.build(stack, 102)
def test_refuses_pr_already_on_trunk(self) -> None:
stack = self.push_stack()
a, b, _ = stack.entries
self.git("checkout", "-q", TRUNK)
for entry in (b, a):
self.git("cherry-pick", entry.head_oid)
self.git("push", "-q", "origin", TRUNK)
with self.subTest(on_trunk=entry.number):
with self.assertRaisesRegex(NativeStackError, rf"#{entry.number}\b"):
self.build(stack, 103)
def test_sets_author_committer_and_message(self) -> None:
stack = self.push_stack()
commits = [
("Ren\u00e9e O'Brien <renee@example.com>", landing_message(pr_url(101))),
(
author(102),
f"{landing_message(pr_url(102))}{stack_dependencies_line([101])}\n",
),
(
author(103),
"Change (#103)\n\n## Test plan\n\n```\npython test.py\n```\n\n"
f"{PULL_REQUEST_RESOLVED}{pr_url(103)}\n"
f"{stack_dependencies_line([101, 102])}\n",
),
]
built = self.build(stack, 103, commits)
for commit, (name, message) in zip(built, commits, strict=True):
people = self.bot_git("log", "-1", "--format=%an <%ae>%n%cn <%ce>", commit)
self.assertEqual(people.splitlines(), [name, f"{BOT_NAME} <{BOT_EMAIL}>"])
self.assertEqual(self.message(commit), message)
def test_cleans_up_message_like_git_commit(self) -> None:
stack = self.push_stack(("user/a",))
# A carriage return inside a co-author's name stays inside its line
name = f"Name\r{PULL_REQUEST_RESOLVED}{pr_url(4321)}\rName"
message = (
"Change (#101)\r\n\r\n## Summary\r\nDetails \r\n\r\n\r\n\r\n"
f"{PULL_REQUEST_RESOLVED}{pr_url(101)}\r\n\r\n"
f"Co-authored-by: {name} <co@example.com>"
)
built = self.build(stack, 101, [(author(101), message)])
self.assertEqual(
[self.message(commit) for commit in built],
[
"Change (#101)\n\n## Summary\nDetails\n\n"
f"{PULL_REQUEST_RESOLVED}{pr_url(101)}\n\n"
f"Co-authored-by: {name} <co@example.com>\n"
],
)
class TestFindStackDependents(GitTestCase):
def setUp(self) -> None:
super().setUp()
self.landings: dict[int, str] = {}
def land_pr(self, number: int, *deps: int) -> str:
message = landing_message(pr_url(number))
if deps:
message += f"{stack_dependencies_line(list(deps))}\n"
self.landings[number] = self.commit(message)
return self.landings[number]
def revert_pr(self, number: int) -> str:
return self.commit(revert_message(pr_url(number), self.landings[number]))
def land_stack(self) -> tuple[str, str, str]:
return self.land_pr(101), self.land_pr(102, 101), self.land_pr(103, 101, 102)
def found(self, number: int, ref: str = TRUNK) -> tuple[str | None, list[Any]]:
return find_stack_dependents(GitRepo(self.dev), ORG, PROJECT, number, ref)
def dependents(self, number: int, ref: str = TRUNK) -> list[tuple[str, int]]:
return self.found(number, ref)[1]
def test_bottom_pr_has_every_pr_above_it_top_first(self) -> None:
a, b, c = self.land_stack()
self.assertEqual(self.found(101), (a, [(c, 103), (b, 102)]))
def test_reverts_of_reverts_reapply_their_commit(self) -> None:
a, b, c = self.land_stack()
def revert(sha: str) -> str:
return self.commit(f"Revert\n\nThis reverts commit {sha}.\n")
revert(revert(b))
self.assertEqual(self.found(101), (a, [(c, 103), (b, 102)]))
reverted = revert(a)
self.assertEqual(self.found(101), (None, []))
reapplied = revert(reverted)
self.assertEqual(self.found(101), (a, [(c, 103), (b, 102)]))
# Merges and rebases read the reapplied PR as landed too
self.assertEqual(_landed_in(GitRepo(self.dev), pr_url(101), TRUNK, TRUNK), a)
revert(reapplied)
self.assertEqual(self.found(101), (None, []))
def test_dependents_are_ordered_by_their_position_in_the_stack(self) -> None:
_, _, c = self.land_stack()
self.revert_pr(102)
b = self.land_pr(102, 101)
self.assertEqual(self.dependents(101), [(c, 103), (b, 102)])
def test_middle_pr_has_only_the_prs_above_it(self) -> None:
_, _, c = self.land_stack()
self.assertEqual(self.dependents(102), [(c, 103)])
self.assertEqual(self.dependents(103), [])
def test_skips_commits_of_other_prs_and_stacks(self) -> None:
self.land_pr(101)
self.land_pr(200)
b = self.land_pr(102, 101)
self.land_pr(300)
other = self.land_pr(301, 300)
c = self.land_pr(103, 101, 102)
self.commit("Unrelated change")
self.assertEqual(self.dependents(101), [(c, 103), (b, 102)])
self.assertEqual(self.dependents(300), [(other, 301)])
def test_skips_dependents_reverted_since(self) -> None:
_, _, c = self.land_stack()
self.land_pr(104, 101, 102, 103)
self.revert_pr(104)
self.revert_pr(102)
self.assertEqual(self.dependents(101), [(c, 103)])
self.assertEqual(self.dependents(103), [])
def test_stack_dependencies_line_quoted_in_a_body_does_not_count(self) -> None:
self.land_pr(101)
self.land_pr(300)
quoted = stack_dependencies_line([101])
self.commit(landing_message(pr_url(600), f"Landed commits end with\n{quoted}"))
message = landing_message(pr_url(301), quoted)
on_300 = self.commit(f"{message}{stack_dependencies_line([300])}\n")
self.assertEqual(self.dependents(101), [])
self.assertEqual(self.dependents(300), [(on_300, 301)])
def test_dependent_relanded_outside_the_stack_is_not_a_dependent(self) -> None:
_, b, _ = self.land_stack()
self.revert_pr(103)
self.land_pr(103)
self.assertEqual(self.dependents(101), [(b, 102)])
self.assertEqual(self.dependents(102), [])
def test_pr_numbers_in_stack_dependencies_must_match_exactly(self) -> None:
for number in (10, 101, 1011):
self.land_pr(number)
on_10 = self.land_pr(201, 10)
on_101 = self.land_pr(202, 101)
on_1011 = self.land_pr(203, 1011)
on_all = self.land_pr(204, 10, 101, 1011)
self.assertEqual(self.dependents(10), [(on_all, 204), (on_10, 201)])
self.assertEqual(self.dependents(101), [(on_all, 204), (on_101, 202)])
self.assertEqual(self.dependents(1011), [(on_all, 204), (on_1011, 203)])
def test_dependents_landed_before_a_reland_still_count(self) -> None:
_, b, c = self.land_stack()
self.revert_pr(101)
self.land_pr(101)
self.assertEqual(self.dependents(101), [(c, 103), (b, 102)])
def test_pr_without_a_landing_has_no_dependents(self) -> None:
self.land_pr(102, 101)
self.assertEqual(self.dependents(101), [])
self.land_pr(101)
c = self.land_pr(103, 101)
self.assertEqual(self.dependents(101), [(c, 103)])
self.revert_pr(101)
self.assertEqual(self.dependents(101), [])
def test_regular_pr_has_no_dependents(self) -> None:
for number in (101, 102, 103):
self.land_pr(number)
self.assertEqual(self.dependents(101), [])
VIABLE_STRICT = "viable/strict"
# Branch, line of f.txt and label of each PR of a line stack
LINE_STACK = (("user/a", 2, "A"), ("user/b", 6, "B"), ("user/c", 9, "C"))
# Branch updates as build_native_stack_rebase returns them
Updates = list[tuple[int, str, str]]
def lines(edits: dict[int, str]) -> str:
"""f.txt, with each line in `edits` followed by its label"""
return "".join(
f"line {n} {edits[n]}\n" if n in edits else f"line {n}\n" for n in range(1, 11)
)
def identity(person: str) -> dict[str, str]:
"""The environment that makes git author and commit as `person`"""
name, _, email = person.rpartition(" <")
email = email.removesuffix(">")
return {
"GIT_AUTHOR_NAME": name,
"GIT_AUTHOR_EMAIL": email,
"GIT_COMMITTER_NAME": name,
"GIT_COMMITTER_EMAIL": email,
}
@contextmanager
def without_identity_variables() -> Iterator[None]:
"""trymerge.yml and tryrebase.yml only set user.name and user.email; these
variables would override them and any identity the code under test sets
through git config"""
with mock.patch.dict(os.environ):
for var in GIT_ENV:
if var.startswith(("GIT_AUTHOR_", "GIT_COMMITTER_")):
del os.environ[var]
yield
class LineStackTestCase(GitTestCase):
"""A stack whose PRs each change their own line of f.txt and add their own file,
in commits by the PR's author, on an origin that refuses non-fast-forward pushes,
even forced ones"""
def setUp(self) -> None:
super().setUp()
self.origin = self.git("remote", "get-url", "origin")
self.origin_git("config", "receive.denyNonFastForwards", "true")
for key, value in (("user.name", BOT_NAME), ("user.email", BOT_EMAIL)):