File: IntegrationTests2.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 (2252 lines) | stat: -rw-r--r-- 96,916 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}

-- For the handy instance IsString PackageIdentifier
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Main where

import Distribution.Client.Compat.Prelude
import Prelude ()

import Distribution.Client.DistDirLayout
import Distribution.Client.ProjectConfig
import Distribution.Client.HttpUtils
import Distribution.Client.TargetSelector hiding (DirActions(..))
import qualified Distribution.Client.TargetSelector as TS (DirActions(..))
import Distribution.Client.ProjectPlanning
import Distribution.Client.ProjectPlanning.Types
import Distribution.Client.ProjectBuilding
import Distribution.Client.ProjectOrchestration
         ( resolveTargets, distinctTargetComponents )
import Distribution.Client.TargetProblem
         ( TargetProblem', TargetProblem (..) )
import Distribution.Client.Types
         ( PackageLocation(..), UnresolvedSourcePackage
         , PackageSpecifier(..) )
import Distribution.Client.Targets
         ( UserConstraint(..), UserConstraintScope(UserAnyQualifier) )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Solver.Types.SourcePackage as SP
import Distribution.Solver.Types.ConstraintSource
         ( ConstraintSource(ConstraintSourceUnknown) )
import Distribution.Solver.Types.PackageConstraint
         ( PackageProperty(PackagePropertySource) )

import qualified Distribution.Client.CmdBuild          as CmdBuild
import qualified Distribution.Client.CmdRepl           as CmdRepl
import qualified Distribution.Client.CmdRun            as CmdRun
import qualified Distribution.Client.CmdTest           as CmdTest
import qualified Distribution.Client.CmdBench          as CmdBench
import qualified Distribution.Client.CmdHaddock        as CmdHaddock
import qualified Distribution.Client.CmdListBin        as CmdListBin

import Distribution.Package
import Distribution.PackageDescription
import Distribution.InstalledPackageInfo (InstalledPackageInfo)
import Distribution.Simple.Setup (toFlag, HaddockFlags(..), defaultHaddockFlags)
import Distribution.Client.Setup (globalCommand)
import Distribution.Client.Config (loadConfig, SavedConfig(savedGlobalFlags), createDefaultConfigFile)
import Distribution.Simple.Compiler
import Distribution.Simple.Command
import qualified Distribution.Simple.Flag as Flag
import Distribution.System
import Distribution.Version
import Distribution.ModuleName (ModuleName)
import Distribution.Text
import Distribution.Utils.Path
import qualified Distribution.Client.CmdHaddockProject as CmdHaddockProject
import Distribution.Client.Setup (globalStoreDir)
import Distribution.Client.GlobalFlags (defaultGlobalFlags)
import Distribution.Simple.Setup (HaddockProjectFlags(..), defaultHaddockProjectFlags)

import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.List (isInfixOf)

import Control.Monad
import Control.Concurrent (threadDelay)
import Control.Exception hiding (assert)
import System.FilePath
import System.Directory
import System.IO (hPutStrLn, stderr)

import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.Options
import Data.Tagged (Tagged(..))
import qualified Data.List as L

import qualified Data.ByteString as BS
import Distribution.Client.GlobalFlags (GlobalFlags, globalNix)
import Distribution.Simple.Flag (Flag (Flag, NoFlag))
import Data.Maybe (fromJust)

#if !MIN_VERSION_directory(1,2,7)
removePathForcibly :: FilePath -> IO ()
removePathForcibly = removeDirectoryRecursive
#endif

main :: IO ()
main =
  defaultMainWithIngredients
    (defaultIngredients ++ [includingOptions projectConfigOptionDescriptions])
    (withProjectConfig $ \config ->
      testGroup "Integration tests (internal)"
                (tests config))


tests :: ProjectConfig -> [TestTree]
tests config =
    --TODO: tests for:
    -- * normal success
    -- * dry-run tests with changes
  [ testGroup "Discovery and planning" $
    [ testCase "find root"      testFindProjectRoot
    , testCase "find root fail" testExceptionFindProjectRoot
    , testCase "no package"    (testExceptionInFindingPackage config)
    , testCase "no package2"   (testExceptionInFindingPackage2 config)
    , testCase "proj conf1"    (testExceptionInProjectConfig config)
    ]
  , testGroup "Target selectors" $
    [ testCaseSteps "valid"              testTargetSelectors
    , testCase      "bad syntax"         testTargetSelectorBadSyntax
    , testCaseSteps "ambiguous syntax"   testTargetSelectorAmbiguous
    , testCase      "no current pkg"     testTargetSelectorNoCurrentPackage
    , testCase      "no targets"         testTargetSelectorNoTargets
    , testCase      "project empty"      testTargetSelectorProjectEmpty
    , testCase      "canonicalized path" testTargetSelectorCanonicalizedPath
    , testCase      "problems (common)"  (testTargetProblemsCommon config)
    , testCaseSteps "problems (build)"   (testTargetProblemsBuild config)
    , testCaseSteps "problems (repl)"    (testTargetProblemsRepl config)
    , testCaseSteps "problems (run)"     (testTargetProblemsRun config)
    , testCaseSteps "problems (list-bin)" (testTargetProblemsListBin config)
    , testCaseSteps "problems (test)"    (testTargetProblemsTest config)
    , testCaseSteps "problems (bench)"   (testTargetProblemsBench config)
    , testCaseSteps "problems (haddock)" (testTargetProblemsHaddock config)
    ]
  , testGroup "Exceptions during building (local inplace)" $
    [ testCase "configure"   (testExceptionInConfigureStep config)
    , testCase "build"       (testExceptionInBuildStep config)
--    , testCase "register"   testExceptionInRegisterStep
    ]
    --TODO: need to repeat for packages for the store
    --TODO: need to check we can build sub-libs, foreign libs and exes
    -- components for non-local packages / packages in the store.

  , testGroup "Successful builds" $
    [ testCaseSteps "Setup script styles" (testSetupScriptStyles config)
    , testCase      "keep-going"          (testBuildKeepGoing config)
#ifndef mingw32_HOST_OS
    -- disabled because https://github.com/haskell/cabal/issues/6272
    , testCase      "local tarball"       (testBuildLocalTarball config)
#endif
    ]

  , testGroup "Regression tests" $
    [ testCase "issue #3324" (testRegressionIssue3324 config)
    , testCase "program options scope all" (testProgramOptionsAll config)
    , testCase "program options scope local" (testProgramOptionsLocal config)
    , testCase "program options scope specific" (testProgramOptionsSpecific config)
    ]
  , testGroup "Flag tests" $
    [
      testCase "Test Nix Flag" testNixFlags,
      testCase "Test Config options for commented options" testConfigOptionComments,
      testCase "Test Ignore Project Flag" testIgnoreProjectFlag
    ]
  , testGroup "haddock-project"
    [ testCase "dependencies" (testHaddockProjectDependencies config)
    ]
  ]

testFindProjectRoot :: Assertion
testFindProjectRoot = do
    Left (BadProjectRootExplicitFile file) <- findProjectRoot (Just testdir)
                                                              (Just testfile)
    file @?= testfile
  where
    testdir  = basedir </> "exception" </> "no-pkg2"
    testfile = "bklNI8O1OpOUuDu3F4Ij4nv3oAqN"


testExceptionFindProjectRoot :: Assertion
testExceptionFindProjectRoot = do
    Right (ProjectRootExplicit dir _) <- findProjectRoot (Just testdir) Nothing
    cwd <- getCurrentDirectory
    dir @?= cwd </> testdir
  where
    testdir = basedir </> "exception" </> "no-pkg2"


testTargetSelectors :: (String -> IO ()) -> Assertion
testTargetSelectors reportSubCase = do
    (_, _, _, localPackages, _) <- configureProject testdir config
    let readTargetSelectors' = readTargetSelectorsWith (dirActions testdir)
                                                       localPackages
                                                       Nothing

    reportSubCase "cwd"
    do Right ts <- readTargetSelectors' []
       ts @?= [TargetPackage TargetImplicitCwd ["p-0.1"] Nothing]

    reportSubCase "all"
    do Right ts <- readTargetSelectors'
                     ["all", ":all"]
       ts @?= replicate 2 (TargetAllPackages Nothing)

    reportSubCase "filter"
    do Right ts <- readTargetSelectors'
                     [ "libs",  ":cwd:libs"
                     , "flibs", ":cwd:flibs"
                     , "exes",  ":cwd:exes"
                     , "tests", ":cwd:tests"
                     , "benchmarks", ":cwd:benchmarks"]
       zipWithM_ (@?=) ts
         [ TargetPackage TargetImplicitCwd ["p-0.1"] (Just kind)
         | kind <- concatMap (replicate 2) [LibKind .. ]
         ]

    reportSubCase "all:filter"
    do Right ts <- readTargetSelectors'
                     [ "all:libs",  ":all:libs"
                     , "all:flibs", ":all:flibs"
                     , "all:exes",  ":all:exes"
                     , "all:tests", ":all:tests"
                     , "all:benchmarks", ":all:benchmarks"]
       zipWithM_ (@?=) ts
         [ TargetAllPackages (Just kind)
         | kind <- concatMap (replicate 2) [LibKind .. ]
         ]

    reportSubCase "pkg"
    do Right ts <- readTargetSelectors'
                     [       ":pkg:p", ".",  "./",   "p.cabal"
                     , "q",  ":pkg:q", "q/", "./q/", "q/q.cabal"]
       ts @?= replicate 4 (mkTargetPackage "p-0.1")
           ++ replicate 5 (mkTargetPackage "q-0.1")

    reportSubCase "pkg:filter"
    do Right ts <- readTargetSelectors'
                     [ "p:libs",  ".:libs",  ":pkg:p:libs"
                     , "p:flibs", ".:flibs", ":pkg:p:flibs"
                     , "p:exes",  ".:exes",  ":pkg:p:exes"
                     , "p:tests", ".:tests",  ":pkg:p:tests"
                     , "p:benchmarks", ".:benchmarks", ":pkg:p:benchmarks"
                     , "q:libs",  "q/:libs", ":pkg:q:libs"
                     , "q:flibs", "q/:flibs", ":pkg:q:flibs"
                     , "q:exes",  "q/:exes", ":pkg:q:exes"
                     , "q:tests", "q/:tests", ":pkg:q:tests"
                     , "q:benchmarks", "q/:benchmarks", ":pkg:q:benchmarks"]
       zipWithM_ (@?=) ts $
         [ TargetPackage TargetExplicitNamed ["p-0.1"] (Just kind)
         | kind <- concatMap (replicate 3) [LibKind .. ]
         ] ++
         [ TargetPackage TargetExplicitNamed ["q-0.1"] (Just kind)
         | kind <- concatMap (replicate 3) [LibKind .. ]
         ]

    reportSubCase "component"
    do Right ts <- readTargetSelectors'
                     [ "p", "lib:p", "p:lib:p", ":pkg:p:lib:p"
                     ,      "lib:q", "q:lib:q", ":pkg:q:lib:q" ]
       ts @?= replicate 4 (TargetComponent "p-0.1" (CLibName LMainLibName) WholeComponent)
           ++ replicate 3 (TargetComponent "q-0.1" (CLibName LMainLibName) WholeComponent)

    reportSubCase "module"
    do Right ts <- readTargetSelectors'
                     [ "P", "lib:p:P", "p:p:P", ":pkg:p:lib:p:module:P"
                     , "QQ", "lib:q:QQ", "q:q:QQ", ":pkg:q:lib:q:module:QQ"
                     , "pexe:PMain" -- p:P or q:QQ would be ambiguous here
                     , "qexe:QMain" -- package p vs component p
                     ]
       ts @?= replicate 4 (TargetComponent "p-0.1" (CLibName LMainLibName) (ModuleTarget "P"))
           ++ replicate 4 (TargetComponent "q-0.1" (CLibName LMainLibName) (ModuleTarget "QQ"))
           ++ [ TargetComponent "p-0.1" (CExeName "pexe") (ModuleTarget "PMain")
              , TargetComponent "q-0.1" (CExeName "qexe") (ModuleTarget "QMain")
              ]

    reportSubCase "file"
    do Right ts <- readTargetSelectors'
                     [ "./P.hs", "p:P.lhs", "lib:p:P.hsc", "p:p:P.hsc",
                                 ":pkg:p:lib:p:file:P.y"
                     , "q/QQ.hs", "q:QQ.lhs", "lib:q:QQ.hsc", "q:q:QQ.hsc",
                                  ":pkg:q:lib:q:file:QQ.y"
                     , "q/Q.hs", "q:Q.lhs", "lib:q:Q.hsc", "q:q:Q.hsc",
                                  ":pkg:q:lib:q:file:Q.y"
                     , "app/Main.hs", "p:app/Main.hs", "exe:ppexe:app/Main.hs", "p:ppexe:app/Main.hs",
                                  ":pkg:p:exe:ppexe:file:app/Main.hs"
                     ]
       ts @?= replicate 5 (TargetComponent "p-0.1" (CLibName LMainLibName) (FileTarget "P"))
           ++ replicate 5 (TargetComponent "q-0.1" (CLibName LMainLibName) (FileTarget "QQ"))
           ++ replicate 5 (TargetComponent "q-0.1" (CLibName LMainLibName) (FileTarget "Q"))
           ++ replicate 5 (TargetComponent "p-0.1" (CExeName "ppexe") (FileTarget ("app" </> "Main.hs")))
       -- Note there's a bit of an inconsistency here: for the single-part
       -- syntax the target has to point to a file that exists, whereas for
       -- all the other forms we don't require that.

    cleanProject testdir
  where
    testdir = "targets/simple"
    config  = mempty


testTargetSelectorBadSyntax :: Assertion
testTargetSelectorBadSyntax = do
    (_, _, _, localPackages, _) <- configureProject testdir config
    let targets = [ "foo bar",  " foo"
                  , "foo:", "foo::bar"
                  , "foo: ", "foo: :bar"
                  , "a:b:c:d:e:f", "a:b:c:d:e:f:g:h" ]
    Left errs <- readTargetSelectors localPackages Nothing targets
    zipWithM_ (@?=) errs (map TargetSelectorUnrecognised targets)
    cleanProject testdir
  where
    testdir = "targets/empty"
    config  = mempty


testTargetSelectorAmbiguous :: (String -> IO ()) -> Assertion
testTargetSelectorAmbiguous reportSubCase = do

    -- 'all' is ambiguous with packages and cwd components
    reportSubCase "ambiguous: all vs pkg"
    assertAmbiguous "all"
      [mkTargetPackage "all", mkTargetAllPackages]
      [mkpkg "all" []]

    reportSubCase "ambiguous: all vs cwd component"
    assertAmbiguous "all"
      [mkTargetComponent "other" (CExeName "all"), mkTargetAllPackages]
      [mkpkg "other" [mkexe "all"]]

    -- but 'all' is not ambiguous with non-cwd components, modules or files
    reportSubCase "unambiguous: all vs non-cwd comp, mod, file"
    assertUnambiguous "All"
      mkTargetAllPackages
      [ mkpkgAt "foo" [mkexe "All"] "foo"
      , mkpkg   "bar" [ mkexe "bar" `withModules` ["All"]
                      , mkexe "baz" `withCFiles` ["All"] ]
      ]

    -- filters 'libs', 'exes' etc are ambiguous with packages and
    -- local components
    reportSubCase "ambiguous: cwd-pkg filter vs pkg"
    assertAmbiguous "libs"
      [ mkTargetPackage "libs"
      , TargetPackage TargetImplicitCwd ["libs"] (Just LibKind) ]
      [mkpkg "libs" []]

    reportSubCase "ambiguous: filter vs cwd component"
    assertAmbiguous "exes"
      [ mkTargetComponent "other" (CExeName "exes")
      , TargetPackage TargetImplicitCwd ["other"] (Just ExeKind) ]
      [mkpkg "other" [mkexe "exes"]]

    -- but filters are not ambiguous with non-cwd components, modules or files
    reportSubCase "unambiguous: filter vs non-cwd comp, mod, file"
    assertUnambiguous "Libs"
      (TargetPackage TargetImplicitCwd ["bar"] (Just LibKind))
      [ mkpkgAt "foo" [mkexe "Libs"] "foo"
      , mkpkg   "bar" [ mkexe "bar" `withModules` ["Libs"]
                      , mkexe "baz" `withCFiles` ["Libs"] ]
      ]

    -- local components shadow packages and other components
    reportSubCase "unambiguous: cwd comp vs pkg, non-cwd comp"
    assertUnambiguous "foo"
      (mkTargetComponent "other" (CExeName "foo"))
      [ mkpkg   "other"  [mkexe "foo"]
      , mkpkgAt "other2" [mkexe "foo"] "other2" -- shadows non-local foo
      , mkpkg "foo" [] ]                        -- shadows package foo

    -- local components shadow modules and files
    reportSubCase "unambiguous: cwd comp vs module, file"
    assertUnambiguous "Foo"
      (mkTargetComponent "bar" (CExeName "Foo"))
      [ mkpkg "bar" [mkexe "Foo"]
      , mkpkg "other" [ mkexe "other"  `withModules` ["Foo"]
                      , mkexe "other2" `withCFiles`  ["Foo"] ]
      ]

    -- packages shadow non-local components
    reportSubCase "unambiguous: pkg vs non-cwd comp"
    assertUnambiguous "foo"
      (mkTargetPackage "foo")
      [ mkpkg "foo" []
      , mkpkgAt "other" [mkexe "foo"] "other" -- shadows non-local foo
      ]

    -- packages shadow modules and files
    reportSubCase "unambiguous: pkg vs module, file"
    assertUnambiguous "Foo"
      (mkTargetPackage "Foo")
      [ mkpkgAt "Foo" [] "foo"
      , mkpkg "other" [ mkexe "other"  `withModules` ["Foo"]
                      , mkexe "other2" `withCFiles`  ["Foo"] ]
      ]

    -- File target is ambiguous, part of multiple components
    reportSubCase "ambiguous: file in multiple comps"
    assertAmbiguous "Bar.hs"
      [ mkTargetFile "foo" (CExeName "bar")  "Bar"
      , mkTargetFile "foo" (CExeName "bar2") "Bar"
      ]
      [ mkpkg "foo" [ mkexe "bar"  `withModules` ["Bar"]
                    , mkexe "bar2" `withModules` ["Bar"] ]
      ]
    reportSubCase "ambiguous: file in multiple comps with path"
    assertAmbiguous ("src" </> "Bar.hs")
      [ mkTargetFile "foo" (CExeName "bar")  ("src" </> "Bar")
      , mkTargetFile "foo" (CExeName "bar2") ("src" </> "Bar")
      ]
      [ mkpkg "foo" [ mkexe "bar"  `withModules` ["Bar"] `withHsSrcDirs` ["src"]
                    , mkexe "bar2" `withModules` ["Bar"] `withHsSrcDirs` ["src"] ]
      ]

    -- non-exact case packages and components are ambiguous
    reportSubCase "ambiguous: non-exact-case pkg names"
    assertAmbiguous "Foo"
      [ mkTargetPackage "foo", mkTargetPackage "FOO" ]
      [ mkpkg "foo" [], mkpkg "FOO" [] ]
    reportSubCase "ambiguous: non-exact-case comp names"
    assertAmbiguous "Foo"
      [ mkTargetComponent "bar" (CExeName "foo")
      , mkTargetComponent "bar" (CExeName "FOO") ]
      [ mkpkg "bar" [mkexe "foo", mkexe "FOO"] ]

    -- exact-case Module or File over non-exact case package or component
    reportSubCase "unambiguous: module vs non-exact-case pkg, comp"
    assertUnambiguous "Baz"
      (mkTargetModule "other" (CExeName "other") "Baz")
      [ mkpkg "baz" [mkexe "BAZ"]
      , mkpkg "other" [ mkexe "other"  `withModules` ["Baz"] ]
      ]
    reportSubCase "unambiguous: file vs non-exact-case pkg, comp"
    assertUnambiguous "Baz"
      (mkTargetFile "other" (CExeName "other") "Baz")
      [ mkpkg "baz" [mkexe "BAZ"]
      , mkpkg "other" [ mkexe "other"  `withCFiles` ["Baz"] ]
      ]
  where
    assertAmbiguous :: String
                    -> [TargetSelector]
                    -> [SourcePackage (PackageLocation a)]
                    -> Assertion
    assertAmbiguous str tss pkgs = do
      res <- readTargetSelectorsWith
               fakeDirActions
               (map SpecificSourcePackage pkgs)
               Nothing
               [str]
      case res of
        Left [TargetSelectorAmbiguous _ tss'] ->
          sort (map snd tss') @?= sort tss
        _ -> assertFailure $ "expected Left [TargetSelectorAmbiguous _ _], "
                          ++ "got " ++ show res

    assertUnambiguous :: String
                      -> TargetSelector
                      -> [SourcePackage (PackageLocation a)]
                      -> Assertion
    assertUnambiguous str ts pkgs = do
      res <- readTargetSelectorsWith
               fakeDirActions
               (map SpecificSourcePackage pkgs)
               Nothing
               [str]
      case res of
        Right [ts'] -> ts' @?= ts
        _ -> assertFailure $ "expected Right [Target...], "
                          ++ "got " ++ show res

    fakeDirActions = TS.DirActions {
      TS.doesFileExist       = \_p -> return True,
      TS.doesDirectoryExist  = \_p -> return True,
      TS.canonicalizePath    = \p -> return ("/" </> p), -- FilePath.Unix.</> ?
      TS.getCurrentDirectory = return "/"
    }

    mkpkg :: String -> [Executable] -> SourcePackage (PackageLocation a)
    mkpkg pkgidstr exes = mkpkgAt pkgidstr exes ""

    mkpkgAt :: String -> [Executable] -> FilePath
            -> SourcePackage (PackageLocation a)
    mkpkgAt pkgidstr exes loc =
      SourcePackage {
        srcpkgPackageId = pkgid,
        srcpkgSource = LocalUnpackedPackage loc,
        srcpkgDescrOverride  = Nothing,
        srcpkgDescription = GenericPackageDescription {
          packageDescription = emptyPackageDescription { package = pkgid },
          gpdScannedVersion  = Nothing,
          genPackageFlags    = [],
          condLibrary        = Nothing,
          condSubLibraries   = [],
          condForeignLibs    = [],
          condExecutables    = [ ( exeName exe, CondNode exe [] [] )
                               | exe <- exes ],
          condTestSuites     = [],
          condBenchmarks     = []
        }
      }
      where
        pkgid = fromMaybe (error $ "failed to parse " ++ pkgidstr) $ simpleParse pkgidstr

    mkexe :: String -> Executable
    mkexe name = mempty { exeName = fromString name }

    withModules :: Executable -> [String] -> Executable
    withModules exe mods =
      exe { buildInfo = (buildInfo exe) { otherModules = map fromString mods } }

    withCFiles :: Executable -> [FilePath] -> Executable
    withCFiles exe files =
      exe { buildInfo = (buildInfo exe) { cSources = files } }

    withHsSrcDirs :: Executable -> [FilePath] -> Executable
    withHsSrcDirs exe srcDirs =
      exe { buildInfo = (buildInfo exe) { hsSourceDirs = map unsafeMakeSymbolicPath srcDirs }}


mkTargetPackage :: PackageId -> TargetSelector
mkTargetPackage pkgid =
    TargetPackage TargetExplicitNamed [pkgid] Nothing

mkTargetComponent :: PackageId -> ComponentName -> TargetSelector
mkTargetComponent pkgid cname =
    TargetComponent pkgid cname WholeComponent

mkTargetModule :: PackageId -> ComponentName -> ModuleName -> TargetSelector
mkTargetModule pkgid cname mname =
    TargetComponent pkgid cname (ModuleTarget mname)

mkTargetFile :: PackageId -> ComponentName -> String -> TargetSelector
mkTargetFile pkgid cname fname =
    TargetComponent pkgid cname (FileTarget fname)

mkTargetAllPackages :: TargetSelector
mkTargetAllPackages = TargetAllPackages Nothing

instance IsString PackageIdentifier where
    fromString pkgidstr = pkgid
      where pkgid = fromMaybe (error $ "fromString @PackageIdentifier " ++ show pkgidstr) $ simpleParse pkgidstr


testTargetSelectorNoCurrentPackage :: Assertion
testTargetSelectorNoCurrentPackage = do
    (_, _, _, localPackages, _) <- configureProject testdir config
    let readTargetSelectors' = readTargetSelectorsWith (dirActions testdir)
                                                       localPackages
                                                       Nothing
        targets = [ "libs",  ":cwd:libs"
                  , "flibs", ":cwd:flibs"
                  , "exes",  ":cwd:exes"
                  , "tests", ":cwd:tests"
                  , "benchmarks", ":cwd:benchmarks"]
    Left errs <- readTargetSelectors' targets
    zipWithM_ (@?=) errs
      [ TargetSelectorNoCurrentPackage ts
      | target <- targets
      , let ts = fromMaybe (error $ "failed to parse target string " ++ target) $ parseTargetString target
      ]
    cleanProject testdir
  where
    testdir = "targets/complex"
    config  = mempty


testTargetSelectorNoTargets :: Assertion
testTargetSelectorNoTargets = do
    (_, _, _, localPackages, _) <- configureProject testdir config
    Left errs <- readTargetSelectors localPackages Nothing []
    errs @?= [TargetSelectorNoTargetsInCwd True]
    cleanProject testdir
  where
    testdir = "targets/complex"
    config  = mempty


testTargetSelectorProjectEmpty :: Assertion
testTargetSelectorProjectEmpty = do
    (_, _, _, localPackages, _) <- configureProject testdir config
    Left errs <- readTargetSelectors localPackages Nothing []
    errs @?= [TargetSelectorNoTargetsInProject]
    cleanProject testdir
  where
    testdir = "targets/empty"
    config  = mempty


-- | Ensure we don't miss primary package and produce
-- TargetSelectorNoTargetsInCwd error due to symlink or
-- drive capitalisation mismatch when no targets are given
testTargetSelectorCanonicalizedPath :: Assertion
testTargetSelectorCanonicalizedPath = do
  (_, _, _, localPackages, _) <- configureProject testdir config
  cwd <- getCurrentDirectory
  let virtcwd = cwd </> basedir </> symlink
  -- Check that the symlink is there before running test as on Windows
  -- some versions/configurations of git won't pull down/create the symlink
  canRunTest <- doesDirectoryExist virtcwd
  when canRunTest (do
      let dirActions' = (dirActions symlink) { TS.getCurrentDirectory = return virtcwd }
      Right ts <- readTargetSelectorsWith dirActions' localPackages Nothing []
      ts @?= [TargetPackage TargetImplicitCwd ["p-0.1"] Nothing])
  cleanProject testdir
  where
    testdir = "targets/simple"
    symlink = "targets/symbolic-link-to-simple"
    config = mempty


testTargetProblemsCommon :: ProjectConfig -> Assertion
testTargetProblemsCommon config0 = do
    (_,elaboratedPlan,_) <- planProject testdir config

    let pkgIdMap :: Map.Map PackageName PackageId
        pkgIdMap = Map.fromList
                     [ (packageName p, packageId p)
                     | p <- InstallPlan.toList elaboratedPlan ]

        cases :: [( TargetSelector -> TargetProblem'
                  , TargetSelector
                  )]
        cases =
          [ -- Cannot resolve packages outside of the project
            ( \_ -> TargetProblemNoSuchPackage "foobar"
            , mkTargetPackage "foobar" )

            -- We cannot currently build components like testsuites or
            -- benchmarks from packages that are not local to the project
          , ( \_ -> TargetComponentNotProjectLocal
                      (pkgIdMap Map.! "filepath") (CTestName "filepath-tests")
                      WholeComponent
            , mkTargetComponent (pkgIdMap Map.! "filepath")
                                (CTestName "filepath-tests") )

            -- Components can be explicitly @buildable: False@
          , ( \_ -> TargetComponentNotBuildable "q-0.1" (CExeName "buildable-false") WholeComponent
            , mkTargetComponent "q-0.1" (CExeName "buildable-false") )

            -- Testsuites and benchmarks can be disabled by the solver if it
            -- cannot satisfy deps
          , ( \_ -> TargetOptionalStanzaDisabledBySolver "q-0.1" (CTestName "solver-disabled") WholeComponent
            , mkTargetComponent "q-0.1" (CTestName "solver-disabled") )

            -- Testsuites and benchmarks can be disabled explicitly by the
            -- user via config
          , ( \_ -> TargetOptionalStanzaDisabledByUser
                      "q-0.1" (CBenchName "user-disabled") WholeComponent
            , mkTargetComponent "q-0.1" (CBenchName "user-disabled") )

            -- An unknown package. The target selector resolution should only
            -- produce known packages, so this should not happen with the
            -- output from 'readTargetSelectors'.
          , ( \_ -> TargetProblemNoSuchPackage "foobar"
            , mkTargetPackage "foobar" )

            -- An unknown component of a known package. The target selector
            -- resolution should only produce known packages, so this should
            -- not happen with the output from 'readTargetSelectors'.
          , ( \_ -> TargetProblemNoSuchComponent "q-0.1" (CExeName "no-such")
            , mkTargetComponent "q-0.1" (CExeName "no-such") )
          ]
    assertTargetProblems
      elaboratedPlan
      CmdBuild.selectPackageTargets
      CmdBuild.selectComponentTarget
      cases
  where
    testdir = "targets/complex"
    config  = config0 {
      projectConfigLocalPackages = (projectConfigLocalPackages config0) {
        packageConfigBenchmarks = toFlag False
      }
    , projectConfigShared = (projectConfigShared config0) {
        projectConfigConstraints =
          [( UserConstraint (UserAnyQualifier "filepath") PackagePropertySource
           , ConstraintSourceUnknown )]
      }
    }


testTargetProblemsBuild :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsBuild config reportSubCase = do

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      CmdBuild.selectPackageTargets
      CmdBuild.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "all-disabled"
    assertProjectTargetProblems
      "targets/all-disabled"
      config {
        projectConfigLocalPackages = (projectConfigLocalPackages config) {
          packageConfigBenchmarks = toFlag False
        }
      }
      CmdBuild.selectPackageTargets
      CmdBuild.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CBenchName "user-disabled")
                                 TargetDisabledByUser True
               , AvailableTarget "p-0.1" (CTestName "solver-disabled")
                                 TargetDisabledBySolver True
               , AvailableTarget "p-0.1" (CExeName "buildable-false")
                                 TargetNotBuildable True
               , AvailableTarget "p-0.1" (CLibName LMainLibName)
                                 TargetNotBuildable True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "enabled component kinds"
    -- When we explicitly enable all the component kinds then selecting the
    -- whole package selects those component kinds too
    do (_,elaboratedPlan,_) <- planProject "targets/variety" config {
           projectConfigLocalPackages = (projectConfigLocalPackages config) {
             packageConfigTests      = toFlag True,
             packageConfigBenchmarks = toFlag True
           }
         }
       assertProjectDistinctTargets
         elaboratedPlan
         CmdBuild.selectPackageTargets
         CmdBuild.selectComponentTarget
         [ mkTargetPackage "p-0.1" ]
         [ ("p-0.1-inplace",             (CLibName LMainLibName))
         , ("p-0.1-inplace-a-benchmark", CBenchName "a-benchmark")
         , ("p-0.1-inplace-a-testsuite", CTestName  "a-testsuite")
         , ("p-0.1-inplace-an-exe",      CExeName   "an-exe")
         , ("p-0.1-inplace-libp",        CFLibName  "libp")
         ]

    reportSubCase "disabled component kinds"
    -- When we explicitly disable all the component kinds then selecting the
    -- whole package only selects the library, foreign lib and exes
    do (_,elaboratedPlan,_) <- planProject "targets/variety" config {
           projectConfigLocalPackages = (projectConfigLocalPackages config) {
             packageConfigTests      = toFlag False,
             packageConfigBenchmarks = toFlag False
           }
         }
       assertProjectDistinctTargets
         elaboratedPlan
         CmdBuild.selectPackageTargets
         CmdBuild.selectComponentTarget
         [ mkTargetPackage "p-0.1" ]
         [ ("p-0.1-inplace",        (CLibName LMainLibName))
         , ("p-0.1-inplace-an-exe", CExeName  "an-exe")
         , ("p-0.1-inplace-libp",   CFLibName "libp")
         ]

    reportSubCase "requested component kinds"
    -- When we selecting the package with an explicit filter then we get those
    -- components even though we did not explicitly enable tests/benchmarks
    do (_,elaboratedPlan,_) <- planProject "targets/variety" config
       assertProjectDistinctTargets
         elaboratedPlan
         CmdBuild.selectPackageTargets
         CmdBuild.selectComponentTarget
         [ TargetPackage TargetExplicitNamed ["p-0.1"] (Just TestKind)
         , TargetPackage TargetExplicitNamed ["p-0.1"] (Just BenchKind)
         ]
         [ ("p-0.1-inplace-a-benchmark", CBenchName "a-benchmark")
         , ("p-0.1-inplace-a-testsuite", CTestName  "a-testsuite")
         ]


testTargetProblemsRepl :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsRepl config reportSubCase = do

    reportSubCase "multiple-libs"
    assertProjectTargetProblems
      "targets/multiple-libs" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( flip CmdRepl.matchesMultipleProblem
               [ AvailableTarget "p-0.1" (CLibName LMainLibName)
                   (TargetBuildable () TargetRequestedByDefault) True
               , AvailableTarget "q-0.1" (CLibName LMainLibName)
                   (TargetBuildable () TargetRequestedByDefault) True
               ]
        , mkTargetAllPackages )
      ]

    reportSubCase "multiple-exes"
    assertProjectTargetProblems
      "targets/multiple-exes" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( flip CmdRepl.matchesMultipleProblem
               [ AvailableTarget "p-0.1" (CExeName "p2")
                   (TargetBuildable () TargetRequestedByDefault) True
               , AvailableTarget "p-0.1" (CExeName "p1")
                   (TargetBuildable () TargetRequestedByDefault) True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "multiple-tests"
    assertProjectTargetProblems
      "targets/multiple-tests" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( flip CmdRepl.matchesMultipleProblem
               [ AvailableTarget "p-0.1" (CTestName "p2")
                   (TargetBuildable () TargetNotRequestedByDefault) True
               , AvailableTarget "p-0.1" (CTestName "p1")
                   (TargetBuildable () TargetNotRequestedByDefault) True
               ]
        , TargetPackage TargetExplicitNamed ["p-0.1"] (Just TestKind) )
      ]

    reportSubCase "multiple targets"
    do (_,elaboratedPlan,_) <- planProject "targets/multiple-exes" config
       assertProjectDistinctTargets
         elaboratedPlan
         CmdRepl.selectPackageTargets
         CmdRepl.selectComponentTarget
         [ mkTargetComponent "p-0.1" (CExeName "p1")
         , mkTargetComponent "p-0.1" (CExeName "p2")
         ]
         [ ("p-0.1-inplace-p1", CExeName "p1")
         , ("p-0.1-inplace-p2", CExeName "p2")
         ]

    reportSubCase "libs-disabled"
    assertProjectTargetProblems
      "targets/libs-disabled" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CLibName LMainLibName) TargetNotBuildable True ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "exes-disabled"
    assertProjectTargetProblems
      "targets/exes-disabled" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CExeName "p") TargetNotBuildable True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "test-only"
    assertProjectTargetProblems
      "targets/test-only" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CTestName "pexe")
                   (TargetBuildable () TargetNotRequestedByDefault) True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      CmdRepl.selectPackageTargets
      CmdRepl.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "requested component kinds"
    do (_,elaboratedPlan,_) <- planProject "targets/variety" config
       -- by default we only get the lib
       assertProjectDistinctTargets
         elaboratedPlan
         CmdRepl.selectPackageTargets
         CmdRepl.selectComponentTarget
         [ TargetPackage TargetExplicitNamed ["p-0.1"] Nothing ]
         [ ("p-0.1-inplace", (CLibName LMainLibName)) ]
       -- When we select the package with an explicit filter then we get those
       -- components even though we did not explicitly enable tests/benchmarks
       assertProjectDistinctTargets
         elaboratedPlan
         CmdRepl.selectPackageTargets
         CmdRepl.selectComponentTarget
         [ TargetPackage TargetExplicitNamed ["p-0.1"] (Just TestKind) ]
         [ ("p-0.1-inplace-a-testsuite", CTestName  "a-testsuite") ]
       assertProjectDistinctTargets
         elaboratedPlan
         CmdRepl.selectPackageTargets
         CmdRepl.selectComponentTarget
         [ TargetPackage TargetExplicitNamed ["p-0.1"] (Just BenchKind) ]
         [ ("p-0.1-inplace-a-benchmark", CBenchName "a-benchmark") ]

testTargetProblemsListBin :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsListBin config reportSubCase = do
    reportSubCase "one-of-each"
    do (_,elaboratedPlan,_) <- planProject "targets/one-of-each" config
       assertProjectDistinctTargets
         elaboratedPlan
         CmdListBin.selectPackageTargets
         CmdListBin.selectComponentTarget
         [ TargetPackage TargetExplicitNamed ["p-0.1"] Nothing
         ]
         [ ("p-0.1-inplace-p1",      CExeName   "p1")
         ]

    reportSubCase "multiple-exes"
    assertProjectTargetProblems
      "targets/multiple-exes" config
      CmdListBin.selectPackageTargets
      CmdListBin.selectComponentTarget
      [ ( flip CmdListBin.matchesMultipleProblem
               [ AvailableTarget "p-0.1" (CExeName "p2")
                   (TargetBuildable () TargetRequestedByDefault) True
               , AvailableTarget "p-0.1" (CExeName "p1")
                   (TargetBuildable () TargetRequestedByDefault) True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "multiple targets"
    do (_,elaboratedPlan,_) <- planProject "targets/multiple-exes" config
       assertProjectDistinctTargets
         elaboratedPlan
         CmdListBin.selectPackageTargets
         CmdListBin.selectComponentTarget
         [ mkTargetComponent "p-0.1" (CExeName "p1")
         , mkTargetComponent "p-0.1" (CExeName "p2")
         ]
         [ ("p-0.1-inplace-p1", CExeName "p1")
         , ("p-0.1-inplace-p2", CExeName "p2")
         ]

    reportSubCase "exes-disabled"
    assertProjectTargetProblems
      "targets/exes-disabled" config
      CmdListBin.selectPackageTargets
      CmdListBin.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CExeName "p") TargetNotBuildable True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      CmdListBin.selectPackageTargets
      CmdListBin.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "lib-only"
    assertProjectTargetProblems
      "targets/lib-only" config
      CmdListBin.selectPackageTargets
      CmdListBin.selectComponentTarget
      [ (CmdListBin.noComponentsProblem, mkTargetPackage "p-0.1" )
      ]

testTargetProblemsRun :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsRun config reportSubCase = do
    reportSubCase "one-of-each"
    do (_,elaboratedPlan,_) <- planProject "targets/one-of-each" config
       assertProjectDistinctTargets
         elaboratedPlan
         CmdRun.selectPackageTargets
         CmdRun.selectComponentTarget
         [ TargetPackage TargetExplicitNamed ["p-0.1"] Nothing
         ]
         [ ("p-0.1-inplace-p1",      CExeName   "p1")
         ]

    reportSubCase "multiple-exes"
    assertProjectTargetProblems
      "targets/multiple-exes" config
      CmdRun.selectPackageTargets
      CmdRun.selectComponentTarget
      [ ( flip CmdRun.matchesMultipleProblem
               [ AvailableTarget "p-0.1" (CExeName "p2")
                   (TargetBuildable () TargetRequestedByDefault) True
               , AvailableTarget "p-0.1" (CExeName "p1")
                   (TargetBuildable () TargetRequestedByDefault) True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "multiple targets"
    do (_,elaboratedPlan,_) <- planProject "targets/multiple-exes" config
       assertProjectDistinctTargets
         elaboratedPlan
         CmdRun.selectPackageTargets
         CmdRun.selectComponentTarget
         [ mkTargetComponent "p-0.1" (CExeName "p1")
         , mkTargetComponent "p-0.1" (CExeName "p2")
         ]
         [ ("p-0.1-inplace-p1", CExeName "p1")
         , ("p-0.1-inplace-p2", CExeName "p2")
         ]

    reportSubCase "exes-disabled"
    assertProjectTargetProblems
      "targets/exes-disabled" config
      CmdRun.selectPackageTargets
      CmdRun.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CExeName "p") TargetNotBuildable True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      CmdRun.selectPackageTargets
      CmdRun.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "lib-only"
    assertProjectTargetProblems
      "targets/lib-only" config
      CmdRun.selectPackageTargets
      CmdRun.selectComponentTarget
      [ (CmdRun.noExesProblem, mkTargetPackage "p-0.1" )
      ]


testTargetProblemsTest :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsTest config reportSubCase = do

    reportSubCase "disabled by config"
    assertProjectTargetProblems
      "targets/tests-disabled"
      config {
        projectConfigLocalPackages = (projectConfigLocalPackages config) {
          packageConfigTests = toFlag False
        }
      }
      CmdTest.selectPackageTargets
      CmdTest.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CTestName "user-disabled")
                                 TargetDisabledByUser True
               , AvailableTarget "p-0.1" (CTestName "solver-disabled")
                                 TargetDisabledByUser True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "disabled by solver & buildable false"
    assertProjectTargetProblems
      "targets/tests-disabled"
      config
      CmdTest.selectPackageTargets
      CmdTest.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CTestName "user-disabled")
                                 TargetDisabledBySolver True
               , AvailableTarget "p-0.1" (CTestName "solver-disabled")
                                 TargetDisabledBySolver True
               ]
        , mkTargetPackage "p-0.1" )

      , ( flip TargetProblemNoneEnabled
               [ AvailableTarget "q-0.1" (CTestName "buildable-false")
                                 TargetNotBuildable True
               ]
        , mkTargetPackage "q-0.1" )
      ]

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      CmdTest.selectPackageTargets
      CmdTest.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "no tests"
    assertProjectTargetProblems
      "targets/simple"
      config
      CmdTest.selectPackageTargets
      CmdTest.selectComponentTarget
      [ ( CmdTest.noTestsProblem, mkTargetPackage "p-0.1" )
      , ( CmdTest.noTestsProblem, mkTargetPackage "q-0.1" )
      ]

    reportSubCase "not a test"
    assertProjectTargetProblems
      "targets/variety"
      config
      CmdTest.selectPackageTargets
      CmdTest.selectComponentTarget $
      [ ( const (CmdTest.notTestProblem
                  "p-0.1" (CLibName LMainLibName))
        , mkTargetComponent "p-0.1" (CLibName LMainLibName) )

      , ( const (CmdTest.notTestProblem
                  "p-0.1" (CExeName "an-exe"))
        , mkTargetComponent "p-0.1" (CExeName "an-exe") )

      , ( const (CmdTest.notTestProblem
                  "p-0.1" (CFLibName "libp"))
        , mkTargetComponent "p-0.1" (CFLibName "libp") )

      , ( const (CmdTest.notTestProblem
                  "p-0.1" (CBenchName "a-benchmark"))
        , mkTargetComponent "p-0.1" (CBenchName "a-benchmark") )
      ] ++
      [ ( const (CmdTest.isSubComponentProblem
                          "p-0.1" cname (ModuleTarget modname))
        , mkTargetModule "p-0.1" cname modname )
      | (cname, modname) <- [ (CTestName  "a-testsuite", "TestModule")
                            , (CBenchName "a-benchmark", "BenchModule")
                            , (CExeName   "an-exe",      "ExeModule")
                            , ((CLibName LMainLibName),                 "P")
                            ]
      ] ++
      [ ( const (CmdTest.isSubComponentProblem
                          "p-0.1" cname (FileTarget fname))
        , mkTargetFile "p-0.1" cname fname)
      | (cname, fname) <- [ (CTestName  "a-testsuite", "Test.hs")
                          , (CBenchName "a-benchmark", "Bench.hs")
                          , (CExeName   "an-exe",      "Main.hs")
                          ]
      ]


testTargetProblemsBench :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsBench config reportSubCase = do

    reportSubCase "disabled by config"
    assertProjectTargetProblems
      "targets/benchmarks-disabled"
      config {
        projectConfigLocalPackages = (projectConfigLocalPackages config) {
          packageConfigBenchmarks = toFlag False
        }
      }
      CmdBench.selectPackageTargets
      CmdBench.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CBenchName "user-disabled")
                                 TargetDisabledByUser True
               , AvailableTarget "p-0.1" (CBenchName "solver-disabled")
                                 TargetDisabledByUser True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "disabled by solver & buildable false"
    assertProjectTargetProblems
      "targets/benchmarks-disabled"
      config
      CmdBench.selectPackageTargets
      CmdBench.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CBenchName "user-disabled")
                                 TargetDisabledBySolver True
               , AvailableTarget "p-0.1" (CBenchName "solver-disabled")
                                 TargetDisabledBySolver True
               ]
        , mkTargetPackage "p-0.1" )

      , ( flip TargetProblemNoneEnabled
               [ AvailableTarget "q-0.1" (CBenchName "buildable-false")
                                 TargetNotBuildable True
               ]
        , mkTargetPackage "q-0.1" )
      ]

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      CmdBench.selectPackageTargets
      CmdBench.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "no benchmarks"
    assertProjectTargetProblems
      "targets/simple"
      config
      CmdBench.selectPackageTargets
      CmdBench.selectComponentTarget
      [ ( CmdBench.noBenchmarksProblem, mkTargetPackage "p-0.1" )
      , ( CmdBench.noBenchmarksProblem, mkTargetPackage "q-0.1" )
      ]

    reportSubCase "not a benchmark"
    assertProjectTargetProblems
      "targets/variety"
      config
      CmdBench.selectPackageTargets
      CmdBench.selectComponentTarget $
      [ ( const (CmdBench.componentNotBenchmarkProblem
                  "p-0.1" (CLibName LMainLibName))
        , mkTargetComponent "p-0.1" (CLibName LMainLibName) )

      , ( const (CmdBench.componentNotBenchmarkProblem
                  "p-0.1" (CExeName "an-exe"))
        , mkTargetComponent "p-0.1" (CExeName "an-exe") )

      , ( const (CmdBench.componentNotBenchmarkProblem
                  "p-0.1" (CFLibName "libp"))
        , mkTargetComponent "p-0.1" (CFLibName "libp") )

      , ( const (CmdBench.componentNotBenchmarkProblem
                  "p-0.1" (CTestName "a-testsuite"))
        , mkTargetComponent "p-0.1" (CTestName "a-testsuite") )
      ] ++
      [ ( const (CmdBench.isSubComponentProblem
                          "p-0.1" cname (ModuleTarget modname))
        , mkTargetModule "p-0.1" cname modname )
      | (cname, modname) <- [ (CTestName  "a-testsuite", "TestModule")
                            , (CBenchName "a-benchmark", "BenchModule")
                            , (CExeName   "an-exe",      "ExeModule")
                            , ((CLibName LMainLibName),                 "P")
                            ]
      ] ++
      [ ( const (CmdBench.isSubComponentProblem
                          "p-0.1" cname (FileTarget fname))
        , mkTargetFile "p-0.1" cname fname)
      | (cname, fname) <- [ (CTestName  "a-testsuite", "Test.hs")
                          , (CBenchName "a-benchmark", "Bench.hs")
                          , (CExeName   "an-exe",      "Main.hs")
                          ]
      ]


testTargetProblemsHaddock :: ProjectConfig -> (String -> IO ()) -> Assertion
testTargetProblemsHaddock config reportSubCase = do

    reportSubCase "all-disabled"
    assertProjectTargetProblems
      "targets/all-disabled"
      config
      (let haddockFlags = mkHaddockFlags False True True False
        in CmdHaddock.selectPackageTargets haddockFlags)
      CmdHaddock.selectComponentTarget
      [ ( flip TargetProblemNoneEnabled
               [ AvailableTarget "p-0.1" (CBenchName "user-disabled")
                                 TargetDisabledByUser True
               , AvailableTarget "p-0.1" (CTestName "solver-disabled")
                                 TargetDisabledBySolver True
               , AvailableTarget "p-0.1" (CExeName "buildable-false")
                                 TargetNotBuildable True
               , AvailableTarget "p-0.1" (CLibName LMainLibName)
                                 TargetNotBuildable True
               ]
        , mkTargetPackage "p-0.1" )
      ]

    reportSubCase "empty-pkg"
    assertProjectTargetProblems
      "targets/empty-pkg" config
      (let haddockFlags = mkHaddockFlags False False False False
        in CmdHaddock.selectPackageTargets haddockFlags)
      CmdHaddock.selectComponentTarget
      [ ( TargetProblemNoTargets, mkTargetPackage "p-0.1" )
      ]

    reportSubCase "enabled component kinds"
    -- When we explicitly enable all the component kinds then selecting the
    -- whole package selects those component kinds too
    (_,elaboratedPlan,_) <- planProject "targets/variety" config
    let haddockFlags = mkHaddockFlags True True True True
     in assertProjectDistinctTargets
          elaboratedPlan
          (CmdHaddock.selectPackageTargets haddockFlags)
          CmdHaddock.selectComponentTarget
          [ mkTargetPackage "p-0.1" ]
          [ ("p-0.1-inplace",             (CLibName LMainLibName))
          , ("p-0.1-inplace-a-benchmark", CBenchName "a-benchmark")
          , ("p-0.1-inplace-a-testsuite", CTestName  "a-testsuite")
          , ("p-0.1-inplace-an-exe",      CExeName   "an-exe")
          , ("p-0.1-inplace-libp",        CFLibName  "libp")
          ]

    reportSubCase "disabled component kinds"
    -- When we explicitly disable all the component kinds then selecting the
    -- whole package only selects the library
    let haddockFlags = mkHaddockFlags False False False False
     in assertProjectDistinctTargets
          elaboratedPlan
          (CmdHaddock.selectPackageTargets haddockFlags)
          CmdHaddock.selectComponentTarget
          [ mkTargetPackage "p-0.1" ]
          [ ("p-0.1-inplace", (CLibName LMainLibName)) ]

    reportSubCase "requested component kinds"
    -- When we selecting the package with an explicit filter then it does not
    -- matter if the config was to disable all the component kinds
    let haddockFlags = mkHaddockFlags False False False False
     in assertProjectDistinctTargets
          elaboratedPlan
          (CmdHaddock.selectPackageTargets haddockFlags)
          CmdHaddock.selectComponentTarget
          [ TargetPackage TargetExplicitNamed ["p-0.1"] (Just FLibKind)
          , TargetPackage TargetExplicitNamed ["p-0.1"] (Just ExeKind)
          , TargetPackage TargetExplicitNamed ["p-0.1"] (Just TestKind)
          , TargetPackage TargetExplicitNamed ["p-0.1"] (Just BenchKind)
          ]
          [ ("p-0.1-inplace-a-benchmark", CBenchName "a-benchmark")
          , ("p-0.1-inplace-a-testsuite", CTestName  "a-testsuite")
          , ("p-0.1-inplace-an-exe",      CExeName   "an-exe")
          , ("p-0.1-inplace-libp",        CFLibName  "libp")
          ]
  where
    mkHaddockFlags flib exe test bench =
      defaultHaddockFlags {
        haddockForeignLibs = toFlag flib,
        haddockExecutables = toFlag exe,
        haddockTestSuites  = toFlag test,
        haddockBenchmarks  = toFlag bench
      }

assertProjectDistinctTargets
  :: forall err. (Eq err, Show err) =>
     ElaboratedInstallPlan
  -> (forall k. TargetSelector -> [AvailableTarget k] -> Either (TargetProblem err) [k])
  -> (forall k. SubComponentTarget ->  AvailableTarget k  -> Either (TargetProblem err)  k )
  -> [TargetSelector]
  -> [(UnitId, ComponentName)]
  -> Assertion
assertProjectDistinctTargets elaboratedPlan
                             selectPackageTargets
                             selectComponentTarget
                             targetSelectors
                             expectedTargets
  | Right targets <- results
  = distinctTargetComponents targets @?= Set.fromList expectedTargets

  | otherwise
  = assertFailure $ "assertProjectDistinctTargets: expected "
                 ++ "(Right targets) but got " ++ show results
  where
    results = resolveTargets
                selectPackageTargets
                selectComponentTarget
                elaboratedPlan
                Nothing
                targetSelectors


assertProjectTargetProblems
  :: forall err. (Eq err, Show err) =>
     FilePath -> ProjectConfig
  -> (forall k. TargetSelector
             -> [AvailableTarget k]
             -> Either (TargetProblem err) [k])
  -> (forall k. SubComponentTarget
             -> AvailableTarget k
             -> Either (TargetProblem err) k )
  -> [(TargetSelector -> TargetProblem err, TargetSelector)]
  -> Assertion
assertProjectTargetProblems testdir config
                            selectPackageTargets
                            selectComponentTarget
                            cases = do
    (_,elaboratedPlan,_) <- planProject testdir config
    assertTargetProblems
      elaboratedPlan
      selectPackageTargets
      selectComponentTarget
      cases


assertTargetProblems
  :: forall err. (Eq err, Show err) =>
     ElaboratedInstallPlan
  -> (forall k. TargetSelector -> [AvailableTarget k] -> Either (TargetProblem err) [k])
  -> (forall k. SubComponentTarget ->  AvailableTarget k  -> Either (TargetProblem err)  k )
  -> [(TargetSelector -> TargetProblem err, TargetSelector)]
  -> Assertion
assertTargetProblems elaboratedPlan selectPackageTargets selectComponentTarget =
    mapM_ (uncurry assertTargetProblem)
  where
    assertTargetProblem expected targetSelector =
      let res = resolveTargets selectPackageTargets selectComponentTarget
                               elaboratedPlan Nothing
                               [targetSelector] in
      case res of
        Left [problem] ->
          problem @?= expected targetSelector

        unexpected ->
          assertFailure $ "expected resolveTargets result: (Left [problem]) "
                       ++ "but got: " ++ show unexpected


testExceptionInFindingPackage :: ProjectConfig -> Assertion
testExceptionInFindingPackage config = do
    BadPackageLocations _ locs <- expectException "BadPackageLocations" $
      void $ planProject testdir config
    case locs of
      [BadLocGlobEmptyMatch "./*.cabal"] -> return ()
      _ -> assertFailure "expected BadLocGlobEmptyMatch"
    cleanProject testdir
  where
    testdir = "exception/no-pkg"


testExceptionInFindingPackage2 :: ProjectConfig -> Assertion
testExceptionInFindingPackage2 config = do
    BadPackageLocations _ locs <- expectException "BadPackageLocations" $
      void $ planProject testdir config
    case locs of
      [BadPackageLocationFile (BadLocDirNoCabalFile ".")] -> return ()
      _ -> assertFailure $ "expected BadLocDirNoCabalFile, got " ++ show locs
    cleanProject testdir
  where
    testdir = "exception/no-pkg2"


testExceptionInProjectConfig :: ProjectConfig -> Assertion
testExceptionInProjectConfig config = do
    BadPerPackageCompilerPaths ps <- expectException "BadPerPackageCompilerPaths" $
      void $ planProject testdir config
    case ps of
      [(pn,"ghc")] | "foo" == pn -> return ()
      _ -> assertFailure $ "expected (PackageName \"foo\",\"ghc\"), got "
                        ++ show ps
    cleanProject testdir
  where
    testdir = "exception/bad-config"


testExceptionInConfigureStep :: ProjectConfig -> Assertion
testExceptionInConfigureStep config = do
    (plan, res) <- executePlan =<< planProject testdir config
    (_pkga1, failure) <- expectPackageFailed plan res pkgidA1
    case buildFailureReason failure of
      ConfigureFailed _ -> return ()
      _ -> assertFailure $ "expected ConfigureFailed, got " ++ show failure
    cleanProject testdir
  where
    testdir = "exception/configure"
    pkgidA1 = PackageIdentifier "a" (mkVersion [1])


testExceptionInBuildStep :: ProjectConfig -> Assertion
testExceptionInBuildStep config = do
    (plan, res) <- executePlan =<< planProject testdir config
    (_pkga1, failure) <- expectPackageFailed plan res pkgidA1
    expectBuildFailed failure
  where
    testdir = "exception/build"
    pkgidA1 = PackageIdentifier "a" (mkVersion [1])

testSetupScriptStyles :: ProjectConfig -> (String -> IO ()) -> Assertion
testSetupScriptStyles config reportSubCase = do

  reportSubCase (show SetupCustomExplicitDeps)

  plan0@(_,_,sharedConfig) <- planProject testdir1 config

  let isOSX (Platform _ OSX) = True
      isOSX _ = False
  -- Skip the Custom tests when the shipped Cabal library is buggy
  unless (isOSX (pkgConfigPlatform sharedConfig)
       && compilerVersion (pkgConfigCompiler sharedConfig) < mkVersion [7,10]) $ do

    (plan1, res1) <- executePlan plan0
    pkg1          <- expectPackageInstalled plan1 res1 pkgidA
    elabSetupScriptStyle pkg1 @?= SetupCustomExplicitDeps
    hasDefaultSetupDeps pkg1 @?= Just False
    marker1 <- readFile (basedir </> testdir1 </> "marker")
    marker1 @?= "ok"
    removeFile (basedir </> testdir1 </> "marker")

    -- implicit deps implies 'Cabal < 2' which conflicts w/ GHC 8.2 or later
    when (compilerVersion (pkgConfigCompiler sharedConfig) < mkVersion [8,2]) $ do
      reportSubCase (show SetupCustomImplicitDeps)
      (plan2, res2) <- executePlan =<< planProject testdir2 config
      pkg2          <- expectPackageInstalled plan2 res2 pkgidA
      elabSetupScriptStyle pkg2 @?= SetupCustomImplicitDeps
      hasDefaultSetupDeps pkg2 @?= Just True
      marker2 <- readFile (basedir </> testdir2 </> "marker")
      marker2 @?= "ok"
      removeFile (basedir </> testdir2 </> "marker")

    reportSubCase (show SetupNonCustomInternalLib)
    (plan3, res3) <- executePlan =<< planProject testdir3 config
    pkg3          <- expectPackageInstalled plan3 res3 pkgidA
    elabSetupScriptStyle pkg3 @?= SetupNonCustomInternalLib
{-
    --TODO: the SetupNonCustomExternalLib case is hard to test since it
    -- requires a version of Cabal that's later than the one we're testing
    -- e.g. needs a .cabal file that specifies cabal-version: >= 2.0
    -- and a corresponding Cabal package that we can use to try and build a
    -- default Setup.hs.
    reportSubCase (show SetupNonCustomExternalLib)
    (plan4, res4) <- executePlan =<< planProject testdir4 config
    pkg4          <- expectPackageInstalled plan4 res4 pkgidA
    pkgSetupScriptStyle pkg4 @?= SetupNonCustomExternalLib
-}
  where
    testdir1 = "build/setup-custom1"
    testdir2 = "build/setup-custom2"
    testdir3 = "build/setup-simple"
    pkgidA   = PackageIdentifier "a" (mkVersion [0,1])
    -- The solver fills in default setup deps explicitly, but marks them as such
    hasDefaultSetupDeps = fmap defaultSetupDepends
                        . setupBuildInfo . elabPkgDescription

-- | Test the behaviour with and without @--keep-going@
--
testBuildKeepGoing :: ProjectConfig -> Assertion
testBuildKeepGoing config = do
    -- P is expected to fail, Q does not depend on P but without
    -- parallel build and without keep-going then we don't build Q yet.
    (plan1, res1) <- executePlan =<< planProject testdir (config `mappend` keepGoing False)
    (_, failure1) <- expectPackageFailed plan1 res1 "p-0.1"
    expectBuildFailed failure1
    _ <- expectPackageConfigured plan1 res1 "q-0.1"

    -- With keep-going then we should go on to successfully build Q
    (plan2, res2) <- executePlan
                 =<< planProject testdir (config `mappend` keepGoing True)
    (_, failure2) <- expectPackageFailed plan2 res2 "p-0.1"
    expectBuildFailed failure2
    _ <- expectPackageInstalled plan2 res2 "q-0.1"
    return ()
  where
    testdir = "build/keep-going"
    keepGoing kg =
      mempty {
        projectConfigBuildOnly = mempty {
          projectConfigKeepGoing = toFlag kg
        }
      }

-- | Test we can successfully build packages from local tarball files.
--
testBuildLocalTarball :: ProjectConfig -> Assertion
testBuildLocalTarball config = do
    -- P is a tarball package, Q is a local dir package that depends on it.
    (plan, res) <- executePlan =<< planProject testdir config
    _ <- expectPackageInstalled plan res "p-0.1"
    _ <- expectPackageInstalled plan res "q-0.1"
    return ()
  where
    testdir = "build/local-tarball"

-- | See <https://github.com/haskell/cabal/issues/3324>
--
-- This test just doesn't seem to work on Windows,
-- due filesystem woes.
--
testRegressionIssue3324 :: ProjectConfig -> Assertion
testRegressionIssue3324 config = when (buildOS /= Windows) $ do
    -- expected failure first time due to missing dep
    (plan1, res1) <- executePlan =<< planProject testdir config
    (_pkgq, failure) <- expectPackageFailed plan1 res1 "q-0.1"
    expectBuildFailed failure

    -- add the missing dep, now it should work
    let qcabal  = basedir </> testdir </> "q" </> "q.cabal"
    withFileFinallyRestore qcabal $ do
      tryFewTimes $ BS.appendFile qcabal ("  build-depends: p\n")
      (plan2, res2) <- executePlan =<< planProject testdir config
      _ <- expectPackageInstalled plan2 res2 "p-0.1"
      _ <- expectPackageInstalled plan2 res2 "q-0.1"
      return ()
  where
    testdir = "regression/3324"

-- | Test global program options are propagated correctly
-- from ProjectConfig to ElaboratedInstallPlan
testProgramOptionsAll :: ProjectConfig -> Assertion
testProgramOptionsAll config0 = do
    -- P is a tarball package, Q is a local dir package that depends on it.
    (_, elaboratedPlan, _) <- planProject testdir config
    let packages = filterConfiguredPackages $ InstallPlan.toList elaboratedPlan

    assertEqual "q"
                (Just [ghcFlag])
                (getProgArgs packages "q")
    assertEqual "p"
                (Just [ghcFlag])
                (getProgArgs packages "p")
  where
    testdir = "regression/program-options"
    programArgs = MapMappend (Map.fromList [("ghc", [ghcFlag])])
    ghcFlag = "-fno-full-laziness"

    -- Insert flag into global config
    config = config0 {
      projectConfigAllPackages = (projectConfigAllPackages config0) {
        packageConfigProgramArgs = programArgs
      }
    }

-- | Test local program options are propagated correctly
-- from ProjectConfig to ElaboratedInstallPlan
testProgramOptionsLocal :: ProjectConfig -> Assertion
testProgramOptionsLocal config0 = do
    (_, elaboratedPlan, _) <- planProject testdir config
    let localPackages = filterConfiguredPackages $ InstallPlan.toList elaboratedPlan

    assertEqual "q"
                (Just [ghcFlag])
                (getProgArgs localPackages "q")
    assertEqual "p"
                Nothing
                (getProgArgs localPackages "p")
  where
    testdir = "regression/program-options"
    programArgs = MapMappend (Map.fromList [("ghc", [ghcFlag])])
    ghcFlag = "-fno-full-laziness"

    -- Insert flag into local config
    config = config0 {
      projectConfigLocalPackages = (projectConfigLocalPackages config0) {
        packageConfigProgramArgs = programArgs
      }
    }

-- | Test package specific program options are propagated correctly
-- from ProjectConfig to ElaboratedInstallPlan
testProgramOptionsSpecific :: ProjectConfig -> Assertion
testProgramOptionsSpecific config0 = do
    (_, elaboratedPlan, _) <- planProject testdir config
    let packages = filterConfiguredPackages $ InstallPlan.toList elaboratedPlan

    assertEqual "q"
                (Nothing)
                (getProgArgs packages "q")
    assertEqual "p"
                (Just [ghcFlag])
                (getProgArgs packages "p")
  where
    testdir = "regression/program-options"
    programArgs = MapMappend (Map.fromList [("ghc", [ghcFlag])])
    ghcFlag = "-fno-full-laziness"

    -- Insert flag into package "p" config
    config = config0 {
        projectConfigSpecificPackage = MapMappend (Map.fromList [(mkPackageName "p", configArgs)])
    }
    configArgs = mempty {
        packageConfigProgramArgs = programArgs
    }

filterConfiguredPackages :: [ElaboratedPlanPackage] -> [ElaboratedConfiguredPackage]
filterConfiguredPackages [] = []
filterConfiguredPackages (InstallPlan.PreExisting _    : pkgs) = filterConfiguredPackages pkgs
filterConfiguredPackages (InstallPlan.Installed   elab : pkgs) = elab : filterConfiguredPackages pkgs
filterConfiguredPackages (InstallPlan.Configured  elab : pkgs) = elab : filterConfiguredPackages pkgs

getProgArgs :: [ElaboratedConfiguredPackage] -> String -> Maybe [String]
getProgArgs [] _ = Nothing
getProgArgs (elab : pkgs) name
    | pkgName (elabPkgSourceId elab) == mkPackageName name
        = Map.lookup "ghc" (elabProgramArgs elab)
    | otherwise
        = getProgArgs pkgs name

---------------------------------
-- Test utils to plan and build
--

basedir :: FilePath
basedir = "tests" </> "IntegrationTests2"

dirActions :: FilePath -> TS.DirActions IO
dirActions testdir =
    defaultDirActions {
      TS.doesFileExist       = \p ->
        TS.doesFileExist defaultDirActions (virtcwd </> p),

      TS.doesDirectoryExist  = \p ->
        TS.doesDirectoryExist defaultDirActions (virtcwd </> p),

      TS.canonicalizePath    = \p ->
        TS.canonicalizePath defaultDirActions (virtcwd </> p),

      TS.getCurrentDirectory =
        TS.canonicalizePath defaultDirActions virtcwd
    }
  where
    virtcwd = basedir </> testdir

type ProjDetails = (DistDirLayout,
                    CabalDirLayout,
                    ProjectConfig,
                    [PackageSpecifier UnresolvedSourcePackage],
                    BuildTimeSettings)

configureProject :: FilePath -> ProjectConfig -> IO ProjDetails
configureProject testdir cliConfig = do
    cabalDirLayout <- defaultCabalDirLayout

    projectRootDir <- canonicalizePath (basedir </> testdir)
    isexplict      <- doesFileExist (projectRootDir </> "cabal.project")
    let projectRoot
          | isexplict = ProjectRootExplicit projectRootDir
                                           (projectRootDir </> "cabal.project")
          | otherwise = ProjectRootImplicit projectRootDir
        distDirLayout = defaultDistDirLayout projectRoot Nothing

    -- Clear state between test runs. The state remains if the previous run
    -- ended in an exception (as we leave the files to help with debugging).
    cleanProject testdir

    httpTransport <- configureTransport verbosity [] Nothing

    (projectConfig, localPackages) <-
      rebuildProjectConfig verbosity
                           httpTransport
                           distDirLayout
                           cliConfig

    let buildSettings = resolveBuildTimeSettings
                          verbosity cabalDirLayout
                          projectConfig

    return (distDirLayout,
            cabalDirLayout,
            projectConfig,
            localPackages,
            buildSettings)

type PlanDetails = (ProjDetails,
                    ElaboratedInstallPlan,
                    ElaboratedSharedConfig)

planProject :: FilePath -> ProjectConfig -> IO PlanDetails
planProject testdir cliConfig = do

    projDetails@(
       distDirLayout,
       cabalDirLayout,
       projectConfig,
       localPackages,
       _buildSettings) <- configureProject testdir cliConfig

    (elaboratedPlan, _, elaboratedShared, _, _) <-
      rebuildInstallPlan verbosity
                         distDirLayout cabalDirLayout
                         projectConfig
                         localPackages
                         Nothing

    return (projDetails,
            elaboratedPlan,
            elaboratedShared)

executePlan :: PlanDetails -> IO (ElaboratedInstallPlan, BuildOutcomes)
executePlan ((distDirLayout, cabalDirLayout, _, _, buildSettings),
             elaboratedPlan,
             elaboratedShared) = do

    let targets :: Map.Map UnitId [ComponentTarget]
        targets =
          Map.fromList
            [ (unitid, [ComponentTarget cname WholeComponent])
            | ts <- Map.elems (availableTargets elaboratedPlan)
            , AvailableTarget {
                availableTargetStatus = TargetBuildable (unitid, cname) _
              } <- ts
            ]
        elaboratedPlan' = pruneInstallPlanToTargets
                            TargetActionBuild targets
                            elaboratedPlan

    pkgsBuildStatus <-
      rebuildTargetsDryRun distDirLayout elaboratedShared
                           elaboratedPlan'

    let elaboratedPlan'' = improveInstallPlanWithUpToDatePackages
                             pkgsBuildStatus elaboratedPlan'

    buildOutcomes <-
      rebuildTargets verbosity
                     distDirLayout
                     (cabalStoreDirLayout cabalDirLayout)
                     elaboratedPlan''
                     elaboratedShared
                     pkgsBuildStatus
                     -- Avoid trying to use act-as-setup mode:
                     buildSettings { buildSettingNumJobs = 1 }

    return (elaboratedPlan'', buildOutcomes)

cleanProject :: FilePath -> IO ()
cleanProject testdir = do
    alreadyExists <- doesDirectoryExist distDir
    when alreadyExists $ removePathForcibly distDir
  where
    projectRoot    = ProjectRootImplicit (basedir </> testdir)
    distDirLayout  = defaultDistDirLayout projectRoot Nothing
    distDir        = distDirectory distDirLayout


verbosity :: Verbosity
verbosity = minBound --normal --verbose --maxBound --minBound



-------------------------------------------
-- Tasty integration to adjust the config
--

withProjectConfig :: (ProjectConfig -> TestTree) -> TestTree
withProjectConfig testtree =
    askOption $ \ghcPath ->
      testtree (mkProjectConfig ghcPath)

mkProjectConfig :: GhcPath -> ProjectConfig
mkProjectConfig (GhcPath ghcPath) =
    mempty {
      projectConfigShared = mempty {
        projectConfigHcPath = maybeToFlag ghcPath
      },
     projectConfigBuildOnly = mempty {
       projectConfigNumJobs = toFlag (Just 1)
     }
    }
  where
    maybeToFlag = maybe mempty toFlag


data GhcPath = GhcPath (Maybe FilePath)
  deriving Typeable

instance IsOption GhcPath where
  defaultValue = GhcPath Nothing
  optionName   = Tagged "with-ghc"
  optionHelp   = Tagged "The ghc compiler to use"
  parseValue   = Just . GhcPath . Just

projectConfigOptionDescriptions :: [OptionDescription]
projectConfigOptionDescriptions = [Option (Proxy :: Proxy GhcPath)]


---------------------------------------
-- HUint style utils for this context
--

expectException :: Exception e => String -> IO a -> IO e
expectException expected action = do
    res <- try action
    case res of
      Left  e -> return e
      Right _ -> throwIO $ HUnitFailure Nothing $ "expected an exception " ++ expected

expectPackagePreExisting :: ElaboratedInstallPlan -> BuildOutcomes -> PackageId
                         -> IO InstalledPackageInfo
expectPackagePreExisting plan buildOutcomes pkgid = do
    planpkg <- expectPlanPackage plan pkgid
    case (planpkg, InstallPlan.lookupBuildOutcome planpkg buildOutcomes) of
      (InstallPlan.PreExisting pkg, Nothing)
                       -> return pkg
      (_, buildResult) -> unexpectedBuildResult "PreExisting" planpkg buildResult

expectPackageConfigured :: ElaboratedInstallPlan -> BuildOutcomes -> PackageId
                        -> IO ElaboratedConfiguredPackage
expectPackageConfigured plan buildOutcomes pkgid = do
    planpkg <- expectPlanPackage plan pkgid
    case (planpkg, InstallPlan.lookupBuildOutcome planpkg buildOutcomes) of
      (InstallPlan.Configured pkg, Nothing)
                       -> return pkg
      (_, buildResult) -> unexpectedBuildResult "Configured" planpkg buildResult

expectPackageInstalled :: ElaboratedInstallPlan -> BuildOutcomes -> PackageId
                       -> IO ElaboratedConfiguredPackage
expectPackageInstalled plan buildOutcomes pkgid = do
    planpkg <- expectPlanPackage plan pkgid
    case (planpkg, InstallPlan.lookupBuildOutcome planpkg buildOutcomes) of
      (InstallPlan.Configured pkg, Just (Right _result)) -- result isn't used by any test
                       -> return pkg
      -- package can be installed in the global .store!
      -- (when installing from tarball!)
      (InstallPlan.Installed pkg, Nothing)
                       -> return pkg
      (_, buildResult) -> unexpectedBuildResult "Installed" planpkg buildResult

expectPackageFailed :: ElaboratedInstallPlan -> BuildOutcomes -> PackageId
                    -> IO (ElaboratedConfiguredPackage, BuildFailure)
expectPackageFailed plan buildOutcomes pkgid = do
    planpkg <- expectPlanPackage plan pkgid
    case (planpkg, InstallPlan.lookupBuildOutcome planpkg buildOutcomes) of
      (InstallPlan.Configured pkg, Just (Left failure))
                       -> return (pkg, failure)
      (_, buildResult) -> unexpectedBuildResult "Failed" planpkg buildResult

unexpectedBuildResult :: String -> ElaboratedPlanPackage
                      -> Maybe (Either BuildFailure BuildResult) -> IO a
unexpectedBuildResult expected planpkg buildResult =
    throwIO $ HUnitFailure Nothing $
         "expected to find " ++ display (packageId planpkg) ++ " in the "
      ++ expected ++ " state, but it is actually in the " ++ actual ++ " state."
  where
    actual = case (buildResult, planpkg) of
      (Nothing, InstallPlan.PreExisting{})       -> "PreExisting"
      (Nothing, InstallPlan.Configured{})        -> "Configured"
      (Just (Right _), InstallPlan.Configured{}) -> "Installed"
      (Just (Left  _), InstallPlan.Configured{}) -> "Failed"
      (Nothing, InstallPlan.Installed{})         -> "Installed globally"
      _                                          -> "Impossible! " ++ show buildResult ++ show planpkg

expectPlanPackage :: ElaboratedInstallPlan -> PackageId
                  -> IO ElaboratedPlanPackage
expectPlanPackage plan pkgid =
    case [ pkg
         | pkg <- InstallPlan.toList plan
         , packageId pkg == pkgid ] of
      [pkg] -> return pkg
      []    -> throwIO $ HUnitFailure Nothing $
                   "expected to find " ++ display pkgid
                ++ " in the install plan but it's not there"
      _     -> throwIO $ HUnitFailure Nothing $
                   "expected to find only one instance of " ++ display pkgid
                ++ " in the install plan but there's several"

expectBuildFailed :: BuildFailure -> IO ()
expectBuildFailed (BuildFailure _ (BuildFailed _)) = return ()
expectBuildFailed (BuildFailure _ reason) =
    assertFailure $ "expected BuildFailed, got " ++ show reason

---------------------------------------
-- Other utils
--

-- | Allow altering a file during a test, but then restore it afterwards
--
-- We read into the memory, as filesystems are tricky. (especially Windows)
--
withFileFinallyRestore :: FilePath -> IO a -> IO a
withFileFinallyRestore file action = do
    originalContents <- BS.readFile file
    action `finally` handle onIOError (tryFewTimes $ BS.writeFile file originalContents)
  where
    onIOError :: IOException -> IO ()
    onIOError e = putStrLn $ "WARNING: Cannot restore " ++ file ++ "; " ++ show e

-- Hopefully works around some Windows file-locking things.
-- Use with care:
--
-- Try action 4 times, with small sleep in between,
-- retrying if it fails for 'IOException' reason.
--
tryFewTimes :: forall a. IO a -> IO a
tryFewTimes action = go (3 :: Int) where
    go :: Int -> IO a
    go !n | n <= 0    = action
          | otherwise = action `catch` onIOError n

    onIOError :: Int -> IOException -> IO a
    onIOError n e = do
        hPutStrLn stderr $ "Trying " ++ show n ++ " after " ++ show e
        threadDelay 10000
        go (n - 1)

testNixFlags :: Assertion
testNixFlags = do
  let gc = globalCommand []
  -- changing from the v1 to v2 build command does not change whether the "--enable-nix" flag
  -- sets the globalNix param of the GlobalFlags type to True even though the v2 command doesn't use it
  let nixEnabledFlags = getFlags gc . commandParseArgs gc True $ ["--enable-nix", "build"]
  let nixDisabledFlags = getFlags gc . commandParseArgs gc True $ ["--disable-nix", "build"]
  let nixDefaultFlags = getFlags gc . commandParseArgs gc True $ ["build"]
  True @=? isJust nixDefaultFlags
  True @=? isJust nixEnabledFlags
  True @=? isJust nixDisabledFlags
  Just True @=? (fromFlag . globalNix . fromJust $ nixEnabledFlags)
  Just False @=? (fromFlag . globalNix . fromJust $ nixDisabledFlags)
  Nothing @=? (fromFlag . globalNix . fromJust $ nixDefaultFlags)

  -- Config file options
  trueConfig <- loadConfig verbosity (Flag (basedir </> "nix-config/nix-true"))
  falseConfig <- loadConfig verbosity (Flag (basedir </> "nix-config/nix-false"))

  Just True @=? (fromFlag . globalNix . savedGlobalFlags $ trueConfig)
  Just False @=? (fromFlag . globalNix . savedGlobalFlags $ falseConfig)

  where
    fromFlag :: Flag Bool -> Maybe Bool
    fromFlag (Flag x) = Just x
    fromFlag NoFlag = Nothing
    getFlags :: CommandUI GlobalFlags -> CommandParse (GlobalFlags -> GlobalFlags, [String]) -> Maybe GlobalFlags
    getFlags cui (CommandReadyToGo (mkflags, _)) = Just . mkflags . commandDefaultFlags $ cui
    getFlags _ _ = Nothing

-- Tests whether config options are commented or not
testConfigOptionComments :: Assertion
testConfigOptionComments = do
  _ <- createDefaultConfigFile verbosity [] (basedir </> "config/default-config")
  defaultConfigFile <- readFile (basedir </> "config/default-config")

  "  url" @=? findLineWith False "url" defaultConfigFile
  "  -- secure" @=? findLineWith True "secure" defaultConfigFile
  "  -- root-keys" @=? findLineWith True "root-keys" defaultConfigFile
  "  -- key-threshold" @=? findLineWith True "key-threshold" defaultConfigFile

  "-- ignore-expiry" @=? findLineWith True "ignore-expiry" defaultConfigFile
  "-- http-transport" @=? findLineWith True "http-transport" defaultConfigFile
  "-- nix" @=? findLineWith True "nix" defaultConfigFile
  "-- store-dir" @=? findLineWith True "store-dir" defaultConfigFile
  "-- active-repositories" @=? findLineWith True "active-repositories" defaultConfigFile
  "-- local-no-index-repo" @=? findLineWith True "local-no-index-repo" defaultConfigFile
  "remote-repo-cache"  @=? findLineWith False "remote-repo-cache" defaultConfigFile
  "-- logs-dir"  @=? findLineWith True "logs-dir" defaultConfigFile
  "-- default-user-config" @=? findLineWith True "default-user-config" defaultConfigFile
  "-- verbose" @=? findLineWith True "verbose" defaultConfigFile
  "-- compiler" @=? findLineWith True "compiler" defaultConfigFile
  "-- cabal-file" @=? findLineWith True "cabal-file" defaultConfigFile
  "-- with-compiler" @=? findLineWith True "with-compiler" defaultConfigFile
  "-- with-hc-pkg" @=? findLineWith True "with-hc-pkg" defaultConfigFile
  "-- program-prefix" @=? findLineWith True "program-prefix" defaultConfigFile
  "-- program-suffix" @=? findLineWith True "program-suffix" defaultConfigFile
  "-- library-vanilla" @=? findLineWith True "library-vanilla" defaultConfigFile
  "-- library-profiling" @=? findLineWith True "library-profiling" defaultConfigFile
  "-- shared" @=? findLineWith True "shared" defaultConfigFile
  "-- static" @=? findLineWith True "static" defaultConfigFile
  "-- executable-dynamic" @=? findLineWith True "executable-dynamic" defaultConfigFile
  "-- executable-static" @=? findLineWith True "executable-static" defaultConfigFile
  "-- profiling" @=? findLineWith True "profiling" defaultConfigFile
  "-- executable-profiling" @=? findLineWith True "executable-profiling" defaultConfigFile
  "-- profiling-detail" @=? findLineWith True "profiling-detail" defaultConfigFile
  "-- library-profiling-detail" @=? findLineWith True "library-profiling-detail" defaultConfigFile
  "-- optimization" @=? findLineWith True "optimization" defaultConfigFile
  "-- debug-info" @=? findLineWith True "debug-info" defaultConfigFile
  "-- build-info" @=? findLineWith True "build-info" defaultConfigFile
  "-- library-for-ghci" @=? findLineWith True "library-for-ghci" defaultConfigFile
  "-- split-sections" @=? findLineWith True "split-sections" defaultConfigFile
  "-- split-objs" @=? findLineWith True "split-objs" defaultConfigFile
  "-- executable-stripping" @=? findLineWith True "executable-stripping" defaultConfigFile
  "-- library-stripping" @=? findLineWith True "library-stripping" defaultConfigFile
  "-- configure-option" @=? findLineWith True "configure-option" defaultConfigFile
  "-- user-install"  @=? findLineWith True "user-install" defaultConfigFile
  "-- package-db"  @=? findLineWith True "package-db" defaultConfigFile
  "-- flags" @=? findLineWith True "flags" defaultConfigFile
  "-- extra-include-dirs" @=? findLineWith True "extra-include-dirs" defaultConfigFile
  "-- deterministic" @=? findLineWith True "deterministic" defaultConfigFile
  "-- cid" @=? findLineWith True "cid" defaultConfigFile
  "-- extra-lib-dirs" @=? findLineWith True "extra-lib-dirs" defaultConfigFile
  "-- extra-lib-dirs-static" @=? findLineWith True "extra-lib-dirs-static" defaultConfigFile
  "-- extra-framework-dirs" @=? findLineWith True "extra-framework-dirs" defaultConfigFile
  "-- extra-prog-path"  @=? findLineWith False "extra-prog-path" defaultConfigFile
  "-- instantiate-with" @=? findLineWith True "instantiate-with" defaultConfigFile
  "-- tests" @=? findLineWith True "tests" defaultConfigFile
  "-- coverage" @=? findLineWith True "coverage" defaultConfigFile
  "-- library-coverage" @=? findLineWith True "library-coverage" defaultConfigFile
  "-- exact-configuration" @=? findLineWith True "exact-configuration" defaultConfigFile
  "-- benchmarks" @=? findLineWith True "benchmarks" defaultConfigFile
  "-- relocatable"  @=? findLineWith True "relocatable" defaultConfigFile
  "-- response-files" @=? findLineWith True "response-files" defaultConfigFile
  "-- allow-depending-on-private-libs" @=? findLineWith True "allow-depending-on-private-libs" defaultConfigFile
  "-- cabal-lib-version" @=? findLineWith True "cabal-lib-version" defaultConfigFile
  "-- append" @=? findLineWith True "append" defaultConfigFile
  "-- backup" @=? findLineWith True "backup" defaultConfigFile
  "-- constraint" @=? findLineWith True "constraint" defaultConfigFile
  "-- preference" @=? findLineWith True "preference" defaultConfigFile
  "-- solver"  @=? findLineWith True "solver" defaultConfigFile
  "-- allow-older"  @=? findLineWith True "allow-older" defaultConfigFile
  "-- allow-newer"  @=? findLineWith True "allow-newer" defaultConfigFile
  "-- write-ghc-environment-files" @=? findLineWith True "write-ghc-environment-files" defaultConfigFile
  "-- documentation"  @=? findLineWith True "documentation" defaultConfigFile
  "-- doc-index-file"  @=? findLineWith True "doc-index-file" defaultConfigFile
  "-- only-download"  @=? findLineWith True "only-download" defaultConfigFile
  "-- target-package-db" @=? findLineWith True "target-package-db" defaultConfigFile
  "-- max-backjumps"  @=? findLineWith True "max-backjumps" defaultConfigFile
  "-- reorder-goals"  @=? findLineWith True "reorder-goals" defaultConfigFile
  "-- count-conflicts"  @=? findLineWith True "count-conflicts" defaultConfigFile
  "-- fine-grained-conflicts"  @=? findLineWith True "fine-grained-conflicts" defaultConfigFile
  "-- minimize-conflict-set"  @=? findLineWith True "minimize-conflict-set" defaultConfigFile
  "-- independent-goals"  @=? findLineWith True "independent-goals" defaultConfigFile
  "-- prefer-oldest"  @=? findLineWith True "prefer-oldest" defaultConfigFile
  "-- shadow-installed-packages"  @=? findLineWith True "shadow-installed-packages" defaultConfigFile
  "-- strong-flags"  @=? findLineWith True "strong-flags" defaultConfigFile
  "-- allow-boot-library-installs"  @=? findLineWith True "allow-boot-library-installs" defaultConfigFile
  "-- reject-unconstrained-dependencies"  @=? findLineWith True "reject-unconstrained-dependencies" defaultConfigFile
  "-- reinstall"  @=? findLineWith True "reinstall" defaultConfigFile
  "-- avoid-reinstalls"  @=? findLineWith True "avoid-reinstalls" defaultConfigFile
  "-- force-reinstalls"  @=? findLineWith True "force-reinstalls" defaultConfigFile
  "-- upgrade-dependencies"  @=? findLineWith True "upgrade-dependencies" defaultConfigFile
  "-- index-state" @=? findLineWith True "index-state" defaultConfigFile
  "-- root-cmd" @=? findLineWith True "root-cmd" defaultConfigFile
  "-- symlink-bindir" @=? findLineWith True "symlink-bindir" defaultConfigFile
  "build-summary"  @=? findLineWith False "build-summary" defaultConfigFile
  "-- build-log" @=? findLineWith True "build-log" defaultConfigFile
  "remote-build-reporting"  @=? findLineWith False "remote-build-reporting" defaultConfigFile
  "-- report-planning-failure"  @=? findLineWith True "report-planning-failure" defaultConfigFile
  "-- per-component"  @=? findLineWith True "per-component" defaultConfigFile
  "-- run-tests" @=? findLineWith True "run-tests" defaultConfigFile
  "jobs"  @=? findLineWith False "jobs" defaultConfigFile
  "-- keep-going"  @=? findLineWith True "keep-going" defaultConfigFile
  "-- offline"  @=? findLineWith True "offline" defaultConfigFile
  "-- lib" @=? findLineWith True "lib" defaultConfigFile
  "-- package-env" @=? findLineWith True "package-env" defaultConfigFile
  "-- overwrite-policy" @=? findLineWith True "overwrite-policy" defaultConfigFile
  "-- install-method" @=? findLineWith True "install-method" defaultConfigFile
  "installdir"  @=? findLineWith False "installdir" defaultConfigFile
  "-- username" @=? findLineWith True "username" defaultConfigFile
  "-- password" @=? findLineWith True "password" defaultConfigFile
  "-- password-command" @=? findLineWith True "password-command" defaultConfigFile
  "-- builddir" @=? findLineWith True "builddir" defaultConfigFile

  "  -- keep-temp-files" @=? findLineWith True "keep-temp-files" defaultConfigFile
  "  -- hoogle" @=? findLineWith True "hoogle" defaultConfigFile
  "  -- html" @=? findLineWith True "html" defaultConfigFile
  "  -- html-location" @=? findLineWith True "html-location" defaultConfigFile
  "  -- executables" @=? findLineWith True "executables" defaultConfigFile
  "  -- foreign-libraries" @=? findLineWith True "foreign-libraries" defaultConfigFile
  "  -- all" @=? findLineWith True "all" defaultConfigFile
  "  -- internal" @=? findLineWith True "internal" defaultConfigFile
  "  -- css" @=? findLineWith True "css" defaultConfigFile
  "  -- hyperlink-source" @=? findLineWith True "hyperlink-source" defaultConfigFile
  "  -- quickjump" @=? findLineWith True "quickjump" defaultConfigFile
  "  -- hscolour-css" @=? findLineWith True "hscolour-css" defaultConfigFile
  "  -- contents-location" @=? findLineWith True "contents-location" defaultConfigFile
  "  -- index-location" @=? findLineWith True "index-location" defaultConfigFile
  "  -- base-url" @=? findLineWith True "base-url" defaultConfigFile

  "  -- interactive" @=? findLineWith True "interactive" defaultConfigFile
  "  -- cabal-version" @=? findLineWith True "cabal-version" defaultConfigFile
  "  -- license" @=? findLineWith True "license" defaultConfigFile
  "  -- extra-doc-file" @=? findLineWith True "extra-doc-file" defaultConfigFile
  "  -- test-dir" @=? findLineWith True "test-dir" defaultConfigFile
  "  -- language" @=? findLineWith True "language" defaultConfigFile
  "  -- application-dir" @=? findLineWith True "application-dir" defaultConfigFile
  "  -- source-dir" @=? findLineWith True "source-dir" defaultConfigFile

  "  -- prefix"  @=? findLineWith True "prefix" defaultConfigFile
  "  -- bindir"@=? findLineWith True "bindir" defaultConfigFile
  "  -- libdir" @=? findLineWith True "libdir" defaultConfigFile
  "  -- libsubdir" @=? findLineWith True "libsubdir" defaultConfigFile
  "  -- dynlibdir" @=? findLineWith True "dynlibdir" defaultConfigFile
  "  -- libexecdir" @=? findLineWith True "libexecdir" defaultConfigFile
  "  -- libexecsubdir" @=? findLineWith True "libexecsubdir" defaultConfigFile
  "  -- datadir" @=? findLineWith True "datadir" defaultConfigFile
  "  -- datasubdir" @=? findLineWith True "datasubdir" defaultConfigFile
  "  -- docdir" @=? findLineWith True "docdir" defaultConfigFile
  "  -- htmldir" @=? findLineWith True "htmldir" defaultConfigFile
  "  -- haddockdir" @=? findLineWith True "haddockdir" defaultConfigFile
  "  -- sysconfdir" @=? findLineWith True "sysconfdir" defaultConfigFile

  "  -- alex-location" @=? findLineWith True "alex-location" defaultConfigFile
  "  -- ar-location" @=? findLineWith True "ar-location" defaultConfigFile
  "  -- c2hs-location" @=? findLineWith True "c2hs-location" defaultConfigFile
  "  -- cpphs-location" @=? findLineWith True "cpphs-location" defaultConfigFile
  "  -- doctest-location" @=? findLineWith True "doctest-location" defaultConfigFile
  "  -- gcc-location" @=? findLineWith True "gcc-location" defaultConfigFile
  "  -- ghc-location" @=? findLineWith True "ghc-location" defaultConfigFile
  "  -- ghc-pkg-location" @=? findLineWith True "ghc-pkg-location" defaultConfigFile
  "  -- ghcjs-location" @=? findLineWith True "ghcjs-location" defaultConfigFile
  "  -- ghcjs-pkg-location" @=? findLineWith True "ghcjs-pkg-location" defaultConfigFile
  "  -- greencard-location" @=? findLineWith True "greencard-location" defaultConfigFile
  "  -- haddock-location" @=? findLineWith True "haddock-location" defaultConfigFile
  "  -- happy-location" @=? findLineWith True "happy-location" defaultConfigFile
  "  -- haskell-suite-location" @=? findLineWith True "haskell-suite-location" defaultConfigFile
  "  -- haskell-suite-pkg-location" @=? findLineWith True "haskell-suite-pkg-location" defaultConfigFile
  "  -- hmake-location" @=? findLineWith True "hmake-location" defaultConfigFile
  "  -- hpc-location" @=? findLineWith True "hpc-location" defaultConfigFile
  "  -- hscolour-location" @=? findLineWith True "hscolour-location" defaultConfigFile
  "  -- jhc-location" @=? findLineWith True "jhc-location" defaultConfigFile
  "  -- ld-location" @=? findLineWith True "ld-location" defaultConfigFile
  "  -- pkg-config-location" @=? findLineWith True "pkg-config-location" defaultConfigFile
  "  -- runghc-location" @=? findLineWith True "runghc-location" defaultConfigFile
  "  -- strip-location" @=? findLineWith True "strip-location" defaultConfigFile
  "  -- tar-location" @=? findLineWith True "tar-location" defaultConfigFile
  "  -- uhc-location" @=? findLineWith True "uhc-location" defaultConfigFile

  "  -- alex-options" @=? findLineWith True "alex-options" defaultConfigFile
  "  -- ar-options" @=? findLineWith True "ar-options" defaultConfigFile
  "  -- c2hs-options" @=? findLineWith True "c2hs-options" defaultConfigFile
  "  -- cpphs-options" @=? findLineWith True "cpphs-options" defaultConfigFile
  "  -- doctest-options" @=? findLineWith True "doctest-options" defaultConfigFile
  "  -- gcc-options" @=? findLineWith True "gcc-options" defaultConfigFile
  "  -- ghc-options" @=? findLineWith True "ghc-options" defaultConfigFile
  "  -- ghc-pkg-options" @=? findLineWith True "ghc-pkg-options" defaultConfigFile
  "  -- ghcjs-options" @=? findLineWith True "ghcjs-options" defaultConfigFile
  "  -- ghcjs-pkg-options" @=? findLineWith True "ghcjs-pkg-options" defaultConfigFile
  "  -- greencard-options" @=? findLineWith True "greencard-options" defaultConfigFile
  "  -- haddock-options" @=? findLineWith True "haddock-options" defaultConfigFile
  "  -- happy-options" @=? findLineWith True "happy-options" defaultConfigFile
  "  -- haskell-suite-options" @=? findLineWith True "haskell-suite-options" defaultConfigFile
  "  -- haskell-suite-pkg-options" @=? findLineWith True "haskell-suite-pkg-options" defaultConfigFile
  "  -- hmake-options" @=? findLineWith True "hmake-options" defaultConfigFile
  "  -- hpc-options" @=? findLineWith True "hpc-options" defaultConfigFile
  "  -- hsc2hs-options" @=? findLineWith True "hsc2hs-options" defaultConfigFile
  "  -- hscolour-options" @=? findLineWith True "hscolour-options" defaultConfigFile
  "  -- jhc-options" @=? findLineWith True "jhc-options" defaultConfigFile
  "  -- ld-options" @=? findLineWith True "ld-options" defaultConfigFile
  "  -- pkg-config-options" @=? findLineWith True "pkg-config-options" defaultConfigFile
  "  -- runghc-options" @=? findLineWith True "runghc-options" defaultConfigFile
  "  -- strip-options" @=? findLineWith True "strip-options" defaultConfigFile
  "  -- tar-options" @=? findLineWith True "tar-options" defaultConfigFile
  "  -- uhc-options" @=? findLineWith True "uhc-options" defaultConfigFile
  where
    -- | Find lines containing a target string.
    findLineWith :: Bool -> String -> String -> String
    findLineWith isComment target text
      | not . null $ findLinesWith isComment target text = removeCommentValue . L.head $ findLinesWith isComment target text
      | otherwise  = text
    findLinesWith :: Bool -> String -> String -> [String]
    findLinesWith isComment target
      | isComment = filter (isInfixOf (" " ++ target ++ ":")) . lines
      | otherwise = filter (isInfixOf (target ++ ":")) . lines
    removeCommentValue :: String -> String
    removeCommentValue = takeWhile (/= ':')

testIgnoreProjectFlag :: Assertion
testIgnoreProjectFlag = do
  -- Coverage flag should be false globally by default (~/.cabal folder)
  (_, _, prjConfigGlobal, _, _) <- configureProject testdir ignoreSetConfig
  let globalCoverageFlag = packageConfigCoverage . projectConfigLocalPackages $ prjConfigGlobal
  False @=? Flag.fromFlagOrDefault False globalCoverageFlag
  -- It is set to true in the cabal.project file
  (_, _, prjConfigLocal, _, _) <- configureProject testdir emptyConfig
  let localCoverageFlag = packageConfigCoverage . projectConfigLocalPackages $ prjConfigLocal
  True @=? Flag.fromFlagOrDefault False localCoverageFlag
  where
    testdir = "build/ignore-project"
    emptyConfig = mempty
    ignoreSetConfig :: ProjectConfig
    ignoreSetConfig = mempty { projectConfigShared = mempty { projectConfigIgnoreProject = Flag True } }


cleanHaddockProject :: FilePath -> IO ()
cleanHaddockProject testdir = do
    cleanProject testdir
    let haddocksdir = basedir </> testdir </> "haddocks"
    alreadyExists <- doesDirectoryExist haddocksdir
    when alreadyExists $ removePathForcibly haddocksdir
    let storedir = basedir </> testdir </> "store"
    alreadyExists' <- doesDirectoryExist storedir
    when alreadyExists' $ removePathForcibly storedir


testHaddockProjectDependencies :: ProjectConfig -> Assertion
testHaddockProjectDependencies config = do
    (_,_,sharedConfig) <- planProject testdir config
    -- `haddock-project` is only supported by `haddock-2.26.1` and above which is
    -- shipped with `ghc-9.4`
    when (compilerVersion (pkgConfigCompiler sharedConfig) > mkVersion [9,4]) $ do
      let dir = basedir </> testdir
      cleanHaddockProject testdir
      withCurrentDirectory dir $ do
        CmdHaddockProject.haddockProjectAction
          defaultHaddockProjectFlags { haddockProjectVerbosity = Flag verbosity }
          ["all"]
          defaultGlobalFlags { globalStoreDir = Flag "store" }

        let haddock = "haddocks" </> "async" </> "async.haddock"
        hasHaddock <- doesFileExist haddock
        unless hasHaddock $ assertFailure ("File `" ++ haddock ++ "` does not exist.")
      cleanHaddockProject testdir
  where
    testdir = "haddock-project/dependencies"