File: VCS.hs

package info (click to toggle)
haskell-cabal-install 3.10.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,400 kB
  • sloc: haskell: 52,202; sh: 80; makefile: 9
file content (947 lines) | stat: -rw-r--r-- 38,064 bytes parent folder | download | duplicates (2)
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
{-# LANGUAGE RecordWildCards, NamedFieldPuns, KindSignatures, DataKinds #-}
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications, ScopedTypeVariables #-}
module UnitTests.Distribution.Client.VCS (tests) where

import Distribution.Client.Compat.Prelude
import Distribution.Client.VCS
import Distribution.Client.RebuildMonad
         ( execRebuild )
import Distribution.Simple.Program
import Distribution.System ( buildOS, OS (Windows) )
import Distribution.Verbosity as Verbosity
import Distribution.Client.Types.SourceRepo (SourceRepositoryPackage (..), SourceRepoProxy)

import Data.List (mapAccumL)
import Data.Tuple
import qualified Data.Map as Map
import qualified Data.Set as Set

import qualified Control.Monad.State as State
import Control.Monad.State (StateT, liftIO, execStateT)
import Control.Exception
import Control.Concurrent (threadDelay)

import System.IO
import System.FilePath
import System.Directory
import System.Random

import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.ExpectedFailure
import UnitTests.Distribution.Client.ArbitraryInstances
import UnitTests.TempTestDir (withTestDir, removeDirectoryRecursiveHack)


-- | These tests take the following approach: we generate a pure representation
-- of a repository plus a corresponding real repository, and then run various
-- test operations and compare the actual working state with the expected
-- working state.
--
-- The first test simply checks that the test infrastructure works. It
-- constructs a repository on disk and then checks out every tag or commit
-- and checks that the working state is the same as the pure representation.
--
-- The second test works in a similar way but tests 'syncSourceRepos'. It
-- uses an arbitrary source repo and a set of (initially empty) destination
-- directories. It picks a number of tags or commits from the source repo and
-- synchronises the destination directories to those target states, and then
-- checks that the working state is as expected (given the pure representation).
--
tests :: MTimeChange -> [TestTree]
tests mtimeChange = map (localOption $ QuickCheckTests 10)
  [ ignoreInWindows "See issue #8048" $
    testGroup "git"
    [ testProperty "check VCS test framework"    prop_framework_git
    , testProperty "cloneSourceRepo"             prop_cloneRepo_git
    , testProperty "syncSourceRepos"             prop_syncRepos_git
    ]

    --
  , ignoreTestBecause "for the moment they're not yet working" $
    testGroup "darcs"
    [ testProperty "check VCS test framework"    $ prop_framework_darcs mtimeChange
    , testProperty "cloneSourceRepo"             $ prop_cloneRepo_darcs mtimeChange
    , testProperty "syncSourceRepos"             $ prop_syncRepos_darcs mtimeChange
    ]

  , ignoreTestBecause "for the moment they're not yet working" $
    testGroup "pijul"
    [ testProperty "check VCS test framework"    prop_framework_pijul
    , testProperty "cloneSourceRepo"             prop_cloneRepo_pijul
    , testProperty "syncSourceRepos"             prop_syncRepos_pijul
    ]

  , ignoreTestBecause "for the moment they're not yet working" $
    testGroup "mercurial"
    [ testProperty "check VCS test framework"    prop_framework_hg
    , testProperty "cloneSourceRepo"             prop_cloneRepo_hg
    , testProperty "syncSourceRepos"             prop_syncRepos_hg
    ]

  ]

  where ignoreInWindows msg =  case buildOS of
          Windows -> ignoreTestBecause msg
          _       -> id

prop_framework_git :: BranchingRepoRecipe 'SubmodulesSupported -> Property
prop_framework_git =
    ioProperty
  . prop_framework vcsGit vcsTestDriverGit
  . WithBranchingSupport

prop_framework_darcs :: MTimeChange -> NonBranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_framework_darcs mtimeChange =
    ioProperty
  . prop_framework vcsDarcs (vcsTestDriverDarcs mtimeChange)
  . WithoutBranchingSupport

prop_framework_pijul :: BranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_framework_pijul =
    ioProperty
  . prop_framework vcsPijul vcsTestDriverPijul
  . WithBranchingSupport

prop_framework_hg :: BranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_framework_hg =
    ioProperty
  . prop_framework vcsHg vcsTestDriverHg
  . WithBranchingSupport

prop_cloneRepo_git :: BranchingRepoRecipe 'SubmodulesSupported -> Property
prop_cloneRepo_git =
    ioProperty
  . prop_cloneRepo vcsGit vcsTestDriverGit
  . WithBranchingSupport

prop_cloneRepo_darcs :: MTimeChange
                     -> NonBranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_cloneRepo_darcs mtimeChange =
    ioProperty
  . prop_cloneRepo vcsDarcs (vcsTestDriverDarcs mtimeChange)
  . WithoutBranchingSupport

prop_cloneRepo_pijul :: BranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_cloneRepo_pijul =
    ioProperty
  . prop_cloneRepo vcsPijul vcsTestDriverPijul
  . WithBranchingSupport

prop_cloneRepo_hg :: BranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_cloneRepo_hg =
    ioProperty
  . prop_cloneRepo vcsHg vcsTestDriverHg
  . WithBranchingSupport

prop_syncRepos_git :: RepoDirSet -> SyncTargetIterations -> PrngSeed
                   -> BranchingRepoRecipe 'SubmodulesSupported  -> Property
prop_syncRepos_git destRepoDirs syncTargetSetIterations seed =
    ioProperty
  . prop_syncRepos vcsGit vcsTestDriverGit
                   destRepoDirs syncTargetSetIterations seed
  . WithBranchingSupport

prop_syncRepos_darcs :: MTimeChange
                     -> RepoDirSet -> SyncTargetIterations -> PrngSeed
                     -> NonBranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_syncRepos_darcs  mtimeChange destRepoDirs syncTargetSetIterations seed =
    ioProperty
  . prop_syncRepos vcsDarcs (vcsTestDriverDarcs mtimeChange)
                   destRepoDirs syncTargetSetIterations seed
  . WithoutBranchingSupport

prop_syncRepos_pijul :: RepoDirSet -> SyncTargetIterations -> PrngSeed
                   -> BranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_syncRepos_pijul destRepoDirs syncTargetSetIterations seed =
    ioProperty
  . prop_syncRepos vcsPijul vcsTestDriverPijul
                   destRepoDirs syncTargetSetIterations seed
  . WithBranchingSupport

prop_syncRepos_hg :: RepoDirSet -> SyncTargetIterations -> PrngSeed
                   -> BranchingRepoRecipe 'SubmodulesNotSupported -> Property
prop_syncRepos_hg destRepoDirs syncTargetSetIterations seed =
    ioProperty
  . prop_syncRepos vcsHg vcsTestDriverHg
                   destRepoDirs syncTargetSetIterations seed
  . WithBranchingSupport

-- ------------------------------------------------------------
-- * General test setup
-- ------------------------------------------------------------

testSetup :: VCS Program
          -> (Verbosity -> VCS ConfiguredProgram
                        -> FilePath -> FilePath -> VCSTestDriver)
          -> RepoRecipe submodules
          -> (VCSTestDriver -> FilePath -> RepoState -> IO a)
          -> IO a
testSetup vcs mkVCSTestDriver repoRecipe theTest = do
    -- test setup
    vcs' <- configureVCS verbosity [] vcs
    withTestDir verbosity "vcstest" $ \tmpdir -> do
      let srcRepoPath = tmpdir </> "src"
          submodulesPath = tmpdir </> "submodules"
          vcsDriver   = mkVCSTestDriver verbosity vcs' submodulesPath srcRepoPath
      repoState <- createRepo vcsDriver repoRecipe

      -- actual test
      result <- theTest vcsDriver tmpdir repoState

      return result
  where
    verbosity = silent

-- ------------------------------------------------------------
-- * Test 1: VCS infrastructure
-- ------------------------------------------------------------

-- | This test simply checks that the test infrastructure works. It constructs
-- a repository on disk and then checks out every tag or commit and checks that
-- the working state is the same as the pure representation.
--
prop_framework :: VCS Program
               -> (Verbosity -> VCS ConfiguredProgram
                             -> FilePath -> FilePath -> VCSTestDriver)
               -> RepoRecipe submodules
               -> IO ()
prop_framework vcs mkVCSTestDriver repoRecipe =
    testSetup vcs mkVCSTestDriver repoRecipe $ \vcsDriver tmpdir repoState ->
      mapM_ (checkAtTag vcsDriver tmpdir) (Map.toList (allTags repoState))
  where
    -- Check for any given tag/commit in the 'RepoState' that the working state
    -- matches the actual working state from the repository at that tag/commit.
    checkAtTag VCSTestDriver {..} tmpdir (tagname, expectedState) =
      case vcsCheckoutTag of
        -- We handle two cases: inplace checkouts for VCSs that support it
        -- (e.g. git) and separate dir otherwise (e.g. darcs)
        Left checkoutInplace -> do
          checkoutInplace tagname
          checkExpectedWorkingState vcsIgnoreFiles vcsRepoRoot expectedState

        Right checkoutCloneTo -> do
          checkoutCloneTo tagname destRepoPath
          checkExpectedWorkingState vcsIgnoreFiles destRepoPath expectedState
          removeDirectoryRecursiveHack silent destRepoPath
        where
          destRepoPath = tmpdir </> "dest"


-- ------------------------------------------------------------
-- * Test 2: 'cloneSourceRepo'
-- ------------------------------------------------------------

prop_cloneRepo :: VCS Program
               -> (Verbosity -> VCS ConfiguredProgram
                             -> FilePath -> FilePath -> VCSTestDriver)
               -> RepoRecipe submodules
               -> IO ()
prop_cloneRepo vcs mkVCSTestDriver repoRecipe =
    testSetup vcs mkVCSTestDriver repoRecipe $ \vcsDriver tmpdir repoState ->
      mapM_ (checkAtTag vcsDriver tmpdir) (Map.toList (allTags repoState))
  where
    checkAtTag VCSTestDriver{..} tmpdir (tagname, expectedState) = do
        cloneSourceRepo verbosity vcsVCS repo destRepoPath
        checkExpectedWorkingState vcsIgnoreFiles destRepoPath expectedState
        removeDirectoryRecursiveHack verbosity destRepoPath
      where
        destRepoPath = tmpdir </> "dest"
        repo = SourceRepositoryPackage
            { srpType     = vcsRepoType vcsVCS
            , srpLocation = vcsRepoRoot
            , srpTag      = Just tagname
            , srpBranch   = Nothing
            , srpSubdir   = []
            , srpCommand  = []
            }
    verbosity = silent


-- ------------------------------------------------------------
-- * Test 3: 'syncSourceRepos'
-- ------------------------------------------------------------

newtype RepoDirSet           = RepoDirSet Int           deriving Show
newtype SyncTargetIterations = SyncTargetIterations Int deriving Show
newtype PrngSeed             = PrngSeed Int             deriving Show

prop_syncRepos :: VCS Program
               -> (Verbosity -> VCS ConfiguredProgram
                             -> FilePath -> FilePath -> VCSTestDriver)
               -> RepoDirSet
               -> SyncTargetIterations
               -> PrngSeed
               -> RepoRecipe submodules
               -> IO ()
prop_syncRepos vcs mkVCSTestDriver
               repoDirs syncTargetSetIterations seed repoRecipe =
    testSetup vcs mkVCSTestDriver repoRecipe $ \vcsDriver tmpdir repoState ->
      let srcRepoPath   = vcsRepoRoot vcsDriver
          destRepoPaths = map (tmpdir </>) (getRepoDirs repoDirs)
       in checkSyncRepos verbosity vcsDriver repoState
                         srcRepoPath destRepoPaths
                         syncTargetSetIterations seed
  where
    verbosity = silent

    getRepoDirs :: RepoDirSet -> [FilePath]
    getRepoDirs (RepoDirSet n) =
        [ "dest" ++ show i | i <- [1..n] ]


-- | The purpose of this test is to check that irrespective of the local cached
-- repo dir we can sync it to an arbitrary target state. So we do that by
-- syncing each target dir to a sequence of target states without cleaning it
-- in between.
--
-- One slight complication is that 'syncSourceRepos' takes a whole list of
-- target dirs to sync in one go (to allow for sharing). So we must actually
-- generate and sync to a sequence of list of target repo states.
--
-- So, given a source repo dir, the corresponding 'RepoState' and a number of
-- target repo dirs, pick a sequence of (lists of) sync targets from the
-- 'RepoState' and synchronise the target dirs with those targets, checking for
-- each one that the actual working state matches the expected repo state.
--
checkSyncRepos
  :: Verbosity
  -> VCSTestDriver
  -> RepoState
  -> FilePath
  -> [FilePath]
  -> SyncTargetIterations
  -> PrngSeed
  -> IO ()
checkSyncRepos verbosity VCSTestDriver { vcsVCS = vcs, vcsIgnoreFiles }
               repoState srcRepoPath destRepoPath
               (SyncTargetIterations syncTargetSetIterations) (PrngSeed seed) =
    mapM_ checkSyncTargetSet syncTargetSets
  where
    checkSyncTargetSet :: [(SourceRepoProxy, FilePath, RepoWorkingState)] -> IO ()
    checkSyncTargetSet syncTargets = do
      _ <- execRebuild "root-unused" $
           syncSourceRepos verbosity vcs
                           [ (repo, repoPath)
                           | (repo, repoPath, _) <- syncTargets ]
      sequence_
        [ checkExpectedWorkingState vcsIgnoreFiles repoPath workingState
        | (_, repoPath, workingState) <- syncTargets ]

    syncTargetSets = take syncTargetSetIterations
                   $ pickSyncTargetSets (vcsRepoType vcs) repoState
                                        srcRepoPath destRepoPath
                                        (mkStdGen seed)

pickSyncTargetSets :: RepoType -> RepoState
                   -> FilePath -> [FilePath]
                   -> StdGen
                   -> [[(SourceRepoProxy, FilePath, RepoWorkingState)]]
pickSyncTargetSets repoType repoState srcRepoPath dstReposPath =
    assert (Map.size (allTags repoState) > 0) $
    unfoldr (Just . swap . pickSyncTargetSet)
  where
    pickSyncTargetSet :: Rand [(SourceRepoProxy, FilePath, RepoWorkingState)]
    pickSyncTargetSet = flip (mapAccumL (flip pickSyncTarget)) dstReposPath

    pickSyncTarget :: FilePath -> Rand (SourceRepoProxy, FilePath, RepoWorkingState)
    pickSyncTarget destRepoPath prng =
        (prng', (repo, destRepoPath, workingState))
      where
        repo                = SourceRepositoryPackage
                              { srpType     = repoType
                              , srpLocation = srcRepoPath
                              , srpTag      = Just tag
                              , srpBranch   = Nothing
                              , srpSubdir   = Proxy
                              , srpCommand  = []
                              }
        (tag, workingState) = Map.elemAt tagIdx (allTags repoState)
        (tagIdx, prng')     = randomR (0, Map.size (allTags repoState) - 1) prng

type Rand a = StdGen -> (StdGen, a)

instance Arbitrary RepoDirSet where
  arbitrary =
    sized $ \n -> oneof $ [ RepoDirSet <$> pure 1 ]
                       ++ [ RepoDirSet <$> choose (2,5) | n >= 3 ]
  shrink (RepoDirSet n) =
    [ RepoDirSet i | i <- shrink n, i > 0 ]

instance Arbitrary SyncTargetIterations where
  arbitrary =
    sized $ \n -> SyncTargetIterations <$> elements [ 1 .. min 20 (n + 1) ]
  shrink (SyncTargetIterations n) =
    [ SyncTargetIterations i | i <- shrink n, i > 0 ]

instance Arbitrary PrngSeed where
  arbitrary = PrngSeed <$> arbitraryBoundedRandom


-- ------------------------------------------------------------
-- * Instructions for constructing repositories
-- ------------------------------------------------------------

-- These instructions for constructing a repository can be interpreted in two
-- ways: to make a pure representation of repository state, and to execute
-- VCS commands to make a repository on-disk.

data SubmodulesSupport = SubmodulesSupported | SubmodulesNotSupported

class KnownSubmodulesSupport (a :: SubmodulesSupport) where
  submoduleSupport :: SubmodulesSupport

instance KnownSubmodulesSupport 'SubmodulesSupported where
  submoduleSupport = SubmodulesSupported

instance KnownSubmodulesSupport 'SubmodulesNotSupported where
  submoduleSupport = SubmodulesNotSupported

data FileUpdate   = FileUpdate FilePath String
                  deriving Show
data SubmoduleAdd = SubmoduleAdd FilePath FilePath (Commit 'SubmodulesSupported)
                  deriving Show

newtype Commit (submodules :: SubmodulesSupport)
  = Commit [Either FileUpdate SubmoduleAdd]
  deriving Show

data TaggedCommits (submodules :: SubmodulesSupport)
  = TaggedCommits TagName    [Commit submodules]
  deriving Show

data BranchCommits (submodules :: SubmodulesSupport)
  = BranchCommits BranchName [Commit submodules]
  deriving Show

type BranchName = String
type TagName    = String

-- | Instructions to make a repository without branches, for VCSs that do not
-- support branches (e.g. darcs).
newtype NonBranchingRepoRecipe submodules
  = NonBranchingRepoRecipe [TaggedCommits submodules]
  deriving Show

-- | Instructions to make a repository with branches, for VCSs that do
-- support branches (e.g. git).
newtype BranchingRepoRecipe submodules
  = BranchingRepoRecipe [Either (TaggedCommits submodules) (BranchCommits submodules)]
 deriving Show

data RepoRecipe submodules
  = WithBranchingSupport       (BranchingRepoRecipe submodules)
  | WithoutBranchingSupport (NonBranchingRepoRecipe submodules)
  deriving Show

-- ---------------------------------------------------------------------------
-- Arbitrary instances for them

genFileName :: Gen FilePath
genFileName = (\c -> "file" </> [c]) <$> choose ('A', 'E')

instance Arbitrary FileUpdate where
  arbitrary = genOnlyFileUpdate
    where
      genOnlyFileUpdate   = FileUpdate <$> genFileName <*> genFileContent
      genFileContent      = vectorOf 10 (choose ('#', '~'))

instance Arbitrary SubmoduleAdd where
  arbitrary = genOnlySubmoduleAdd
    where
      genOnlySubmoduleAdd = SubmoduleAdd <$> genFileName <*> genSubmoduleSrc <*> arbitrary
      genSubmoduleSrc     = vectorOf 20 (choose ('a', 'z'))

instance forall submodules.KnownSubmodulesSupport submodules => Arbitrary (Commit submodules) where
  arbitrary = Commit <$> shortListOf1 5 fileUpdateOrSubmoduleAdd
    where
      fileUpdateOrSubmoduleAdd =
        case submoduleSupport @submodules of
          SubmodulesSupported -> frequency [ (10, Left <$> arbitrary)
                                           , (1, Right <$> arbitrary)
                                           ]
          SubmodulesNotSupported -> Left <$> arbitrary
  shrink (Commit writes) = Commit <$> filter (not . null) (shrink writes)

instance KnownSubmodulesSupport submodules => Arbitrary (TaggedCommits submodules) where
  arbitrary = TaggedCommits <$> genTagName <*>  shortListOf1 5 arbitrary
    where
      genTagName = ("tag_" ++) <$> shortListOf1 5 (choose ('A', 'Z'))
  shrink (TaggedCommits tag commits) =
    TaggedCommits tag <$> filter (not . null) (shrink commits)

instance KnownSubmodulesSupport submodules => Arbitrary (BranchCommits submodules) where
  arbitrary = BranchCommits <$> genBranchName <*> shortListOf1 5 arbitrary
    where
      genBranchName =
        sized $ \n ->
          (\c -> "branch_" ++ [c]) <$> elements (take (max 1 n) ['A'..'E'])

  shrink (BranchCommits branch commits) =
    BranchCommits branch <$> filter (not . null) (shrink commits)

instance KnownSubmodulesSupport submodules => Arbitrary (NonBranchingRepoRecipe submodules) where
  arbitrary = NonBranchingRepoRecipe <$> shortListOf1 15 arbitrary
  shrink (NonBranchingRepoRecipe xs) =
    NonBranchingRepoRecipe <$> filter (not . null) (shrink xs)

instance KnownSubmodulesSupport submodules => Arbitrary (BranchingRepoRecipe submodules) where
  arbitrary = BranchingRepoRecipe <$> shortListOf1 15 taggedOrBranch
    where
      taggedOrBranch = frequency [ (3, Left  <$> arbitrary)
                                 , (1, Right <$> arbitrary)
                                 ]
  shrink (BranchingRepoRecipe xs) =
    BranchingRepoRecipe <$> filter (not . null) (shrink xs)


-- ------------------------------------------------------------
-- * A pure model of repository state
-- ------------------------------------------------------------

-- | The full state of a repository. In particular it records the full working
-- state for every tag.
--
-- This is also the interpreter state for executing a 'RepoRecipe'.
--
-- This allows us to compare expected working states with the actual files in
-- the working directory of a repository. See 'checkExpectedWorkingState'.
--
data RepoState =
     RepoState {
       currentBranch  :: BranchName,
       currentWorking :: RepoWorkingState,
       allTags        :: Map TagOrCommitId RepoWorkingState,
       allBranches    :: Map BranchName RepoWorkingState
     }
  deriving Show

type RepoWorkingState = Map FilePath String
type CommitId         = String
type TagOrCommitId    = String


------------------------------------------------------------------------------
-- Functions used to interpret instructions for constructing repositories

initialRepoState :: RepoState
initialRepoState =
    RepoState {
      currentBranch  = "branch_master",
      currentWorking = Map.empty,
      allTags        = Map.empty,
      allBranches    = Map.empty
    }

updateFile :: FilePath -> String -> RepoState -> RepoState
updateFile filename content state@RepoState{currentWorking} =
  let removeSubmodule = Map.filterWithKey (\path _ -> not $ filename `isPrefixOf` path) currentWorking
  in state { currentWorking = Map.insert filename content removeSubmodule }

addSubmodule :: FilePath -> RepoState -> RepoState -> RepoState
addSubmodule submodulePath submoduleState mainState =
  let newFiles = Map.mapKeys (submodulePath </>) (currentWorking submoduleState)
      removeSubmodule = Map.filterWithKey (\path _ -> not $ submodulePath `isPrefixOf` path ) (currentWorking mainState)
      newWorking = Map.union removeSubmodule newFiles
  in mainState { currentWorking = newWorking}

addTagOrCommit :: TagOrCommitId -> RepoState -> RepoState
addTagOrCommit commit state@RepoState{currentWorking, allTags} =
  state { allTags = Map.insert commit currentWorking allTags }

switchBranch :: BranchName -> RepoState -> RepoState
switchBranch branch state@RepoState{currentWorking, currentBranch, allBranches} =
  -- Use updated allBranches to cover case of switching to the same branch
  let allBranches' = Map.insert currentBranch currentWorking allBranches in
  state {
    currentBranch  = branch,
    currentWorking = case Map.lookup branch allBranches' of
                       Just working -> working
                       -- otherwise we're creating a new branch, which starts
                       -- from our current branch state
                       Nothing      -> currentWorking,
    allBranches    = allBranches'
  }


-- ------------------------------------------------------------
-- * Comparing on-disk with expected 'RepoWorkingState'
-- ------------------------------------------------------------

-- | Compare expected working states with the actual files in
-- the working directory of a repository.
--
checkExpectedWorkingState :: Set FilePath
                          -> FilePath -> RepoWorkingState -> IO ()
checkExpectedWorkingState ignore repoPath expectedState = do
    currentState <- getCurrentWorkingState ignore repoPath
    unless (currentState == expectedState) $
      throwIO (WorkingStateMismatch expectedState currentState)

data WorkingStateMismatch =
     WorkingStateMismatch RepoWorkingState -- expected
                          RepoWorkingState -- actual
  deriving Show

instance Exception WorkingStateMismatch

getCurrentWorkingState :: Set FilePath -> FilePath -> IO RepoWorkingState
getCurrentWorkingState ignore repoRoot = do
    entries <- getDirectoryContentsRecursive ignore repoRoot ""
    Map.fromList <$> mapM getFileEntry
                          [ file | (file, isDir) <- entries, not isDir ]
  where
   getFileEntry name =
     withBinaryFile (repoRoot </> name) ReadMode $ \h -> do
       str <- hGetContents h
       _   <- evaluate (length str)
       return (name, str)

getDirectoryContentsRecursive :: Set FilePath -> FilePath -> FilePath
                              -> IO [(FilePath, Bool)]
getDirectoryContentsRecursive ignore dir0 dir = do
    entries  <- getDirectoryContents (dir0 </> dir)
    entries' <- sequence
                  [ do isdir <- doesDirectoryExist (dir0 </> dir </> entry)
                       return (dir </> entry, isdir)
                  | entry <- entries
                  , not (isPrefixOf "." entry)
                  , (dir </> entry) `Set.notMember` ignore
                  ]
    let subdirs = [ d | (d, True)  <- entries' ]
    subdirEntries <- mapM (getDirectoryContentsRecursive ignore dir0) subdirs
    return (concat (entries' : subdirEntries))


-- ------------------------------------------------------------
-- * Executing instructions to make on-disk VCS repos
-- ------------------------------------------------------------

-- | Execute the instructions in a 'RepoRecipe' using the given 'VCSTestDriver'
-- to make an on-disk repository.
--
-- This also returns a 'RepoState'. This is done as part of construction to
-- support VCSs like git that have commit ids, so that those commit ids can be
-- included in the 'RepoState's 'allTags' set.
--
createRepo :: VCSTestDriver -> RepoRecipe submodules -> IO RepoState
createRepo vcsDriver@VCSTestDriver{vcsRepoRoot, vcsInit} recipe = do
    createDirectoryIfMissing True vcsRepoRoot
    createDirectoryIfMissing True (vcsRepoRoot </> "file")
    vcsInit
    execStateT createRepoAction initialRepoState
  where
    createRepoAction :: StateT RepoState IO ()
    createRepoAction = case recipe of
      WithoutBranchingSupport r -> execNonBranchingRepoRecipe vcsDriver r
      WithBranchingSupport    r -> execBranchingRepoRecipe    vcsDriver r

type CreateRepoAction a = VCSTestDriver -> a -> StateT RepoState IO ()

execNonBranchingRepoRecipe :: CreateRepoAction (NonBranchingRepoRecipe submodules)
execNonBranchingRepoRecipe vcsDriver (NonBranchingRepoRecipe taggedCommits) =
    mapM_ (execTaggdCommits vcsDriver) taggedCommits

execBranchingRepoRecipe :: CreateRepoAction (BranchingRepoRecipe submodules)
execBranchingRepoRecipe vcsDriver (BranchingRepoRecipe taggedCommits) =
    mapM_ (either (execTaggdCommits  vcsDriver)
                  (execBranchCommits vcsDriver))
          taggedCommits

execBranchCommits :: CreateRepoAction (BranchCommits submodules)
execBranchCommits vcsDriver@VCSTestDriver{vcsSwitchBranch}
                  (BranchCommits branch commits) = do
    mapM_ (execCommit vcsDriver) commits
    -- add commits and then switch branch
    State.modify (switchBranch branch)
    state <- State.get -- repo state after the commits and branch switch
    liftIO $ vcsSwitchBranch state branch

    -- It may seem odd that we add commits on the existing branch and then
    -- switch branch. In part this is because git cannot branch from an empty
    -- repo state, it complains that the master branch doesn't exist yet.

execTaggdCommits :: CreateRepoAction (TaggedCommits submodules)
execTaggdCommits vcsDriver@VCSTestDriver{vcsTagState}
                 (TaggedCommits tagname commits) = do
    mapM_ (execCommit vcsDriver) commits
    -- add commits then tag
    state <- State.get -- repo state after the commits
    liftIO $ vcsTagState state tagname
    State.modify (addTagOrCommit tagname)

execCommit :: CreateRepoAction (Commit submodules)
execCommit vcsDriver@VCSTestDriver{..} (Commit fileUpdates) = do
    mapM_ (either (execFileUpdate vcsDriver) (execSubmoduleAdd vcsDriver)) fileUpdates
    state <- State.get -- existing state, not updated
    mcommit <- liftIO $ vcsCommitChanges state
    State.modify (maybe id addTagOrCommit mcommit)

execFileUpdate :: CreateRepoAction FileUpdate
execFileUpdate VCSTestDriver{..} (FileUpdate filename content) = do
    isDir <- liftIO $ doesDirectoryExist (vcsRepoRoot </> filename)
    liftIO . when isDir $ removeDirectoryRecursive (vcsRepoRoot </> filename)
    liftIO $ writeFile (vcsRepoRoot </> filename) content
    state <- State.get -- existing state, not updated
    liftIO $ vcsAddFile state filename
    State.modify (updateFile filename content)

execSubmoduleAdd :: CreateRepoAction SubmoduleAdd
execSubmoduleAdd vcsDriver (SubmoduleAdd submodulePath source submoduleCommit) = do
    submoduleVcsDriver <- liftIO $ vcsSubmoduleDriver vcsDriver source
    let submoduleRecipe = WithoutBranchingSupport $ NonBranchingRepoRecipe [TaggedCommits "submodule-tag" [submoduleCommit]]
    submoduleState <- liftIO $ createRepo submoduleVcsDriver submoduleRecipe
    mainState <- State.get -- existing state, not updated
    liftIO $ vcsAddSubmodule vcsDriver mainState (vcsRepoRoot submoduleVcsDriver) submodulePath
    State.modify $ addSubmodule submodulePath submoduleState

-- ------------------------------------------------------------
-- * VCSTestDriver for various VCSs
-- ------------------------------------------------------------

-- | Extends 'VCS' with extra methods to construct a repository. Used by
-- 'createRepo'.
--
-- Several of the methods are allowed to rely on the current 'RepoState'
-- because some VCSs need different commands for initial vs later actions
-- (like adding a file to the tracked set, or creating a new branch).
--
-- The driver instance knows the particular repo directory.
--
data VCSTestDriver = VCSTestDriver {
       vcsVCS             :: VCS ConfiguredProgram,
       vcsRepoRoot        :: FilePath,
       vcsIgnoreFiles     :: Set FilePath,
       vcsInit            :: IO (),
       vcsAddFile         :: RepoState -> FilePath -> IO (),
       vcsSubmoduleDriver :: FilePath -> IO VCSTestDriver,
       vcsAddSubmodule    :: RepoState -> FilePath -> FilePath -> IO (),
       vcsCommitChanges   :: RepoState -> IO (Maybe CommitId),
       vcsTagState        :: RepoState -> TagName -> IO (),
       vcsSwitchBranch    :: RepoState -> BranchName -> IO (),
       vcsCheckoutTag     :: Either (TagName -> IO ())
                                    (TagName -> FilePath -> IO ())
     }


vcsTestDriverGit :: Verbosity -> VCS ConfiguredProgram
                 -> FilePath -> FilePath -> VCSTestDriver
vcsTestDriverGit verbosity vcs submoduleDir repoRoot =
    VCSTestDriver {
      vcsVCS = vcs

    , vcsRepoRoot = repoRoot

    , vcsIgnoreFiles = Set.empty

    , vcsInit =
        git $ ["init"]  ++ verboseArg

    , vcsAddFile = \_ filename ->
        git ["add", filename]

    , vcsCommitChanges = \_state -> do
        git $ [ "-c", "user.name=A", "-c", "user.email=a@example.com"
              , "commit", "--all", "--message=a patch"
              , "--author=A <a@example.com>"
              ] ++ verboseArg
        commit <- git' ["log", "--format=%H", "-1"]
        let commit' = takeWhile (not . isSpace) commit
        return (Just commit')

    , vcsTagState = \_ tagname ->
        git ["tag", "--force", "--no-sign", tagname]

    , vcsSubmoduleDriver =
        pure . vcsTestDriverGit verbosity vcs submoduleDir . (submoduleDir </>)

    , vcsAddSubmodule = \_ source dest -> do
        destExists <- (||) <$> doesFileExist (repoRoot </> dest)
                           <*> doesDirectoryExist (repoRoot </> dest)
        when destExists $ git ["rm", "-f", dest]
        -- If there is an old submodule git dir with the same name, remove it.
        -- It most likely has a different URL and `git submodule add` will fai.
        submoduleGitDirExists <- doesDirectoryExist $ submoduleGitDir dest
        when submoduleGitDirExists $ removeDirectoryRecursive (submoduleGitDir dest)
        git ["submodule", "add", source, dest]
        git ["submodule", "update", "--init", "--recursive", "--force"]

    , vcsSwitchBranch = \RepoState{allBranches} branchname -> do
        deinitAndRemoveCachedSubmodules
        unless (branchname `Map.member` allBranches) $
          git ["branch", branchname]
        git $ ["checkout", branchname] ++ verboseArg
        updateSubmodulesAndCleanup

    , vcsCheckoutTag = Left $ \tagname -> do
        deinitAndRemoveCachedSubmodules
        git $ ["checkout", "--detach", "--force", tagname] ++ verboseArg
        updateSubmodulesAndCleanup
    }
  where
    gitInvocation args = (programInvocation (vcsProgram vcs) args) {
                           progInvokeCwd = Just repoRoot
                         }
    git  = runProgramInvocation       verbosity . gitInvocation
    git' = getProgramInvocationOutput verbosity . gitInvocation
    verboseArg = [ "--quiet" | verbosity < Verbosity.normal ]
    submoduleGitDir path = repoRoot </> ".git" </> "modules" </> path
    deinitAndRemoveCachedSubmodules = do
      git $ ["submodule", "deinit", "--force", "--all"] ++ verboseArg
      let gitModulesDir = repoRoot </> ".git" </> "modules"
      gitModulesExists <- doesDirectoryExist gitModulesDir
      when gitModulesExists $ removeDirectoryRecursive gitModulesDir
    updateSubmodulesAndCleanup = do
      git $ ["submodule", "sync", "--recursive"] ++ verboseArg
      git $ ["submodule", "update", "--init", "--recursive", "--force"] ++ verboseArg
      git $ ["submodule", "foreach", "--recursive"] ++ verboseArg ++ ["git clean -ffxdq"]
      git $ ["clean", "-ffxdq"] ++ verboseArg


type MTimeChange = Int

vcsTestDriverDarcs :: MTimeChange -> Verbosity -> VCS ConfiguredProgram
                   -> FilePath -> FilePath -> VCSTestDriver
vcsTestDriverDarcs mtimeChange verbosity vcs _ repoRoot =
    VCSTestDriver {
      vcsVCS = vcs

    , vcsRepoRoot = repoRoot

    , vcsIgnoreFiles = Set.singleton "_darcs"

    , vcsInit =
        darcs ["initialize"]

    , vcsAddFile = \state filename -> do
        threadDelay mtimeChange
        unless (filename `Map.member` currentWorking state) $
          darcs ["add", filename]
        -- Darcs's file change tracking relies on mtime changes,
        -- so we have to be careful with doing stuff too quickly:

    , vcsSubmoduleDriver = \_->
        fail "vcsSubmoduleDriver: darcs does not support submodules"

    , vcsAddSubmodule = \_ _ _ ->
        fail "vcsAddSubmodule: darcs does not support submodules"

    , vcsCommitChanges = \_state -> do
        threadDelay mtimeChange
        darcs ["record", "--all", "--author=author", "--name=a patch"]
        return Nothing

    , vcsTagState = \_ tagname ->
        darcs ["tag", "--author=author", tagname]

    , vcsSwitchBranch = \_ _ ->
        fail "vcsSwitchBranch: darcs does not support branches within a repo"

    , vcsCheckoutTag = Right $ \tagname dest ->
        darcs ["clone", "--lazy", "--tag=^" ++ tagname ++ "$", ".", dest]
    }
  where
    darcsInvocation args = (programInvocation (vcsProgram vcs) args) {
                               progInvokeCwd = Just repoRoot
                           }
    darcs = runProgramInvocation verbosity . darcsInvocation


vcsTestDriverPijul :: Verbosity -> VCS ConfiguredProgram
                   -> FilePath -> FilePath -> VCSTestDriver
vcsTestDriverPijul verbosity vcs _ repoRoot =
    VCSTestDriver {
      vcsVCS = vcs

    , vcsRepoRoot = repoRoot

    , vcsIgnoreFiles = Set.empty

    , vcsInit =
        pijul $ ["init"]

    , vcsAddFile = \_ filename ->
        pijul ["add", filename]

    , vcsSubmoduleDriver = \_ ->
        fail "vcsSubmoduleDriver: pijul does not support submodules"

    , vcsAddSubmodule = \_ _ _ ->
        fail "vcsAddSubmodule: pijul does not support submodules"

    , vcsCommitChanges = \_state -> do
        pijul $ ["record", "-a", "-m 'a patch'"
                , "-A 'A <a@example.com>'"
                ]
        commit <- pijul' ["log"]
        let commit' = takeWhile (not . isSpace) commit
        return (Just commit')

    -- tags work differently in pijul...
    -- so this is wrong
    , vcsTagState = \_ tagname ->
        pijul ["tag", tagname]

    , vcsSwitchBranch = \_ branchname -> do
--        unless (branchname `Map.member` allBranches) $
--          pijul ["from-branch", branchname]
        pijul $ ["checkout", branchname]

    , vcsCheckoutTag = Left $ \tagname ->
        pijul $ ["checkout", tagname]
    }
  where
    gitInvocation args = (programInvocation (vcsProgram vcs) args) {
                           progInvokeCwd = Just repoRoot
                         }
    pijul  = runProgramInvocation       verbosity . gitInvocation
    pijul' = getProgramInvocationOutput verbosity . gitInvocation

vcsTestDriverHg :: Verbosity -> VCS ConfiguredProgram
                -> FilePath -> FilePath -> VCSTestDriver
vcsTestDriverHg verbosity vcs _ repoRoot =
    VCSTestDriver {
      vcsVCS = vcs

    , vcsRepoRoot = repoRoot

    , vcsIgnoreFiles = Set.empty

    , vcsInit =
        hg $ ["init"]  ++ verboseArg

    , vcsAddFile = \_ filename ->
        hg ["add", filename]

    , vcsSubmoduleDriver = \_ ->
        fail "vcsSubmoduleDriver: hg submodules not supported"

    , vcsAddSubmodule = \_ _ _ ->
        fail "vcsAddSubmodule: hg submodules not supported"

    , vcsCommitChanges = \_state -> do
        hg $ [ "--user='A <a@example.com>'"
              , "commit", "--message=a patch"
              ] ++ verboseArg
        commit <- hg' ["log", "--template='{node}\\n' -l1"]
        let commit' = takeWhile (not . isSpace) commit
        return (Just commit')

    , vcsTagState = \_ tagname ->
        hg ["tag", "--force", tagname]

    , vcsSwitchBranch = \RepoState{allBranches} branchname -> do
        unless (branchname `Map.member` allBranches) $
          hg ["branch", branchname]
        hg $ ["checkout", branchname] ++ verboseArg

    , vcsCheckoutTag = Left $ \tagname ->
        hg $ ["checkout", "--rev", tagname] ++ verboseArg
    }
  where
    hgInvocation args = (programInvocation (vcsProgram vcs) args) {
                           progInvokeCwd = Just repoRoot
                         }
    hg  = runProgramInvocation       verbosity . hgInvocation
    hg' = getProgramInvocationOutput verbosity . hgInvocation
    verboseArg = [ "--quiet" | verbosity < Verbosity.normal ]