aboutsummaryrefslogtreecommitdiff
path: root/libbpkg/manifest.hxx
blob: 35bf9153fe11b9590d5879c06ffdd3cf5a54c401 (plain)
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
// file      : libbpkg/manifest.hxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#ifndef LIBBPKG_MANIFEST_HXX
#define LIBBPKG_MANIFEST_HXX

#include <map>
#include <string>
#include <vector>
#include <cassert>
#include <cstdint>    // uint*_t
#include <ostream>
#include <utility>    // move()
#include <stdexcept>  // logic_error
#include <functional>

#include <libbutl/url.hxx>
#include <libbutl/path.hxx>
#include <libbutl/optional.hxx>
#include <libbutl/small-vector.hxx>
#include <libbutl/standard-version.hxx>
#include <libbutl/manifest-forward.hxx>

#include <libbpkg/package-name.hxx>

#include <libbpkg/export.hxx>
#include <libbpkg/version.hxx>

namespace bpkg
{
  using strings = std::vector<std::string>;

  // @@ Let's create <libbpkg/types.hxx> with "basic" package types.
  //
  class LIBBPKG_EXPORT version
  {
  public:
    // Let's keep the members in the order they appear in the string
    // representation. We also make them const to make sure things stay
    // consistent.
    //
    const std::uint16_t epoch;
    const std::string upstream;
    const butl::optional<std::string> release;

    // The absent revision semantics depends on the context the version object
    // is used in. Normally, it is equivalent to zero revision but may have a
    // special meaning, for example, denoting any package revision.
    //
    const butl::optional<std::uint16_t> revision;

    const std::uint32_t iteration;

    // Upstream part canonical representation.
    //
    const std::string canonical_upstream;

    // Release part canonical representation.
    //
    const std::string canonical_release;

    // Create a special empty version. It is less than any other valid
    // version (and is conceptually equivalent to +0-0-).
    //
    version (): epoch (0), release (""), iteration (0) {}

    // By default, treat the zero revision as no revision. Throw
    // std::invalid_argument if the passed string is not a valid version
    // representation.
    //
    enum flags
    {
      none               = 0,
      fold_zero_revision = 0x01,
      allow_iteration    = 0x02
    };

    explicit
    version (const std::string& v, flags fl = fold_zero_revision)
        : version (v.c_str (), fl) {}

    explicit
    version (const char* v, flags fl = fold_zero_revision)
        : version (data_type (v, data_type::parse::full, fl))
    {
    }

    // Create the version object from separate epoch, upstream, release,
    // revision, and iteration parts.
    //
    // Note that it is possible (and legal) to create the special empty
    // version via this interface as version(0, string(), string(), nullopt, 0).
    //
    version (std::uint16_t epoch,
             std::string upstream,
             butl::optional<std::string> release,
             butl::optional<std::uint16_t> revision,
             std::uint32_t iteration);

    std::uint16_t
    effective_revision () const noexcept {return revision ? *revision : 0;}

    version (version&&) = default;
    version (const version&) = default;
    version& operator= (version&&);
    version& operator= (const version&);

    // If the revision is ignored, then the iteration (that semantically
    // extends the revision) is also ignored, regardless of the argument.
    //
    std::string
    string (bool ignore_revision = false, bool ignore_iteration = false) const;

    bool
    operator< (const version& v) const noexcept {return compare (v) < 0;}

    bool
    operator> (const version& v) const noexcept {return compare (v) > 0;}

    bool
    operator== (const version& v) const noexcept {return compare (v) == 0;}

    bool
    operator<= (const version& v) const noexcept {return compare (v) <= 0;}

    bool
    operator>= (const version& v) const noexcept {return compare (v) >= 0;}

    bool
    operator!= (const version& v) const noexcept {return compare (v) != 0;}

    // If the revision is ignored, then the iteration is also ignored,
    // regardless of the argument (see above for details).
    //
    int
    compare (const version& v,
             bool ignore_revision = false,
             bool ignore_iteration = false) const noexcept
    {
      if (epoch != v.epoch)
        return epoch < v.epoch ? -1 : 1;

      if (int c = canonical_upstream.compare (v.canonical_upstream))
        return c;

      if (int c = canonical_release.compare (v.canonical_release))
        return c;

      if (!ignore_revision)
      {
        if (revision != v.revision)
          return revision < v.revision ? -1 : 1;

        if (!ignore_iteration && iteration != v.iteration)
          return iteration < v.iteration ? -1 : 1;
      }

      return 0;
    }

    bool
    empty () const noexcept
    {
      bool e (upstream.empty ());

      assert (!e ||
              (epoch == 0 &&
               release && release->empty () &&
               !revision && iteration == 0));

      return e;
    }

  private:
    struct LIBBPKG_EXPORT data_type
    {
      enum class parse {full, upstream, release};

      data_type (const char*, parse, flags);

      // Note that there is no iteration component as it can't be present in
      // the string representation passed to the ctor.
      //
      std::uint16_t epoch;
      std::string upstream;
      butl::optional<std::string> release;
      butl::optional<std::uint16_t> revision;
      std::uint32_t iteration;
      std::string canonical_upstream;
      std::string canonical_release;
    };

    explicit
    version (data_type&& d)
        : epoch (d.epoch),
          upstream (std::move (d.upstream)),
          release (std::move (d.release)),
          revision (d.revision),
          iteration (d.iteration),
          canonical_upstream (std::move (d.canonical_upstream)),
          canonical_release (std::move (d.canonical_release)) {}
  };

  inline std::ostream&
  operator<< (std::ostream& os, const version& v)
  {
    return os << (v.empty () ? "<empty-version>" : v.string ());
  }

  inline version::flags
  operator&= (version::flags& x, version::flags y)
  {
    return x = static_cast<version::flags> (
      static_cast<std::uint16_t> (x) &
      static_cast<std::uint16_t> (y));
  }

  inline version::flags
  operator|= (version::flags& x, version::flags y)
  {
    return x = static_cast<version::flags> (
      static_cast<std::uint16_t> (x) |
      static_cast<std::uint16_t> (y));
  }

  inline version::flags
  operator& (version::flags x, version::flags y)
  {
    return x &= y;
  }

  inline version::flags
  operator| (version::flags x, version::flags y)
  {
    return x |= y;
  }

  // priority
  //
  class priority
  {
  public:
    enum value_type {low, medium, high, security};

    value_type value; // Shouldn't be necessary to access directly.
    std::string comment;

    priority (value_type v = low, std::string c = "")
        : value (v), comment (std::move (c)) {}

    operator value_type () const {return value;}
  };

  // description
  // description-file
  // change
  // change-file
  //
  class LIBBPKG_EXPORT text_file
  {
  public:
    using path_type = butl::path;

    bool file;

    union
    {
      std::string text;
      path_type path;
    };

    std::string comment;

    // File text constructor.
    //
    explicit
    text_file (std::string t = ""): file (false), text (std::move (t)) {}

    // File reference constructor.
    //
    text_file (path_type p, std::string c)
        : file (true), path (std::move (p)), comment (std::move (c)) {}

    text_file (text_file&&);
    text_file (const text_file&);
    text_file& operator= (text_file&&);
    text_file& operator= (const text_file&);

    ~text_file ();
  };

  // license
  //
  class licenses: public butl::small_vector<std::string, 1>
  {
  public:
    std::string comment;

    explicit
    licenses (std::string c = ""): comment (std::move (c)) {}
  };

  // url
  // doc-url
  // src-url
  // package-url
  //
  // URL that has the following constraints:
  //
  // - is not rootless
  // - is not local (the scheme is not `file`)
  // - authority is present and is not empty
  //
  // See libbutl/url.hxx for details.
  //
  // NOTE: this class must not be DLL-exported wholesale (non-exported base).
  //
  class manifest_url: public butl::url
  {
  public:
    std::string comment;

    // Throw invalid_argument on parsing or constraints checking error.
    //
    explicit LIBBPKG_EXPORT
    manifest_url (const std::string& u, std::string c = "");

    manifest_url () = default;
  };

  // email
  // package-email
  // build-email
  // build-warning-email
  // build-error-email
  //
  class email: public std::string
  {
  public:
    std::string comment;

    explicit
    email (std::string e = "", std::string c = "")
        : std::string (std::move (e)), comment (std::move (c)) {}
  };

  // Represented as a version range. Note that the versions may refer to the
  // dependent package version and can be completed with the actual versions
  // using the effective() function. Such versions are represented as an empty
  // version object and have the dollar character string representation.
  //
  // If the version endpoints are equal and both are closed, then this is the
  // `== <version>` constraint (in particular, `== $` if empty endpoints). If
  // both endpoints are empty and one of them is open, then this is either
  // `~$` (min endpoint is open) or `^$` (max endpoint is open). Note that
  // equal endpoints can never be both open.
  //
  // An absent endpoint version revision has the 'any revision' meaning
  // (except for an earliest release for which the revision is meaningless) and
  // so translates into the effective revision differently, depending on the
  // range endpoint side and openness:
  //
  // [X Y)  ==  [X+0   Y+0)
  // (X Y]  ==  (X+max Y+max]
  //
  class LIBBPKG_EXPORT version_constraint
  {
  public:
    butl::optional<version> min_version;
    butl::optional<version> max_version;
    bool min_open;
    bool max_open;

    // Preserve the zero endpoint version revisions (see above for details).
    //
    explicit
    version_constraint (const std::string&);

    version_constraint (butl::optional<version> min_version, bool min_open,
                        butl::optional<version> max_version, bool max_open);

    explicit
    version_constraint (const version& v)
        : version_constraint (v, false, v, false) {}

    version_constraint () = default;

    bool
    empty () const noexcept {return !min_version && !max_version;}

    bool
    complete () const noexcept
    {
      return (!min_version || !min_version->empty ()) &&
             (!max_version || !max_version->empty ());
    }

    // Return the completed constraint if it refers to the dependent package
    // version and copy of itself otherwise. Throw std::invalid_argument if
    // the resulting constraint is invalid (max version is less than min
    // version in range, non-standard or latest snapshot version for a
    // shortcut operator, etc.).
    //
    version_constraint
    effective (version) const;

    std::string
    string () const;
  };

  inline std::ostream&
  operator<< (std::ostream& os, const version_constraint& vc)
  {
    return os << vc.string ();
  }

  inline bool
  operator== (const version_constraint& x, const version_constraint& y)
  {
    return x.min_version == y.min_version && x.max_version == y.max_version &&
           x.min_open == y.min_open && x.max_open == y.max_open;
  }

  inline bool
  operator!= (const version_constraint& x, const version_constraint& y)
  {
    return !(x == y);
  }

  struct LIBBPKG_EXPORT dependency
  {
    package_name name;
    butl::optional<version_constraint> constraint;

    dependency () = default;
    dependency (package_name n, butl::optional<version_constraint> c)
        : name (std::move (n)), constraint (std::move (c)) {}

    // Parse the dependency string representation in the
    // `<name> [<version-constraint>]` form. Throw std::invalid_argument if
    // the value is invalid.
    //
    explicit
    dependency (std::string);

    std::string
    string () const;
  };

  inline std::ostream&
  operator<< (std::ostream& os, const dependency& d)
  {
    return os << d.string ();
  }

  // depends
  //
  // The dependency alternative can be represented in one of the following
  // forms.
  //
  // Single-line form:
  //
  //   <dependencies> ['?' <enable-condition>] [<reflect-config>]
  //
  //   <dependencies> = <dependency> |
  //                    ({ <dependency> [ <dependency>]* } [<version-constraint>])
  //
  //   <enable-condition> - buildfile evaluation context
  //   <reflect-config>   - dependent package configuration variable assignment
  //
  //   If the version constraint is specified after the dependency group, it
  //   only applies to dependencies without a version constraint.
  //
  // Multi-line forms:
  //
  //   <dependencies>
  //   {
  //     enable <enable-condition>
  //
  //     prefer
  //     {
  //       <prefer-config>
  //     }
  //
  //     accept <accept-condition>
  //
  //     reflect
  //     {
  //       <reflect-config>
  //     }
  //   }
  //   |
  //   <dependencies>
  //   {
  //     enable <enable-condition>
  //
  //     require
  //     {
  //       <require-config>
  //     }
  //
  //     reflect
  //     {
  //       <reflect-config>
  //     }
  //   }
  //
  //   <prefer-config>    - buildfile fragment containing dependency packages
  //                        configuration variables assignments
  //
  //   <accept-condition> - buildfile evaluation context
  //
  //   <require-config>   - buildfile fragment containing dependency packages
  //                        configuration variables assignments
  //
  //   <reflect-config>   - buildfile fragment containing dependent package
  //                        configuration variables assignments
  //
  //   In the multi-line form the block may contain comments besides the
  //   clauses. The '#' character starts a single-line comment which spans
  //   until the end of the line. Unless it is followed with '\' followed by
  //   the newline in which case this is a multi-line comment which spans
  //   until the closing '#\' is encountered.
  //
  // The dependency alternative is only considered by bpkg if the enable
  // condition evaluates to true. If the enable clause is not specified, then
  // it is always considered.
  //
  // The prefer clause specifies the preferred dependency package
  // configuration that may potentially differ from the resulting
  // configuration after the preferred/required configurations from all the
  // selected dependency alternatives of all the dependent packages are
  // "negotiated" by bpkg. The accept clause is used to verify that the
  // resulting configuration is still acceptable for the dependent
  // package. The accept clause must always be specified if the prefer clause
  // is specified.
  //
  // The require clause specifies the only acceptable dependency packages
  // configuration. It is a shortcut for specifying the prefer/accept clauses,
  // where the accept condition verifies all the variable values assigned in
  // the prefer clause. The require clause and the prefer/accept clause pair
  // are optional and are mutually exclusive.
  //
  // The reflect clause specifies the dependent package configuration that
  // should be used if the alternative is selected.
  //
  // All clauses are optional but at least one of them must be specified.
  //
  class dependency_alternative: public butl::small_vector<dependency, 1>
  {
  public:
    butl::optional<std::string> enable;
    butl::optional<std::string> reflect;
    butl::optional<std::string> prefer;
    butl::optional<std::string> accept;
    butl::optional<std::string> require;

    dependency_alternative () = default;
    dependency_alternative (butl::optional<std::string> e,
                            butl::optional<std::string> r,
                            butl::optional<std::string> p,
                            butl::optional<std::string> a,
                            butl::optional<std::string> q)
        : enable (std::move (e)),
          reflect (std::move (r)),
          prefer (std::move (p)),
          accept (std::move (a)),
          require (std::move (q)) {}

    // Can be used to copy a dependency alternative object, while omitting
    // some clauses which are no longer needed.
    //
    dependency_alternative (butl::optional<std::string> e,
                            butl::optional<std::string> r,
                            butl::optional<std::string> p,
                            butl::optional<std::string> a,
                            butl::optional<std::string> q,
                            butl::small_vector<dependency, 1> ds)
        : small_vector<dependency, 1> (move (ds)),
          enable (std::move (e)),
          reflect (std::move (r)),
          prefer (std::move (p)),
          accept (std::move (a)),
          require (std::move (q)) {}

    // Return the single-line representation if possible (the prefer and
    // require clauses are absent and the reflect clause either absent or
    // contains no newlines).
    //
    LIBBPKG_EXPORT std::string
    string () const;

    // Return true if the string() function would return the single-line
    // representation.
    //
    LIBBPKG_EXPORT bool
    single_line () const;
  };

  inline std::ostream&
  operator<< (std::ostream& os, const dependency_alternative& da)
  {
    return os << da.string ();
  }

  class dependency_alternatives:
    public butl::small_vector<dependency_alternative, 1>
  {
  public:
    bool buildtime;
    std::string comment;

    dependency_alternatives () = default;
    dependency_alternatives (bool b, std::string c)
        : buildtime (b), comment (std::move (c)) {}

    // Parse the dependency alternatives string representation in the form:
    //
    // [*] <alternative> [ '|' <alternative>]* [; <comment>]
    //
    // Where <alternative> can be single or multi-line (see above). Note also
    // that leading `*` and trailing comment can be on separate lines. Throw
    // manifest_parsing if the value is invalid.
    //
    // Use the dependent package name to verify that the reflect clauses in
    // the dependency alternative representations refer to the dependent
    // package configuration variable.
    //
    // Optionally, specify the stream name to use when creating the
    // manifest_parsing exception. The start line and column arguments can be
    // used to align the exception information with a containing stream. This
    // is useful when the alternatives representation is a part of some larger
    // text (manifest, etc).
    //
    // Note that semicolons inside alternatives must be escaped with the
    // backslash (not to be treated as the start of a comment). Backslashes at
    // the end of buildfile fragment lines need to also be escaped, if
    // dependency alternatives representation comes from the manifest file
    // (since trailing backslashes in manifest lines has special semantics).
    //
    explicit LIBBPKG_EXPORT
    dependency_alternatives (const std::string&,
                             const package_name& dependent,
                             const std::string& name = std::string (),
                             std::uint64_t line = 1,
                             std::uint64_t column = 1);

    LIBBPKG_EXPORT std::string
    string () const;

    // Return true if there is a conditional alternative in the list.
    //
    LIBBPKG_EXPORT bool
    conditional () const;
  };

  inline std::ostream&
  operator<< (std::ostream& os, const dependency_alternatives& das)
  {
    return os << das.string ();
  }

  // requires
  //
  // The requirement alternative string representation is similar to that of
  // the dependency alternative with the following differences:
  //
  // - The requirement id (with or without version) can mean anything (but
  //   must still be a valid package name).
  //
  // - Only the enable and reflect clauses are permitted (reflect is allowed
  //   for potential future support of recognized requirement alternatives,
  //   for example, C++ standard).
  //
  // - The simplified representation syntax, where the comment carries the
  //   main information and thus is mandatory, is also supported (see
  //   requirement_alternatives for details). For example:
  //
  //   requires: ; X11 libs.
  //   requires: ? ($windows) ; Only 64-bit.
  //   requires: ? ; Only 64-bit if on Windows.
  //   requires: x86_64 ? ; Only if on Windows.
  //
  class requirement_alternative: public butl::small_vector<std::string, 1>
  {
  public:
    butl::optional<std::string> enable;
    butl::optional<std::string> reflect;

    requirement_alternative () = default;
    requirement_alternative (butl::optional<std::string> e,
                             butl::optional<std::string> r)
        : enable (std::move (e)), reflect (std::move (r)) {}

    // Return the single-line representation if possible (the reflect clause
    // either absent or contains no newlines).
    //
    LIBBPKG_EXPORT std::string
    string () const;

    // Return true if the string() function would return the single-line
    // representation.
    //
    LIBBPKG_EXPORT bool
    single_line () const;

    // Return true if this is a single requirement with an empty id or an
    // empty enable condition.
    //
    bool
    simple () const
    {
      return size () == 1 && (back ().empty () || (enable && enable->empty ()));
    }
  };

  class requirement_alternatives:
    public butl::small_vector<requirement_alternative, 1>
  {
  public:
    bool buildtime;
    std::string comment;

    requirement_alternatives () = default;
    requirement_alternatives (bool b, std::string c)
        : buildtime (b), comment (std::move (c)) {}

    // Parse the requirement alternatives string representation in the
    // following forms:
    //
    // [*] <alternative> [ '|' <alternative>]* [; <comment>]
    // [*] [<requirement-id>] [? [<enable-condition>]] ; <comment>
    //
    // Parsing the second form ends up with a single alternative with a single
    // potentially empty requirement id, potentially with an enable condition
    // with potentially empty value (see examples above).
    //
    // Throw manifest_parsing if the value is invalid.
    //
    // Optionally, specify the stream name to use when creating the
    // manifest_parsing exception. The start line and column arguments can be
    // used to align the exception information with a containing stream. This
    // is useful when the alternatives representation is a part of some larger
    // text (manifest, etc).
    //
    explicit LIBBPKG_EXPORT
    requirement_alternatives (const std::string&,
                              const package_name& dependent,
                              const std::string& name = std::string (),
                              std::uint64_t line = 1,
                              std::uint64_t column = 1);

    LIBBPKG_EXPORT std::string
    string () const;

    // Return true if there is a conditional alternative in the list.
    //
    LIBBPKG_EXPORT bool
    conditional () const;

    // Return true if this is a single simple requirement alternative.
    //
    bool
    simple () const
    {
      return size () == 1 && back ().simple ();
    }
  };

  inline std::ostream&
  operator<< (std::ostream& os, const requirement_alternatives& ra)
  {
    return os << ra.string ();
  }

  class build_constraint
  {
  public:
    // If true, then the package should not be built for matching target
    // configurations by automated build bots.
    //
    bool exclusion;

    // Filesystem wildcard patterns for the build configuration name and
    // target.
    //
    std::string config;
    butl::optional<std::string> target;

    std::string comment;

    build_constraint () = default;
    build_constraint (bool e,
                      std::string n,
                      butl::optional<std::string> t,
                      std::string c)
        : exclusion (e),
          config (std::move (n)),
          target (std::move (t)),
          comment (std::move (c)) {}
  };

  // Package manifest value validation forbid/require flags.
  //
  // Some package manifest values can be forbidden or required for certain
  // repository types and in specific contexts (for example, when parsing an
  // individual manifest, a manifest list, etc).
  //
  // Also note that, naturally, the forbid_* and require_* flags are mutually
  // exclusive for the same value.
  //
  enum class package_manifest_flags: std::uint16_t
  {
    none                           = 0x000,

    forbid_file                    = 0x001, // Forbid *-file manifest values.
    forbid_location                = 0x002,
    forbid_sha256sum               = 0x004,
    forbid_fragment                = 0x008,
    forbid_incomplete_dependencies = 0x010,

    require_location               = 0x020,
    require_sha256sum              = 0x040,
    require_description_type       = 0x080,
    require_bootstrap_build        = 0x100
  };

  inline package_manifest_flags
  operator&= (package_manifest_flags& x, package_manifest_flags y)
  {
    return x = static_cast<package_manifest_flags> (
      static_cast<std::uint16_t> (x) &
      static_cast<std::uint16_t> (y));
  }

  inline package_manifest_flags
  operator|= (package_manifest_flags& x, package_manifest_flags y)
  {
    return x = static_cast<package_manifest_flags> (
      static_cast<std::uint16_t> (x) |
      static_cast<std::uint16_t> (y));
  }

  inline package_manifest_flags
  operator& (package_manifest_flags x, package_manifest_flags y)
  {
    return x &= y;
  }

  inline package_manifest_flags
  operator| (package_manifest_flags x, package_manifest_flags y)
  {
    return x |= y;
  }

  // Target build configuration class term.
  //
  class LIBBPKG_EXPORT build_class_term
  {
  public:
    char operation; // '+', '-' or '&'
    bool inverted;  // Operation is followed by '!'.
    bool simple;    // Name if true, expr otherwise.
    union
    {
      std::string                   name; // Class name.
      std::vector<build_class_term> expr; // Parenthesized expression.
    };

    // Create the simple term object (class name).
    //
    build_class_term (std::string n, char o, bool i)
        : operation (o), inverted (i), simple (true), name (std::move (n)) {}

    // Create the compound term object (parenthesized expression).
    //
    build_class_term (std::vector<build_class_term> e, char o, bool i)
        : operation (o), inverted (i), simple (false), expr (std::move (e)) {}

    // Required by VC for some reason.
    //
    build_class_term ()
        : operation ('\0'), inverted (false), simple (true), name () {}

    build_class_term (build_class_term&&);
    build_class_term (const build_class_term&);
    build_class_term& operator= (build_class_term&&);
    build_class_term& operator= (const build_class_term&);

    ~build_class_term ();

    // Check that the specified string is a valid class name, that is
    // non-empty, containing only alpha-numeric characters, '_', '+', '-', '.'
    // (except as the first character for the last three). Return true if the
    // name is reserved (starts with '_'). Throw std::invalid_argument if
    // invalid.
    //
    static bool
    validate_name (const std::string&);
  };

  // Map of derived build classes to their bases.
  //
  using build_class_inheritance_map = std::map<std::string, std::string>;

  // Target build configuration class expression. Includes comment and
  // optional underlying set.
  //
  class LIBBPKG_EXPORT build_class_expr
  {
  public:
    std::string comment;
    strings underlying_classes;
    std::vector<build_class_term> expr;

  public:
    build_class_expr () = default;

    // Parse the string representation of a space-separated build class
    // expression, potentially prepended with a space-separated underlying
    // build class set, in which case the expression can be empty. If both,
    // underlying class set and expression are present, then they should be
    // separated with the semicolon. Throw std::invalid_argument if the
    // representation is invalid. Some expression examples:
    //
    // +gcc
    // -msvc -clang
    // default leagacy
    // default leagacy :
    // default leagacy : -msvc
    // default leagacy : &gcc
    //
    build_class_expr (const std::string&, std::string comment);

    // Create the expression object from a class list (c1, c2, ...) using the
    // specified operation (+/-/&) according to the following rules:
    //
    // +  ->  +c1 +c2 ...
    // -  ->  -c1 -c2 ...
    // &  ->  &( +c1 +c2 ... )
    //
    // An empty class list results in an empty expression.
    //
    // Note: it is assumed that the class names are valid.
    //
    build_class_expr (const strings& classes,
                      char operation,
                      std::string comment);

    // Return the string representation of the build class expression,
    // potentially prepended with the underlying class set.
    //
    std::string
    string () const;

    // Match a target build configuration that belongs to the specified list
    // of classes (and recursively to their bases) against the expression.
    // Either return or update the result (the latter allows to sequentially
    // matching against a list of expressions).
    //
    // Notes:
    //
    // - The derived-to-base map is not verified (that there are no
    //   inheritance cycles, etc.).
    //
    // - The underlying class set doesn't affect the match in any way (it
    //   should have been used to pre-filter the set of target build
    //   configurations).
    //
    void
    match (const strings&,
           const build_class_inheritance_map&,
           bool& result) const;

    bool
    match (const strings& cs, const build_class_inheritance_map& bs) const
    {
      bool r (false);
      match (cs, bs, r);
      return r;
    }
  };

  inline std::ostream&
  operator<< (std::ostream& os, const build_class_expr& bce)
  {
    return os << bce.string ();
  }

  // Package build configuration. Includes comment and optional target build
  // configuration class expressions/constraints overrides.
  //
  class build_package_config
  {
  public:
    std::string name;

    // Whitespace separated list of potentially double/single-quoted package
    // configuration arguments for bpkg-pkg-build command executed by
    // automated build bots.
    //
    std::string arguments;

    std::string comment;

    butl::small_vector<build_class_expr, 1> builds;
    std::vector<build_constraint> constraints;

    build_package_config () = default;

    // Built incrementally.
    //
    explicit
    build_package_config (std::string n): name (move (n)) {}

    // Return the configuration's build class expressions/constraints if they
    // override the specified common expressions/constraints and return the
    // latter otherwise (see package_manifest::override() for the override
    // semantics details).
    //
    const butl::small_vector<build_class_expr, 1>&
    effective_builds (const butl::small_vector<build_class_expr, 1>& common)
      const noexcept
    {
      return !builds.empty () ? builds : common;
    }

    const std::vector<build_constraint>&
    effective_constraints (const std::vector<build_constraint>& common) const
      noexcept
    {
      return !builds.empty () || !constraints.empty () ? constraints : common;
    }
  };

  enum class text_type
  {
    plain,
    common_mark,
    github_mark
  };

  LIBBPKG_EXPORT std::string
  to_string (text_type);

  // Throw std::invalid_argument if the argument is not a well-formed text
  // type. Otherwise, return nullopt for an unknown text variant.
  //
  LIBBPKG_EXPORT butl::optional<text_type>
  to_text_type (const std::string&); // May throw std::invalid_argument.

  inline std::ostream&
  operator<< (std::ostream& os, text_type t)
  {
    return os << to_string (t);
  }

  enum class test_dependency_type
  {
    tests,
    examples,
    benchmarks
  };

  LIBBPKG_EXPORT std::string
  to_string (test_dependency_type);

  // May throw std::invalid_argument.
  //
  LIBBPKG_EXPORT test_dependency_type
  to_test_dependency_type (const std::string&);

  inline std::ostream&
  operator<< (std::ostream& os, test_dependency_type t)
  {
    return os << to_string (t);
  }

  struct LIBBPKG_EXPORT test_dependency: dependency
  {
    test_dependency_type type;
    bool buildtime;
    butl::optional<std::string> reflect;

    test_dependency () = default;
    test_dependency (package_name n,
                     test_dependency_type t,
                     bool b,
                     butl::optional<version_constraint> c,
                     butl::optional<std::string> r)
        : dependency {std::move (n), std::move (c)},
          type (t),
          buildtime (b),
          reflect (std::move (r)) {}

    // Parse the test dependency string representation in the
    // `[*] <name> [<version-constraint>] [<reflect-config>]` form. Throw
    // std::invalid_argument if the value is invalid.
    //
    // Verify that the reflect clause, if present, refers to the test
    // dependency package configuration variable. Note that such variable
    // value normally signals the dependent package being tested.
    //
    test_dependency (std::string, test_dependency_type);

    std::string
    string () const;
  };

  // Package's buildfile path and content.
  //
  struct buildfile
  {
    // The path is relative to the package's build/ subdirectory with the
    // extension stripped.
    //
    // For example, for the build/config/common.build file the path will be
    // config/common.
    //
    // Note that the actual file path depends on the project's buildfile
    // naming scheme and for the config/common example above the actual path
    // can also be build2/config/common.build2.
    //
    butl::path path;
    std::string content;

    buildfile () = default;
    buildfile (butl::path p, std::string c)
        : path (std::move (p)),
          content (std::move (c)) {}
  };

  class LIBBPKG_EXPORT package_manifest
  {
  public:
    using version_type = bpkg::version;
    using priority_type = bpkg::priority;
    using email_type = bpkg::email;

    package_name name;
    version_type version;
    butl::optional<std::string> upstream_version;
    butl::optional<package_name> project;
    butl::optional<priority_type> priority;
    std::string summary;

    butl::small_vector<licenses, 1> license_alternatives;
    butl::small_vector<std::string, 5> topics;
    butl::small_vector<std::string, 5> keywords;
    butl::optional<text_file> description;
    butl::optional<std::string> description_type;
    butl::small_vector<text_file, 1> changes;
    butl::optional<manifest_url> url;
    butl::optional<manifest_url> doc_url;
    butl::optional<manifest_url> src_url;
    butl::optional<manifest_url> package_url;
    butl::optional<email_type> email;
    butl::optional<email_type> package_email;
    butl::optional<email_type> build_email;
    butl::optional<email_type> build_warning_email;
    butl::optional<email_type> build_error_email;
    std::vector<dependency_alternatives> dependencies;
    std::vector<requirement_alternatives> requirements;
    butl::small_vector<test_dependency, 1> tests;

    // Common build classes/constraints that apply to all configurations
    // unless overridden.
    //
    butl::small_vector<build_class_expr, 1> builds;
    std::vector<build_constraint> build_constraints;

    // Note that the parsing constructor adds the implied (empty) default
    // configuration at the beginning of the list. Also note that serialize()
    // writes no values for such a configuration.
    //
    butl::small_vector<build_package_config, 1> build_configs; // 1 for default.

    // If true, then this package use the alternative buildfile naming scheme
    // (build2/, .build2). In the manifest serialization this is encoded as
    // either *-build or *-build2 value names.
    //
    butl::optional<bool> alt_naming;

    butl::optional<std::string> bootstrap_build;
    butl::optional<std::string> root_build;

    // Additional buildfiles which are potentially included by root.build.
    //
    std::vector<buildfile>  buildfiles;      // Buildfiles content.
    std::vector<butl::path> buildfile_paths;

    // The following values are only valid in the manifest list (and only for
    // certain repository types).
    //
    butl::optional<butl::path> location;
    butl::optional<std::string> sha256sum;
    butl::optional<std::string> fragment;

    const package_name&
    effective_project () const noexcept {return project ? *project : name;}

    // Return the description type value if present, text_type::github_mark if
    // the description refers to a file with the .md or .markdown extension
    // and text_type::plain if it refers to a file with the .txt extension or
    // no extension or the description does not come from a file. Depending on
    // the ignore_unknown value either throw std::invalid_argument or return
    // nullopt if the description value or the file extension is unknown.
    // Throw std::logic_error if the description value is nullopt.
    //
    butl::optional<text_type>
    effective_description_type (bool ignore_unknown = false) const;

  public:
    package_manifest () = default;

    // Create individual manifest.
    //
    // The default package_manifest_flags value corresponds to a valid
    // individual package manifest.
    //
    package_manifest (butl::manifest_parser&,
                      bool ignore_unknown = false,
                      bool complete_dependencies = true,
                      package_manifest_flags =
                        package_manifest_flags::forbid_location  |
                        package_manifest_flags::forbid_sha256sum |
                        package_manifest_flags::forbid_fragment);

    // As above but also call the translate function for the version value
    // passing through any exception it may throw. Throw std::invalid_argument
    // if the resulting version isn't a valid package version (empty, earliest
    // release, etc).
    //
    // In particular, the translation function may "patch" the version with
    // the snapshot information (see <libbutl/standard-version.hxx> for
    // details). This translation is normally required for manifests of
    // packages that are accessed as directories (as opposed to package
    // archives that should have their version already patched).
    //
    using translate_function = void (version_type&);

    package_manifest (butl::manifest_parser&,
                      const std::function<translate_function>&,
                      bool ignore_unknown = false,
                      bool complete_depends = true,
                      package_manifest_flags =
                        package_manifest_flags::forbid_location  |
                        package_manifest_flags::forbid_sha256sum |
                        package_manifest_flags::forbid_fragment);

    // As above but construct the package manifest from the pre-parsed
    // manifest values list.
    //
    // Note that the list is expected not to contain the format version nor
    // the end-of-manifest/stream pairs.
    //
    package_manifest (const std::string& name,
                      std::vector<butl::manifest_name_value>&&,
                      bool ignore_unknown = false,
                      bool complete_dependencies = true,
                      package_manifest_flags =
                        package_manifest_flags::forbid_location  |
                        package_manifest_flags::forbid_sha256sum |
                        package_manifest_flags::forbid_fragment);

    package_manifest (const std::string& name,
                      std::vector<butl::manifest_name_value>&&,
                      const std::function<translate_function>&,
                      bool ignore_unknown = false,
                      bool complete_depends = true,
                      package_manifest_flags =
                        package_manifest_flags::forbid_location  |
                        package_manifest_flags::forbid_sha256sum |
                        package_manifest_flags::forbid_fragment);

    // Create an element of the list manifest.
    //
    package_manifest (butl::manifest_parser&,
                      butl::manifest_name_value start,
                      bool ignore_unknown,
                      bool complete_depends,
                      package_manifest_flags);

    // Override manifest values with the specified. Throw manifest_parsing if
    // any value is invalid, cannot be overridden, or its name is not
    // recognized.
    //
    // The specified values override the whole groups they belong to,
    // resetting all the group values prior to being applied. Currently, only
    // the following value groups can be overridden:
    //
    //   {build-*email}
    //   {builds, build-{include,exclude}}
    //   {*-builds, *-build-{include,exclude}}
    //   {*-build-config}
    //
    // Throw manifest_parsing if the configuration specified by the build
    // package configuration-specific build constraints group value overrides
    // doesn't exists. In contrast, for the build config override add a new
    // configuration if it doesn't exist and update the arguments of the
    // existing configuration otherwise. In the former case, all the potential
    // build constraints overrides for such a newly added configuration must
    // follow the respective *-build-config override.
    //
    // Note that the build constraints group values (both common and build
    // config-specific) are overridden hierarchically so that the
    // [*-]build-{include,exclude} overrides don't affect the respective
    // [*-]builds values.
    //
    // Also note that the common and build config-specific build constraints
    // group value overrides are mutually exclusive. If the common build
    // constraints are overridden, then all the build config-specific
    // constraints are removed. Otherwise, if some build config-specific
    // constraints are overridden, then for the remaining configs the build
    // constraints are reset to `builds: none`.
    //
    // If a non-empty source name is specified, then the specified values are
    // assumed to also include the line/column information and the possibly
    // thrown manifest_parsing exception will contain the invalid value's
    // location information. Otherwise, the exception description will refer
    // to the invalid value instead.
    //
    void
    override (const std::vector<butl::manifest_name_value>&,
              const std::string& source_name);

    // Validate the overrides without applying them to any manifest.
    //
    // Specifically, validate that the override values can be parsed according
    // to their name semantics and that the value sequence makes sense (no
    // mutually exclusive values, etc). Note, however, that the subsequent
    // applying of the successfully validated overrides to a specific package
    // manifest may still fail (no build config exists for specified *-builds,
    // etc).
    //
    static void
    validate_overrides (const std::vector<butl::manifest_name_value>&,
                        const std::string& source_name);

    // If the minimum libbpkg version is specified, then also apply the
    // required backward compatibility workarounds to the serialized manifest
    // so that clients of all libbpkg versions greater or equal to the
    // specified version can parse it, ignoring unknown values.
    //
    // Note that clients of the latest major libbpkg version can fully
    // recognize the produced manifest and thus can parse it without ignoring
    // unknown values.
    //
    void
    serialize (
      butl::manifest_serializer&,
      const butl::optional<butl::standard_version>& = butl::nullopt) const;

    // Serialize only package manifest header values.
    //
    void
    serialize_header (butl::manifest_serializer&) const;

    // Load the *-file manifest values using the specified load function that
    // returns the file contents passing through any exception it may throw.
    // If nullopt is returned, then the respective *-file value is left
    // unexpanded. Set the potentially absent description type value to the
    // effective description type. If the effective type is nullopt then
    // assign a synthetic unknown type.
    //
    // Note that if the returned file contents is empty, load_files() makes
    // sure that this is allowed by the value's semantics throwing
    // manifest_parsing otherwise. However, the load function may want to
    // recognize such cases itself in order to issue more precise diagnostics.
    //
    using load_function =
      butl::optional<std::string> (const std::string& name,
                                   const butl::path& value);

    void
    load_files (const std::function<load_function>&,
                bool ignore_unknown = false);
  };

  // Create individual package manifest.
  //
  inline package_manifest
  pkg_package_manifest (butl::manifest_parser& p,
                        bool ignore_unknown = false,
                        bool complete_depends = true)
  {
    return package_manifest (p, ignore_unknown, complete_depends);
  }

  LIBBPKG_EXPORT package_manifest
  dir_package_manifest (butl::manifest_parser&, bool ignore_unknown = false);

  LIBBPKG_EXPORT package_manifest
  git_package_manifest (butl::manifest_parser&, bool ignore_unknown = false);

  // Create an element of the package list manifest.
  //
  LIBBPKG_EXPORT package_manifest
  pkg_package_manifest (butl::manifest_parser&,
                        butl::manifest_name_value start,
                        bool ignore_unknown = false);

  LIBBPKG_EXPORT package_manifest
  dir_package_manifest (butl::manifest_parser&,
                        butl::manifest_name_value start,
                        bool ignore_unknown = false);

  LIBBPKG_EXPORT package_manifest
  git_package_manifest (butl::manifest_parser&,
                        butl::manifest_name_value start,
                        bool ignore_unknown = false);

  // Serialize.
  //
  inline void
  pkg_package_manifest (
    butl::manifest_serializer& s,
    const package_manifest& m,
    const butl::optional<butl::standard_version>& min_ver = butl::nullopt)
  {
    m.serialize (s, min_ver);
  }

  // Normally there is no need to serialize dir and git package manifests,
  // unless for testing.
  //
  LIBBPKG_EXPORT void
  dir_package_manifest (butl::manifest_serializer&, const package_manifest&);

  LIBBPKG_EXPORT void
  git_package_manifest (butl::manifest_serializer&, const package_manifest&);

  class LIBBPKG_EXPORT pkg_package_manifests:
    public std::vector<package_manifest>
  {
  public:
    using base_type = std::vector<package_manifest>;

    using base_type::base_type;

    // Checksum of the corresponding repository_manifests.
    //
    std::string sha256sum;

  public:
    pkg_package_manifests () = default;
    pkg_package_manifests (butl::manifest_parser&,
                           bool ignore_unknown = false);

    // If the minimum libbpkg version is specified, then also apply the
    // required backward compatibility workarounds to the serialized package
    // manifests list (see package_manifest::serialize() for details).
    //
    void
    serialize (
      butl::manifest_serializer&,
      const butl::optional<butl::standard_version>& = butl::nullopt) const;
  };

  class LIBBPKG_EXPORT dir_package_manifests:
    public std::vector<package_manifest>
  {
  public:
    using base_type = std::vector<package_manifest>;

    using base_type::base_type;

  public:
    dir_package_manifests () = default;
    dir_package_manifests (butl::manifest_parser&,
                           bool ignore_unknown = false);

    // Normally there is no need to serialize dir package manifests, unless for
    // testing.
    //
    void
    serialize (butl::manifest_serializer&) const;
  };

  class LIBBPKG_EXPORT git_package_manifests:
    public std::vector<package_manifest>
  {
  public:
    using base_type = std::vector<package_manifest>;

    using base_type::base_type;

  public:
    git_package_manifests () = default;
    git_package_manifests (butl::manifest_parser&,
                           bool ignore_unknown = false);

    // Normally there is no need to serialize git package manifests, unless for
    // testing.
    //
    void
    serialize (butl::manifest_serializer&) const;
  };

  // Traits class for the repository URL object.
  //
  enum class repository_protocol {file, http, https, git, ssh};

  struct LIBBPKG_EXPORT repository_url_traits
  {
    using string_type = std::string;
    using path_type   = butl::path;

    using scheme_type    = repository_protocol;
    using authority_type = butl::basic_url_authority<string_type>;

    static butl::optional<scheme_type>
    translate_scheme (const string_type&,
                      string_type&&,
                      butl::optional<authority_type>&,
                      butl::optional<path_type>&,
                      butl::optional<string_type>&,
                      butl::optional<string_type>&,
                      bool&);

    static string_type
    translate_scheme (string_type&,
                      const scheme_type&,
                      const butl::optional<authority_type>&,
                      const butl::optional<path_type>&,
                      const butl::optional<string_type>&,
                      const butl::optional<string_type>&,
                      bool);

    static path_type
    translate_path (string_type&&);

    static string_type
    translate_path (const path_type&);
  };

  // Repository URL. Note that it represents both the remote (http(s)://,
  // git://, etc) and local (file:// as well as plain directory path)
  // repository URLs. May also be empty.
  //
  // Notes:
  //
  // - For an empty URL object all components are absent. For a non-empty one
  //   the path is always present and normalized. The string representation of
  //   non-empty object with non-empty path never contains the trailing slash
  //   (except for the root path on POSIX system).
  //
  // - For the remote URL object the host component is normalized (see
  //   butl::basic_url_host for details) and the path is relative.
  //
  // - For the local URL object the path can be relative or absolute. Query
  //   can not be present. Represent the object using the file:// notation if
  //   it is absolute and the authority or fragment is present. Otherwise
  //   represent it as a local path, appending the fragment if present.
  //
  // - repository_url(string) ctor throws std::invalid_argument exception for
  //   an empty string.
  //
  using repository_url = butl::basic_url<repository_protocol,
                                         repository_url_traits>;

  // Repository type.
  //
  enum class repository_type {pkg, dir, git};

  LIBBPKG_EXPORT std::string
  to_string (repository_type);

  LIBBPKG_EXPORT repository_type
  to_repository_type (const std::string&); // May throw std::invalid_argument.

  inline std::ostream&
  operator<< (std::ostream& os, repository_type t)
  {
    return os << to_string (t);
  }

  // Repository basis.
  //
  enum class repository_basis
  {
    archive,
    directory,
    version_control
  };

  // Guess the repository type from the URL:
  //
  // 1. If scheme is git then git.
  //
  // 2. If path has the .git extension then git.
  //
  // 3. If scheme is http(s) or ssh then pkg.
  //
  // 4. If local, check if directory contains the .git/ subdirectory then
  //    git, otherwise pkg.
  //
  // Can throw system_error in the later case.
  //
  LIBBPKG_EXPORT repository_type
  guess_type (const repository_url&, bool local);

  // Repository URL that may have a repository type specified as part of its
  // scheme in the [<type>'+']<protocol> form. For example:
  //
  // git+http://example.com/repo  (repository type + protocol)
  // git://example.com/repo       (protocol only)
  //
  // If the substring preceding the '+' character is not a valid repository
  // type or the part that follows doesn't conform to the repository URL
  // notation, then the whole string is considered to be a repository URL.
  // For example, for all of the following strings the repository URL is
  // untyped (local) and relative:
  //
  // foo+http://example.com/repo  (invalid repository type)
  // git+ftp://example.com/repo   (invalid repository protocol)
  // git+file://example.com/repo  (invalid authority)
  // git+c:/repo                  (not a URL notation)
  //
  // Note also that in quite a few manifests where we specify the location we
  // also allow specifying the type as a separate value. While this may seem
  // redundant (and it now is in a few cases, at least for the time being),
  // keep in mind that for the local relative path the type cannot be
  // specified as part of the URL (since its representation is a non-URL).
  //
  struct LIBBPKG_EXPORT typed_repository_url
  {
    repository_url url;
    butl::optional<repository_type> type;

    explicit
    typed_repository_url (const std::string&);
  };

  class LIBBPKG_EXPORT repository_location
  {
  public:
    // Create a special empty repository_location.
    //
    repository_location () = default;

    // Create a remote or absolute repository location from a potentially
    // typed repository URL (see above).
    //
    // If the type is not specified in the URL scheme then use the one passed
    // as an argument or, if not present, guess it according to the specified
    // local flag (see above). Throw std::invalid_argument if the argument
    // doesn't represent a valid remote or absolute repository location or
    // mismatching types are specified in the URL scheme and in the argument.
    // Underlying OS errors (which may happen when guessing the type when the
    // local flag is set) are reported by throwing std::system_error.
    //
    explicit
    repository_location (
      const std::string&,
      const butl::optional<repository_type>& = butl::nullopt,
      bool local = false);

    // Create remote, absolute or empty repository location making sure that
    // the URL matches the repository type. Throw std::invalid_argument if the
    // URL object is a relative local path.
    //
    // Note that the repository location string representation may differ from
    // the original URL in the presence of the trailing slash. This may cause
    // problems with some WEB servers that are sensitive to the trailing slash
    // presence/absence. For example:
    //
    // $ git clone http://git.sv.gnu.org/r/config.git
    //   warning: redirecting to http://git.savannah.gnu.org/r/config.git/
    //
    // Also note that we disregard the slash presence/absence on multiple
    // levels:
    //
    // - reduce absent path to an empty one in
    //   repository_url_traits::translate_scheme() (so a.com/ becomes a.com)
    //
    // - use path::*string() rather than path::*representation() functions
    //   in repository_url_traits::translate_*() functions
    //
    // - may append slash in repository_location ctor
    //
    repository_location (repository_url, repository_type);

    // Create a potentially relative repository location. If base is not
    // empty, use it to complete the relative location to the remote/absolute
    // one. Throw std::invalid_argument if base is not empty but the location
    // is empty, base itself is relative, or the resulting completed location
    // is invalid.
    //
    repository_location (repository_url,
                         repository_type,
                         const repository_location& base);

    repository_location (const repository_location& l,
                         const repository_location& base)
        : repository_location (l.url (), l.type (), base) {}

    // Note that relative locations have no canonical name. Canonical name of
    // an empty location is the empty name.
    //
    const std::string&
    canonical_name () const noexcept {return canonical_name_;}

    // There are 3 types of locations: remote, local absolute filesystem
    // path and local relative filesystem path. Plus there is the special
    // empty location. The following predicates can be used to determine
    // what kind of location it is. Note that except for empty(), all the
    // other predicates throw std::logic_error for an empty location.
    //
    bool
    empty () const noexcept {return url_.empty ();}

    bool
    local () const
    {
      if (empty ())
        throw std::logic_error ("empty location");

      return url_.scheme == repository_protocol::file;
    }

    bool
    remote () const
    {
      return !local ();
    }

    bool
    absolute () const
    {
      if (empty ())
        throw std::logic_error ("empty location");

      // Note that in remote locations path is always relative.
      //
      return url_.path->absolute ();
    }

    bool
    relative () const
    {
      return local () && url_.path->relative ();
    }

    repository_type
    type () const
    {
      if (empty ())
        throw std::logic_error ("empty location");

      return type_;
    }

    repository_basis
    basis () const
    {
      switch (type ())
      {
      case repository_type::pkg: return repository_basis::archive;
      case repository_type::dir: return repository_basis::directory;
      case repository_type::git: return repository_basis::version_control;
      }

      assert (false); // Can't be here.
      return repository_basis::archive;
    }

    // Note that the URL of an empty location is empty.
    //
    const repository_url&
    url () const
    {
      return url_;
    }

    // Repository path. Note that for repository types that refer to
    // "directories" it always contains the trailing slash.
    //
    const butl::path&
    path () const
    {
      if (empty ())
        throw std::logic_error ("empty location");

      return *url_.path;
    }

    const std::string&
    host () const
    {
      if (local ())
        throw std::logic_error ("local location");

      return url_.authority->host;
    }

    // Value 0 indicated that no port was specified explicitly.
    //
    std::uint16_t
    port () const
    {
      if (local ())
        throw std::logic_error ("local location");

      return url_.authority->port;
    }

    repository_protocol
    proto () const
    {
      if (empty ())
        throw std::logic_error ("empty location");

      return url_.scheme;
    }

    const butl::optional<std::string>&
    fragment () const
    {
      if (relative ())
        throw std::logic_error ("relative filesystem path");

      return url_.fragment;
    }

    bool
    archive_based () const
    {
      return basis () == repository_basis::archive;
    }

    bool
    directory_based () const
    {
      return basis () == repository_basis::directory;
    }

    bool
    version_control_based () const
    {
      return basis () == repository_basis::version_control;
    }

    // Return an untyped URL if the correct type can be guessed just from
    // the URL. Otherwise, return the typed URL.
    //
    // String representation is empty for an empty location and is always
    // untyped for the relative location (which is a non-URL).
    //
    std::string
    string () const;

  private:
    std::string canonical_name_;
    repository_url url_;
    repository_type type_;
  };

  inline std::ostream&
  operator<< (std::ostream& os, const repository_location& l)
  {
    return os << l.string ();
  }

  // Git refname/pattern and/or commit. If none of them is present then the
  // default reference set is assumed. If both are present then the commit is
  // expected to belong to the history of the specified refs (e.g., tag or
  // branch). Note that the name member can also be an abbreviated commit id
  // (full, 40-character commit ids should always be stored in the commit
  // member since they may refer to an unadvertised commit).
  //
  class LIBBPKG_EXPORT git_ref_filter
  {
  public:
    butl::optional<std::string> name;
    butl::optional<std::string> commit;
    bool exclusion = false;

  public:
    git_ref_filter () = default; // Default reference set.

    // Parse the [+|-][<name>][@<commit>] reference filter representation.
    // Throw std::invalid_argument if the string is empty or the filter
    // representation format is invalid.
    //
    explicit
    git_ref_filter (const std::string&);

    git_ref_filter (butl::optional<std::string> n,
                    butl::optional<std::string> c,
                    bool e)
        : name (std::move (n)),
          commit (std::move (c)),
          exclusion (e) {}

    bool
    default_refs () const {return !name && !commit;}
  };

  using git_ref_filters = butl::small_vector<git_ref_filter, 2>;

  // Parse a comma-separated list of git reference filters. If the argument
  // starts with the '#' character then prepend the resulting list with the
  // default reference set filter (see above). If the argument is absent then
  // return the list containing a single default reference set filter. Throw
  // std::invalid_argument if the filter list format is invalid.
  //
  LIBBPKG_EXPORT git_ref_filters
  parse_git_ref_filters (const butl::optional<std::string>&);

  enum class repository_role
  {
    base,
    prerequisite,
    complement
  };

  class LIBBPKG_EXPORT repository_manifest
  {
  public:
    using email_type = bpkg::email;

    repository_location location;         // Non-empy for non-base roles.
    butl::optional<repository_role> role;

    // The following values may only be present for the base repository (and
    // only for certain repository types).
    //
    butl::optional<std::string> url;
    butl::optional<email_type>  email;
    butl::optional<std::string> summary;
    butl::optional<std::string> description;
    butl::optional<std::string> certificate;

    // The repository fingerprint to trust. May only be present for the
    // prerequisite or complement repository and only for repository types
    // that support authentication (currently only pkg).
    //
    butl::optional<std::string> trust;

    // The repository fragment id this repository belongs to (may only be
    // present for multi-fragment repositories).
    //
    butl::optional<std::string> fragment;

    // Return the effective role of the repository. If the role is not
    // explicitly specified, then the base role is assumed.
    //
    repository_role
    effective_role () const noexcept
    {
      return role ? *role : repository_role::base;
    }

    // Return the effective web interface URL based on the specified remote
    // repository location. If url is not present, doesn't start with '.', or
    // the repository type differs from pkg, then return it unchanged.
    // Otherwise, process the relative format as described in the manifest
    // specification. Throw std::invalid_argument if the relative url format is
    // invalid or if the repository location is empty or local.
    //
    butl::optional<std::string>
    effective_url (const repository_location&) const;

  public:
    repository_manifest () = default; // VC export.

    void
    serialize (butl::manifest_serializer&) const;
  };

  // Create individual repository manifest.
  //
  LIBBPKG_EXPORT repository_manifest
  pkg_repository_manifest (butl::manifest_parser&,
                           bool ignore_unknown = false);

  LIBBPKG_EXPORT repository_manifest
  dir_repository_manifest (butl::manifest_parser&,
                           bool ignore_unknown = false);

  LIBBPKG_EXPORT repository_manifest
  git_repository_manifest (butl::manifest_parser&,
                           bool ignore_unknown = false);

  // Create an element of the repository list manifest.
  //
  LIBBPKG_EXPORT repository_manifest
  pkg_repository_manifest (butl::manifest_parser&,
                           butl::manifest_name_value start,
                           bool ignore_unknown = false);

  LIBBPKG_EXPORT repository_manifest
  dir_repository_manifest (butl::manifest_parser&,
                           butl::manifest_name_value start,
                           bool ignore_unknown = false);

  LIBBPKG_EXPORT repository_manifest
  git_repository_manifest (butl::manifest_parser&,
                           butl::manifest_name_value start,
                           bool ignore_unknown = false);

  struct repositories_manifest_header
  {
  public:
    butl::optional<butl::standard_version> min_bpkg_version;
    butl::optional<std::string>            compression;
  };

  class LIBBPKG_EXPORT pkg_repository_manifests:
    public std::vector<repository_manifest>
  {
  public:
    using base_type = std::vector<repository_manifest>;

    using base_type::base_type;

    butl::optional<repositories_manifest_header> header;

  public:
    pkg_repository_manifests () = default;
    pkg_repository_manifests (butl::manifest_parser&,
                              bool ignore_unknown = false);

    void
    serialize (butl::manifest_serializer&) const;
  };

  class LIBBPKG_EXPORT dir_repository_manifests:
    public std::vector<repository_manifest>
  {
  public:
    using base_type = std::vector<repository_manifest>;

    using base_type::base_type;

    butl::optional<repositories_manifest_header> header;

  public:
    dir_repository_manifests () = default;
    dir_repository_manifests (butl::manifest_parser&,
                              bool ignore_unknown = false);

    void
    serialize (butl::manifest_serializer&) const;
  };

  class LIBBPKG_EXPORT git_repository_manifests:
    public std::vector<repository_manifest>
  {
  public:
    using base_type = std::vector<repository_manifest>;

    using base_type::base_type;

    butl::optional<repositories_manifest_header> header;

  public:
    git_repository_manifests () = default;
    git_repository_manifests (butl::manifest_parser&,
                              bool ignore_unknown = false);

    void
    serialize (butl::manifest_serializer&) const;
  };

  // Search a repository manifest list for the base repository and return its
  // reference, if found. Otherwise, return a reference to an empty manifest
  // instance (which is the representation of the default base).
  //
  LIBBPKG_EXPORT const repository_manifest&
  find_base_repository (const std::vector<repository_manifest>&) noexcept;

  class LIBBPKG_EXPORT signature_manifest
  {
  public:
    // Checksum of the corresponding package_manifests.
    //
    std::string sha256sum;

    // Signature of the corresponding package_manifests. Calculated by
    // encrypting package_manifests checksum (stored in sha256sum) with the
    // repository certificate private key.
    //
    std::vector<char> signature;

  public:
    signature_manifest () = default;
    signature_manifest (butl::manifest_parser&, bool ignore_unknown = false);

    // Serialize sha256sum and base64-encoded representation of the signature.
    //
    void
    serialize (butl::manifest_serializer&) const;

  private:
    // Used for delegating in public constructor. Strictly speaking is not
    // required, as a signature_manifest currently never appears as a part of
    // a manifest list, but kept for the consistency with other manifests
    // implementations.
    //
    signature_manifest (butl::manifest_parser&,
                        butl::manifest_name_value start,
                        bool ignore_unknown);
  };

  // Extract the package name component from <name>[/<version>] or
  // <name><version-constraint>. Throw invalid_argument on parsing error.
  //
  // Note: the version and version constraint are not verified.
  //
  LIBBPKG_EXPORT package_name
  extract_package_name (const char*, bool allow_version = true);

  inline package_name
  extract_package_name (const std::string& s, bool allow_version = true)
  {
    return extract_package_name (s.c_str (), allow_version);
  }

  // Extract the package version component from <name>[/<version>]. Return
  // empty version if none is specified. Throw invalid_argument on parsing
  // error and for the earliest and stub versions.
  //
  // Note: the package name is not verified.
  //
  LIBBPKG_EXPORT version
  extract_package_version (const char*,
                           version::flags fl = version::fold_zero_revision);

  inline version
  extract_package_version (const std::string& s,
                           version::flags fl = version::fold_zero_revision)
  {
    return extract_package_version (s.c_str (), fl);
  }
}

#endif // LIBBPKG_MANIFEST_HXX