Documentation
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
#!/usr/bin/env python3

import os
import re
import subprocess
import tempfile
import textwrap

import git
import pytest
from helpers import (
    NonExistentPath,
    TempGitFileRemote,
    TempGitRepository,
    checksum_directory,
    grm,
    shell,
)

templates = {
    "repo_simple": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "test"
        """,
        "yaml": """
            trees:
            - root: "{root}"
              repos:
              - name: "test"
        """,
    },
    "repo_with_remote": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "test"

            [[trees.repos.remotes]]
            name = "{remotename}"
            url = "file://{remote}"
            type = "file"
        """,
        "yaml": textwrap.dedent(
            """
            trees:
            - root: "{root}"
              repos:
              - name: test
                remotes:
                - name: "{remotename}"
                  url: "file://{remote}"
                  type: "file"
        """
        ),
    },
    "repo_with_two_remotes": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "test"

            [[trees.repos.remotes]]
            name = "origin"
            url = "file://{remote1}"
            type = "file"

            [[trees.repos.remotes]]
            name = "origin2"
            url = "file://{remote2}"
            type = "file"
        """,
        "yaml": textwrap.dedent(
            """
            trees:
            - root: "{root}"
              repos:
              - name: "test"
                remotes:
                - name: "origin"
                  url: "file://{remote1}"
                  type: "file"
                - name: "origin2"
                  url: "file://{remote2}"
                  type: "file"
        """
        ),
    },
    "worktree_repo_simple": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "test"
            worktree_setup = true
        """,
        "yaml": textwrap.dedent(
            """
            trees:
            - root: "{root}"
              repos:
              - name: test
                worktree_setup: true
        """
        ),
    },
    "worktree_repo_with_remote": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "test"
            worktree_setup = true

            [[trees.repos.remotes]]
            name = "origin"
            url = "file://{remote}"
            type = "file"
        """,
        "yaml": textwrap.dedent(
            """
            trees:
            - root: "{root}"
              repos:
              - name: test
                worktree_setup: true
                remotes:
                - name: origin
                  url: "file://{remote}"
                  type: "file"
        """
        ),
    },
    "repo_in_subdirectory": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "outer/inner"

            [[trees.repos.remotes]]
            name = "origin"
            url = "file://{remote}"
            type = "file"
        """,
        "yaml": textwrap.dedent(
            """
            trees:
            - root: "{root}"
              repos:
              - name: outer/inner
                remotes:
                - name: origin
                  url: "file://{remote}"
                  type: "file"
        """
        ),
    },
    "nested_trees": {
        "toml": """
            [[trees]]
            root = "{root}"

            [[trees.repos]]
            name = "outer"

            [[trees.repos.remotes]]
            name = "origin"
            url = "file://{remote1}"
            type = "file"

            [[trees]]
            root = "{root}/subdir"

            [[trees.repos]]
            name = "inner"

            [[trees.repos.remotes]]
            name = "origin"
            url = "file://{remote2}"
            type = "file"
        """,
        "yaml": textwrap.dedent(
            """
            trees:
            - root: "{root}"
              repos:
              - name: outer
                remotes:
                - name: origin
                  url: "file://{remote1}"
                  type: "file"
            - root: "{root}/subdir"
              repos:
              - name: inner
                remotes:
                - name: origin
                  url: "file://{remote2}"
                  type: "file"
        """
        ),
    },
}


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_config_is_valid_symlink(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote, head_commit_sha):
            with tempfile.NamedTemporaryFile() as config:
                with tempfile.TemporaryDirectory() as config_dir:
                    config_symlink = os.path.join(config_dir, "cfglink")
                    os.symlink(config.name, config_symlink)

                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote, remotename="origin"
                            )
                        )

                    subprocess.run(["cat", config.name])

                    cmd = grm(["repos", "sync", "config", "--config", config_symlink])
                    assert cmd.returncode == 0

                    git_dir = os.path.join(target, "test")
                    assert os.path.exists(git_dir)
                    with git.Repo(git_dir) as repo:
                        assert not repo.bare
                        assert not repo.is_dirty()
                        assert set([str(r) for r in repo.remotes]) == {"origin"}
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == head_commit_sha


def test_repos_sync_config_is_invalid_symlink():
    with tempfile.TemporaryDirectory() as target:
        with tempfile.TemporaryDirectory() as config_dir:
            with NonExistentPath() as nonexistent_dir:
                config_symlink = os.path.join(config_dir, "cfglink")
                os.symlink(nonexistent_dir, config_symlink)

                cmd = grm(["repos", "sync", "config", "--config", config_symlink])

                assert cmd.returncode != 0
                assert len(cmd.stdout) == 0
                assert "not found" in cmd.stderr.lower()
                assert not os.path.exists(os.path.join(target, "test"))
                assert not os.path.exists(os.path.join(target, "test"))


def test_repos_sync_config_is_directory():
    with tempfile.TemporaryDirectory() as config:
        cmd = grm(["repos", "sync", "config", "--config", config])

        assert cmd.returncode != 0
        assert len(cmd.stdout) == 0
        assert "is a directory" in cmd.stderr.lower()


def test_repos_sync_config_is_unreadable():
    with tempfile.TemporaryDirectory() as config_dir:
        config_path = os.path.join(config_dir, "cfg")
        open(config_path, "w")
        os.chmod(config_path, 0o0000)
        cmd = grm(["repos", "sync", "config", "--config", config_path])

        assert os.path.exists(config_path)
        assert cmd.returncode != 0
        assert len(cmd.stdout) == 0


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_unmanaged_repos(configtype):
    with tempfile.TemporaryDirectory() as root:
        with TempGitRepository(dir=root) as unmanaged_repo:
            with tempfile.NamedTemporaryFile() as config:
                with open(config.name, "w") as f:
                    f.write(templates["repo_simple"][configtype].format(root=root))

                cmd = grm(["repos", "sync", "config", "--config", config.name])
                assert cmd.returncode == 0

                git_dir = os.path.join(root, "test")
                assert os.path.exists(git_dir)

                # this removes the prefix (root) from the path (unmanaged_repo)
                unmanaged_repo_name = os.path.relpath(unmanaged_repo, root)
                regex = f".*unmanaged.*{unmanaged_repo_name}"
                assert any(
                    [re.match(regex, line) for line in cmd.stderr.lower().split("\n")]
                )


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_root_is_file(configtype):
    with tempfile.NamedTemporaryFile() as target:
        with tempfile.NamedTemporaryFile() as config:
            with open(config.name, "w") as f:
                f.write(templates["repo_simple"][configtype].format(root=target.name))

            cmd = grm(["repos", "sync", "config", "--config", config.name])
            assert cmd.returncode != 0
            assert "notadirectory" in cmd.stderr.lower()


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_clone(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_two_remotes"][configtype].format(
                                root=target, remote1=remote1, remote2=remote2
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    git_dir = os.path.join(target, "test")
                    assert os.path.exists(git_dir)
                    with git.Repo(git_dir) as repo:
                        assert not repo.bare
                        assert not repo.is_dirty()
                        assert set([str(r) for r in repo.remotes]) == {
                            "origin",
                            "origin2",
                        }
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == remote1_head_commit_sha

                        assert len(repo.remotes) == 2
                        urls = list(repo.remote("origin").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote1}"

                        urls = list(repo.remote("origin2").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote2}"


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_repo_in_subdirectory(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote, remote_head_commit_sha):
            with tempfile.NamedTemporaryFile() as config:
                with open(config.name, "w") as f:
                    f.write(
                        templates["repo_in_subdirectory"][configtype].format(
                            root=target, remote=remote
                        )
                    )

                cmd = grm(["repos", "sync", "config", "--config", config.name])
                assert cmd.returncode == 0

                git_dir = os.path.join(target, "outer", "inner")
                assert os.path.exists(git_dir)
                with git.Repo(git_dir) as repo:
                    assert not repo.bare
                    assert not repo.is_dirty()
                    assert set([str(r) for r in repo.remotes]) == {"origin"}
                    assert str(repo.active_branch) == "master"
                    assert str(repo.head.commit) == remote_head_commit_sha

                    assert len(repo.remotes) == 1
                    urls = list(repo.remote("origin").urls)
                    assert len(urls) == 1
                    assert urls[0] == f"file://{remote}"

                cmd = grm(["repos", "sync", "config", "--config", config.name])
                assert "found unmanaged repository" not in cmd.stderr.lower()


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_nested_clone(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["nested_trees"][configtype].format(
                                root=target, remote1=remote1, remote2=remote2
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    def validate(git_dir, sha, remote):
                        assert os.path.exists(git_dir)
                        with git.Repo(git_dir) as repo:
                            assert not repo.bare
                            assert not repo.is_dirty()
                            assert set([str(r) for r in repo.remotes]) == {"origin"}
                            assert str(repo.active_branch) == "master"
                            assert str(repo.head.commit) == sha

                            assert len(repo.remotes) == 1
                            urls = list(repo.remote("origin").urls)
                            assert len(urls) == 1
                            assert urls[0] == f"file://{remote}"

                    validate(
                        os.path.join(target, "outer"), remote1_head_commit_sha, remote1
                    )
                    validate(
                        os.path.join(target, "subdir", "inner"),
                        remote2_head_commit_sha,
                        remote2,
                    )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    print(cmd.stdout)
                    print(cmd.stderr)
                    assert "found unmanaged repository" not in cmd.stderr.lower()


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_init(configtype):
    with tempfile.TemporaryDirectory() as target:
        with tempfile.NamedTemporaryFile() as config:
            with open(config.name, "w") as f:
                f.write(templates["repo_simple"][configtype].format(root=target))

            cmd = grm(["repos", "sync", "config", "--config", config.name])
            assert cmd.returncode == 0

            git_dir = os.path.join(target, "test")
            assert os.path.exists(git_dir)
            with git.Repo(git_dir) as repo:
                assert not repo.bare
                assert not repo.is_dirty()
                # as there are no commits yet, HEAD does not point to anything
                # valid
                assert not repo.head.is_valid()


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_add_remote(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    git_dir = os.path.join(target, "test")

                    assert os.path.exists(git_dir)
                    with git.Repo(git_dir) as repo:
                        assert not repo.bare
                        assert not repo.is_dirty()
                        assert set([str(r) for r in repo.remotes]) == {"origin"}
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == remote1_head_commit_sha

                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_two_remotes"][configtype].format(
                                root=target, remote1=remote1, remote2=remote2
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0
                    with git.Repo(git_dir) as repo:
                        assert set([str(r) for r in repo.remotes]) == {
                            "origin",
                            "origin2",
                        }

                        urls = list(repo.remote("origin").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote1}"

                        urls = list(repo.remote("origin2").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote2}"


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_remove_remote(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_two_remotes"][configtype].format(
                                root=target, remote1=remote1, remote2=remote2
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    git_dir = os.path.join(target, "test")

                    assert os.path.exists(git_dir)
                    with git.Repo(git_dir) as repo:
                        assert not repo.bare
                        assert not repo.is_dirty()
                        assert set([str(r) for r in repo.remotes]) == {
                            "origin",
                            "origin2",
                        }
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == remote1_head_commit_sha

                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote2, remotename="origin2"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0
                    shell(f"cd {git_dir} && git remote -v")
                    with git.Repo(git_dir) as repo:
                        """
                        There is some bug(?) in GitPython. It does not properly
                        detect removed remotes. It will still report the old
                        remove in repo.remotes.

                        So instead, we make sure that we get an Exception when
                        we try to access the old remove via repo.remote().

                        Note that repo.remote() checks the actual repo lazily.
                        Even `exists()` seems to just check against repo.remotes
                        and will return True even if the remote is not actually
                        configured. So we have to force GitPython to hit the filesystem.
                        calling Remotes.urls does. But it returns an iterator
                        that first has to be unwrapped via list(). Only THEN
                        do we actually get an exception of the remotes does not
                        exist.
                        """
                        with pytest.raises(git.exc.GitCommandError):
                            list(repo.remote("origin").urls)

                        urls = list(repo.remote("origin2").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote2}"


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_change_remote_url(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    git_dir = os.path.join(target, "test")

                    assert os.path.exists(git_dir)
                    with git.Repo(git_dir) as repo:
                        assert not repo.bare
                        assert not repo.is_dirty()
                        assert set([str(r) for r in repo.remotes]) == {"origin"}
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == remote1_head_commit_sha

                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote2, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0
                    with git.Repo(git_dir) as repo:
                        assert set([str(r) for r in repo.remotes]) == {"origin"}

                        urls = list(repo.remote("origin").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote2}"


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_change_remote_name(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    git_dir = os.path.join(target, "test")

                    assert os.path.exists(git_dir)
                    with git.Repo(git_dir) as repo:
                        assert not repo.bare
                        assert not repo.is_dirty()
                        assert set([str(r) for r in repo.remotes]) == {"origin"}
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == remote1_head_commit_sha

                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin2"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0
                    with git.Repo(git_dir) as repo:
                        # See the note in `test_repos_sync_normal_remove_remote()`
                        # about repo.remotes
                        with pytest.raises(git.exc.GitCommandError):
                            list(repo.remote("origin").urls)

                        urls = list(repo.remote("origin2").urls)
                        assert len(urls) == 1
                        assert urls[0] == f"file://{remote1}"


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
@pytest.mark.parametrize("init_worktree", [True, False, "default"])
def test_repos_sync_worktree_clone(configtype, init_worktree):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote, head_commit_sha):
            with tempfile.NamedTemporaryFile() as config:
                with open(config.name, "w") as f:
                    f.write(
                        templates["worktree_repo_with_remote"][configtype].format(
                            root=target, remote=remote, remotename="origin"
                        )
                    )

                args = ["repos", "sync", "config", "--config", config.name]
                if init_worktree is True:
                    args.append("--init-worktree=true")
                if init_worktree is False:
                    args.append("--init-worktree=false")

                for i in [1, 2]:
                    cmd = grm(args)
                    assert cmd.returncode == 0

                    worktree_dir = f"{target}/test"
                    assert os.path.exists(worktree_dir)

                    if init_worktree is True or init_worktree == "default":
                        assert set(os.listdir(worktree_dir)) == {
                            ".git-main-working-tree",
                            "master",
                        }
                    else:
                        assert set(os.listdir(worktree_dir)) == {
                            ".git-main-working-tree"
                        }

                    with git.Repo(
                        os.path.join(worktree_dir, ".git-main-working-tree")
                    ) as repo:
                        assert repo.bare
                        assert set([str(r) for r in repo.remotes]) == {"origin"}
                        assert str(repo.active_branch) == "master"
                        assert str(repo.head.commit) == head_commit_sha


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_worktree_init(configtype):
    with tempfile.TemporaryDirectory() as target:
        with tempfile.NamedTemporaryFile() as config:
            with open(config.name, "w") as f:
                f.write(
                    templates["worktree_repo_simple"][configtype].format(root=target)
                )

            cmd = grm(["repos", "sync", "config", "--config", config.name])
            assert cmd.returncode == 0

            worktree_dir = f"{target}/test"
            assert os.path.exists(worktree_dir)

            assert set(os.listdir(worktree_dir)) == {".git-main-working-tree"}
            with git.Repo(os.path.join(worktree_dir, ".git-main-working-tree")) as repo:
                assert repo.bare
                # as there are no commits yet, HEAD does not point to anything
                # valid
                assert not repo.head.is_valid()


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_invalid_syntax(configtype):
    with tempfile.NamedTemporaryFile() as config:
        with open(config.name, "w") as f:
            if configtype == "toml":
                f.write(
                    """
                    [[trees]]
                    root = invalid as there are no quotes ;)
                """
                )
            elif configtype == "yaml":
                f.write(
                    """
                    trees:
                    wrong:
                    indentation:
                """
                )
            else:
                raise NotImplementedError()
            cmd = grm(["repos", "sync", "config", "--config", config.name])
            assert cmd.returncode != 0


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_unchanged(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_two_remotes"][configtype].format(
                                root=target, remote1=remote1, remote2=remote2
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    before = checksum_directory(target)
                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    after = checksum_directory(target)
                    assert cmd.returncode == 0

                    assert before == after


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_normal_change_to_worktree(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    with open(config.name, "w") as f:
                        f.write(
                            templates["worktree_repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode != 0
                    assert "already exists" in cmd.stderr
                    assert "not using a worktree setup" in cmd.stderr


@pytest.mark.parametrize("configtype", ["toml", "yaml"])
def test_repos_sync_worktree_change_to_normal(configtype):
    with tempfile.TemporaryDirectory() as target:
        with TempGitFileRemote() as (remote1, remote1_head_commit_sha):
            with TempGitFileRemote() as (remote2, remote2_head_commit_sha):
                with tempfile.NamedTemporaryFile() as config:
                    with open(config.name, "w") as f:
                        f.write(
                            templates["worktree_repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode == 0

                    with open(config.name, "w") as f:
                        f.write(
                            templates["repo_with_remote"][configtype].format(
                                root=target, remote=remote1, remotename="origin"
                            )
                        )

                    cmd = grm(["repos", "sync", "config", "--config", config.name])
                    assert cmd.returncode != 0
                    assert "already exists" in cmd.stderr
                    assert "using a worktree setup" in cmd.stderr