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
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
use std::collections::BTreeMap;
use std::fs;
use std::path;

use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
pub enum FlatpakManifestFormat {
    JSON,
    YAML,
}
impl Default for FlatpakManifestFormat {
    fn default() -> Self {
        FlatpakManifestFormat::YAML
    }
}

lazy_static! {
    static ref REVERSE_DNS_FILENAME_REGEX: Regex = Regex::new(
        r"[a-z][a-z][a-z]*\.[a-z][0-9a-zA-Z_\-]+\.[a-z][0-9a-zA-Z_\-]+(\.[a-z][0-9a-zA-Z_\-]+)*\.(json|yaml|yml)$"
    ).unwrap();
}

lazy_static! {
    pub static ref KNOWN_GENERATED_SOURCES_PATHS: Vec<String> = vec![
        "cargo-sources.json".to_string(),
        "generated-sources.json".to_string(),
        // For the go generator, the default is <module-name>-sources.json
        "-sources.json".to_string(),
        "python2-modules.json".to_string(),
        "python3-modules.json".to_string(),
        "python2-requirements.json".to_string(),
        "python3-requirements.json".to_string(),
        "pypi-dependencies.json".to_string(),
        "generated-poetry-sources.json".to_string(),
        "rubygems.json".to_string(),
    ];
}

/// Main structure for a Flatpak application manifest.
/// See `man flatpak-manifest` for the flatpak manifest specs.
#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Default)]
#[serde(rename_all = "kebab-case")]
#[serde(default)]
pub struct FlatpakManifest {
    #[serde(skip_serializing)]
    pub format: FlatpakManifestFormat,

    /// Name of the application.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub app_name: String,

    /// A string defining the application id.
    /// Both names (app-id and id) are accepted.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub app_id: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub id: String,

    /// The branch to use when exporting the application.
    /// If this is unset the defaults come from the default-branch option.
    ///
    /// This key overrides both the default-branch key, and the --default-branch commandline option.
    /// Unless you need a very specific branchname (like for a runtime or an extension) it is recommended
    /// to use the default-branch key instead, because you can then override the default using
    /// --default-branch when building for instance a test build.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub branch: String,

    /// The default branch to use when exporting the application. Defaults to master.
    /// This key can be overridden by the --default-branch commandline option.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub default_branch: String,

    /// The collection ID of the repository, defaults to being unset.
    /// Setting a globally unique collection ID allows the apps in the
    /// repository to be shared over peer to peer systems without needing further configuration.
    /// If building in an existing repository, the collection ID must match the existing
    /// configured collection ID for that repository.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub collection_id: String,

    /// The name of the runtime that the application uses.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub runtime: String,

    /// The version of the runtime that the application uses, defaults to master.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub runtime_version: String,

    /// The name of the development runtime that the application builds with.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub sdk: String,

    /// The name of the development extensions that the application requires to build.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sdk_extensions: Vec<String>,

    /// Initialize the (otherwise empty) writable /var in the build with a copy of this runtime.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub var: String,

    /// Use this file as the base metadata file when finishing.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub metadata: String,

    /// Build a new runtime instead of an application.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build_runtime: Option<bool>,

    /// Whether the manifest describes an extension to be used by other manifests.
    /// Extensions can be used to bundle programming langages and their associated
    /// tools, for example.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build_extension: Option<bool>,

    /// Start with the files from the specified application.
    /// This can be used to create applications that extend another application.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub base: String,

    /// Use this specific version of the application specified in base.
    /// If unspecified, this uses the value specified in branch
    #[serde(skip_serializing_if = "String::is_empty")]
    pub base_version: String,

    /// Install these extra extensions from the base application when
    /// initializing the application directory.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub base_extensions: Vec<String>,

    /// Inherit these extra extensions points from the base application or
    /// sdk when finishing the build.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub inherit_extensions: Vec<String>,

    /// Inherit these extra extensions points from the base application or sdk
    /// when finishing the build, but do not inherit them into the platform.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub inherit_sdk_extensions: Vec<String>,

    /// Inherit these extra extensions points from the base application or sdk when finishing the build,
    /// but do not inherit them into the platform.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build_options: Option<FlatpakBuildOptions>,

    /// The name of the command that the flatpak should run on execution.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,

    /// Add these tags to the metadata file.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,

    /// This is a dictionary of extension objects.
    /// The key is the name of the extension.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub add_extensions: BTreeMap<String, FlatpakExtension>,

    /// This is a dictionary of extension objects similar to add-extensions.
    /// The main difference is that the extensions are added early and are
    /// available for use during the build.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub add_build_extensions: BTreeMap<String, FlatpakExtension>,

    /// An array of file patterns that should be removed at the end.
    /// Patterns starting with / are taken to be full pathnames (without the /app prefix),
    /// otherwise they just match the basename.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cleanup: Vec<String>,

    /// An array of commandlines that are run during the cleanup phase.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cleanup_commands: Vec<String>,

    /// Extra files to clean up in the platform.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cleanup_platform: Vec<String>,

    /// An array of commandlines that are run during the cleanup phase of the platform.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cleanup_platform_commands: Vec<String>,

    /// An array of commandlines that are run after importing the base platform,
    /// but before applying the new files from the sdk. This is a good place to e.g. delete
    /// things from the base that may conflict with the files added in the sdk.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub prepare_platform_commands: Vec<String>,

    /// An array of arguments passed to the flatpak build-finish command.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub finish_args: Vec<String>,

    /// Any desktop file with this name will be renamed to a name
    /// based on id during the cleanup phase.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub rename_desktop_file: String,

    /// Any appdata file with this name will be renamed to a name based
    /// on id during the cleanup phase.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub rename_appdata_file: String,

    /// Any icon with this name will be renamed to a name based on id during
    /// the cleanup phase. Note that this is the icon name, not the full filenames,
    /// so it should not include a filename extension.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub rename_icon: String,

    /// Replace the appdata project-license field with this string.
    /// This is useful as the upstream license is typically only about
    /// the application itself, whereas the bundled app can contain other
    /// licenses too.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub appdata_license: String,

    /// If rename-icon is set, keep a copy of the old icon file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub copy_icon: Option<bool>,

    /// This string will be prefixed to the Name key in the main application desktop file.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub desktop_file_name_prefix: String,

    /// This string will be suffixed to the Name key in the main application desktop file.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub desktop_file_name_suffix: String,

    /// An array of strings specifying the modules to be built in order.
    /// String members in the array are interpreted as the name of a separate
    /// json or yaml file that contains a module. See below for details.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub modules: Vec<FlatpakModule>,
}
impl FlatpakManifest {
    pub fn get_id(&self) -> String {
        if !self.app_id.is_empty() {
            return self.app_id.to_string();
        }
        return self.id.to_string();
    }

    pub fn load_from_file(path: String) -> Result<FlatpakManifest, String> {
        let file_path = path::Path::new(&path);
        if !file_path.is_file() {
            return Err(format!("{} is not a file.", path));
        }

        if FlatpakManifest::file_path_matches(&file_path.to_str().unwrap()) {
            let manifest_content = match fs::read_to_string(file_path) {
                Ok(content) => content,
                Err(e) => {
                    return Err(format!(
                        "Could not read file {}: {}!",
                        file_path.to_str().unwrap(),
                        e
                    ))
                }
            };

            let manifest = match FlatpakManifest::parse(&path, &manifest_content) {
                Ok(m) => m,
                Err(e) => return Err(format!("Failed to parse Flatpak manifest at {}: {}", path, e)),
            };

            return Ok(manifest);
        } else {
            return Err(format!("{} is not a Flatpak manifest.", path));
        }
    }

    pub fn file_extension_matches(path: &str) -> bool {
        if path.to_lowercase().ends_with("yml") || path.to_lowercase().ends_with("yaml") {
            return true;
        }
        if path.to_lowercase().ends_with("json") {
            return true;
        }
        return false;
    }

    pub fn file_path_matches(path: &str) -> bool {
        REVERSE_DNS_FILENAME_REGEX.is_match(&path.to_lowercase())
    }

    pub fn parse(manifest_path: &str, manifest_content: &str) -> Result<FlatpakManifest, String> {
        let mut flatpak_manifest: FlatpakManifest = FlatpakManifest::default();

        if manifest_path.to_lowercase().ends_with("yaml") || manifest_path.to_lowercase().ends_with("yml") {
            flatpak_manifest = match serde_yaml::from_str(&manifest_content) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
            flatpak_manifest.format = FlatpakManifestFormat::YAML;
        } else if manifest_path.to_lowercase().ends_with("json") {
            let json_content_without_comments = crate::utils::remove_comments_from_json(manifest_content);
            flatpak_manifest = match serde_json::from_str(&json_content_without_comments) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
            flatpak_manifest.format = FlatpakManifestFormat::JSON;
        }

        // From https://docs.flatpak.org/en/latest/manifests.html#basic-properties:
        // Each manifest file should specify basic information about the application that is to be built,
        // including the app-id, runtime, runtime-version, sdk and command parameters.
        // That being said, the `command` field is not required by manifests that declare an
        // extension to be build, using the `build-extension` field.
        if flatpak_manifest.app_id.is_empty() && flatpak_manifest.id.is_empty() {
            return Err(
                "Required top-level field id (or app-id) is missing from Flatpak manifest.".to_string(),
            );
        }
        if flatpak_manifest.runtime.is_empty() {
            return Err("Required top-level field runtime is missing from Flatpak manifest.".to_string());
        }
        if flatpak_manifest.runtime_version.is_empty() {
            return Err(
                "Required top-level field runtime-version is missing from Flatpak manifest.".to_string(),
            );
        }
        if flatpak_manifest.sdk.is_empty() {
            return Err("Required top-level field sdk is missing from Flatpak manifest.".to_string());
        }

        Ok(flatpak_manifest)
    }

    pub fn dump(&self) -> Result<String, String> {
        if let FlatpakManifestFormat::JSON = self.format {
            return match serde_json::to_string_pretty(&self) {
                Ok(d) => Ok(d),
                Err(e) => return Err(format!("Failed to dump the Flatpak manifest: {}.", e)),
            };
        }

        if let FlatpakManifestFormat::YAML = self.format {
            return match serde_yaml::to_string(&self) {
                Ok(d) => Ok(d),
                Err(e) => return Err(format!("Failed to dump the Flatpak manifest: {}.", e)),
            };
        }

        Err(format!("Invalid format for Flatpak manifest."))
    }

    pub fn get_all_module_urls(&self) -> Vec<String> {
        let mut all_urls = vec![];
        for module in &self.modules {
            let module: &FlatpakModuleDescription = match module {
                FlatpakModule::Path(_) => continue,
                FlatpakModule::Description(m) => &m,
            };
            all_urls.append(&mut module.get_all_urls());
        }
        all_urls
    }

    pub fn get_main_module_url(&self) -> Option<String> {
        let main_module = match self.modules.last() {
            Some(m) => m,
            None => return None,
        };
        let main_module: &FlatpakModuleDescription = match main_module {
            FlatpakModule::Path(_) => return None,
            FlatpakModule::Description(m) => m,
        };
        return main_module.get_main_url();
    }

    pub fn get_max_depth(&self) -> i32 {
        let mut max_depth: i32 = 1;
        for module in &self.modules {
            if let FlatpakModule::Description(module_description) = module {
                let module_depth = module_description.get_max_depth();
                if module_depth > max_depth {
                    max_depth = module_depth;
                }
            }
        }
        return max_depth;
    }

    pub fn is_extension(&self) -> bool {
        if let Some(e) = self.build_extension {
            return e;
        }
        false
    }

    pub fn get_all_modules_recursively(&self) -> Vec<&FlatpakModule> {
        let mut all_modules: Vec<&FlatpakModule> = vec![];
        for module in &self.modules {
            all_modules.push(module);

            let module = match module {
                FlatpakModule::Description(d) => d,
                FlatpakModule::Path(_) => continue,
            };
            for child_module in module.get_all_modules_recursively() {
                all_modules.push(child_module);
            }
        }
        all_modules
    }
}

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Hash)]
#[serde(rename_all = "kebab-case")]
#[serde(untagged)]
/// Each module item can be either a path to a module description file,
/// or an inline module description.
pub enum FlatpakModule {
    Path(String),
    Description(FlatpakModuleDescription),
}
impl FlatpakModule {
    pub fn get_all_repos_urls(&self) -> Vec<String> {
        if let FlatpakModule::Description(module_description) = self {
            return module_description.get_all_urls();
        } else {
            return vec![];
        }
    }
}

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Default)]
#[derive(Hash)]
#[serde(rename_all = "kebab-case")]
#[serde(default)]
/// Each module specifies a source that has to be separately built and installed.
/// It contains the build options and a list of sources to download and extract before
/// building.
///
/// Modules can be nested, in order to turn related modules on and off with a single key.
pub struct FlatpakModuleDescription {
    /// The name of the module, used in e.g. build logs. The name is also
    /// used for constructing filenames and commandline arguments,
    /// therefore using spaces or '/' in this string is a bad idea.
    pub name: String,

    /// If true, skip this module
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,

    /// An array of objects defining sources that will be downloaded and extracted in order.
    /// String members in the array are interpreted as the name of a separate
    /// json or yaml file that contains sources. See below for details.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sources: Vec<FlatpakSource>,

    /// An array of options that will be passed to configure
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub config_opts: Vec<String>,

    /// An array of arguments that will be passed to make
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub make_args: Vec<String>,

    /// An array of arguments that will be passed to make install
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub make_install_args: Vec<String>,

    /// If true, remove the configure script before starting build
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rm_configure: Option<bool>,

    /// Ignore the existence of an autogen script
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_autogen: Option<bool>,

    /// Don't call make with arguments to build in parallel
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_parallel_make: Option<bool>,

    /// Name of the rule passed to make for the install phase, default is install
    #[serde(skip_serializing_if = "String::is_empty")]
    pub install_rule: String,

    /// Don't run the make install (or equivalent) stage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_make_install: Option<bool>,

    /// Don't fix up the python (*.pyo or *.pyc) header timestamps for ostree use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_python_timestamp_fix: Option<bool>,

    /// Use cmake instead of configure (deprecated: use buildsystem instead)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cmake: Option<bool>,

    /// Build system to use.
    /// See [`static@crate::build_systems::FLATPAK_BUILD_SYSTEMS`] for available values.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub buildsystem: String,

    /// Use a build directory that is separate from the source directory
    #[serde(skip_serializing_if = "Option::is_none")]
    pub builddir: Option<bool>,

    /// Build inside this subdirectory of the extracted sources
    #[serde(skip_serializing_if = "String::is_empty")]
    pub subdir: String,

    /// A build options object that can override global options
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build_options: Option<FlatpakBuildOptions>,

    /// An array of commands to run during build (between make and make install if those are used).
    /// This is primarily useful when using the "simple" buildsystem.
    /// Each command is run in /bin/sh -c, so it can use standard POSIX shell syntax such as piping output.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub build_commands: Vec<String>,

    /// An array of shell commands that are run after the install phase.
    /// Can for example clean up the install dir, or install extra files.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub post_install: Vec<String>,

    /// An array of file patterns that should be removed at the end.
    /// Patterns starting with / are taken to be full pathnames (without the /app prefix), otherwise
    /// they just match the basename. Note that any patterns will only match
    /// files installed by this module.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cleanup: Vec<String>,

    /// The way the builder works is that files in the install directory are hard-links to the cached files,
    /// so you're not allowed to modify them in-place. If you list a file in this then the hardlink
    /// will be broken and you can modify it. This is a workaround, ideally installing files should
    /// replace files, not modify existing ones.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ensure_writable: Vec<String>,

    /// If non-empty, only build the module on the arches listed.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub only_arches: Vec<String>,

    /// Don't build on any of the arches listed.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub skip_arches: Vec<String>,

    /// Extra files to clean up in the platform.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cleanup_platform: Vec<String>,

    /// If true this will run the tests after installing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_tests: Option<bool>,

    /// The target to build when running the tests. Defaults to "check" for make and "test" for ninja.
    /// Set to empty to disable.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub test_rule: String,

    /// Array of commands to run during the tests.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub test_commands: Vec<String>,

    /// An array of objects specifying nested modules to be built before this one.
    /// String members in the array are interpreted as names of a separate json or
    /// yaml file that contains a module.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub modules: Vec<FlatpakModule>,
}
impl FlatpakModuleDescription {
    pub fn uses_external_data_checker(&self) -> bool {
        for source in &self.sources {
            let source_description = match source {
                FlatpakSource::Description(d) => d,
                FlatpakSource::Path(_) => continue,
            };
            if source_description.x_checker_data.is_some() {
                return true;
            }
        }
        return false;
    }

    pub fn get_all_mirror_urls(&self) -> Vec<String> {
        let mut all_urls = vec![];
        for module in &self.modules {
            if let FlatpakModule::Description(module_description) = module {
                all_urls.append(&mut module_description.get_all_mirror_urls());
            }
        }
        for source in &self.sources {
            for url in source.get_all_mirror_urls() {
                all_urls.push(url.to_string());
            }
        }
        all_urls
    }

    pub fn get_buildsystem(&self) -> Option<String> {
        if !self.buildsystem.is_empty() {
            return Some(self.buildsystem.to_string());
        }
        if self.cmake.unwrap_or(false) {
            return Some(crate::build_systems::CMAKE.to_string());
        }
        return None;
    }

    pub fn is_patched(&self) -> bool {
        for source in &self.sources {
            if let FlatpakSource::Description(sd) = source {
                if let Some(t) = &sd.r#type {
                    if t == "patch" {
                        return true;
                    }
                }
            }
        }
        false
    }

    pub fn load_from_file(path: String) -> Result<FlatpakModuleDescription, String> {
        let file_path = path::Path::new(&path);
        if !file_path.is_file() {
            return Err(format!("{} is not a file.", path));
        }

        if FlatpakModuleDescription::file_path_matches(&file_path.to_str().unwrap()) {
            let module_content = match fs::read_to_string(file_path) {
                Ok(content) => content,
                Err(e) => {
                    return Err(format!(
                        "Could not read file {}: {}!",
                        file_path.to_str().unwrap(),
                        e
                    ));
                }
            };
            let module = match FlatpakModuleDescription::parse(&path, &module_content) {
                Ok(m) => m,
                Err(e) => return Err(format!("Failed to parse Flatpak module at {}: {}", path, e)),
            };
            return Ok(module);
        } else {
            return Err(format!("{} is not a Flatpak module.", path));
        }
    }

    pub fn parse(module_path: &str, module_content: &str) -> Result<FlatpakModuleDescription, String> {
        let mut flatpak_module: FlatpakModuleDescription = FlatpakModuleDescription::default();

        if module_path.to_lowercase().ends_with("yaml") || module_path.to_lowercase().ends_with("yml") {
            flatpak_module = match serde_yaml::from_str(&module_content) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
        } else if module_path.to_lowercase().ends_with("json") {
            let json_content_without_comments = crate::utils::remove_comments_from_json(module_content);
            flatpak_module = match serde_json::from_str(&json_content_without_comments) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
        }

        if flatpak_module.name.is_empty() {
            return Err("Required top-level field name is missing from Flatpak module.".to_string());
        }
        if flatpak_module.sources.is_empty() {
            return Err("Required sources were not found in Flatpak module.".to_string());
        }
        for source in &flatpak_module.sources {
            let source_path = match source {
                FlatpakSource::Description(_) => continue,
                FlatpakSource::Path(p) => p,
            };
            // The string elements of the source array should only be FS paths, not
            // URLs or anything else.
            if source_path.starts_with("http://") || source_path.starts_with("https://") {
                return Err("Sources provided as strings cannot be URLs!".to_string());
            }
        }

        Ok(flatpak_module)
    }

    pub fn dump(&self) -> Result<String, String> {
        return match serde_yaml::to_string(&self) {
            Ok(d) => Ok(d),
            Err(e) => Err(format!("Failed to dump the Flatpak manifest: {}.", e)),
        };
    }

    pub fn file_path_matches(path: &str) -> bool {
        return FlatpakManifest::file_extension_matches(path);
    }

    pub fn get_all_urls(&self) -> Vec<String> {
        let mut all_urls = vec![];
        for module in &self.modules {
            if let FlatpakModule::Description(module_description) = module {
                all_urls.append(&mut module_description.get_all_urls());
            }
        }
        for source in &self.sources {
            for url in source.get_all_urls() {
                all_urls.push(url);
            }
        }
        all_urls
    }

    pub fn get_all_archive_urls(&self) -> Vec<String> {
        let mut all_archive_urls = vec![];
        for source in &self.sources {
            if source.get_type_name() != "archive" {
                continue;
            }

            let source_description = match &source {
                FlatpakSource::Path(_) => continue,
                FlatpakSource::Description(d) => d,
            };

            let archive_url = match &source_description.url {
                Some(u) => u,
                None => continue,
            };
            all_archive_urls.push(archive_url.to_string());
        }
        all_archive_urls
    }

    pub fn get_all_git_urls(&self) -> Vec<String> {
        let mut all_git_urls = vec![];
        for source in &self.sources {
            if source.get_type_name() != "git" {
                continue;
            }

            let source_description = match &source {
                FlatpakSource::Path(_) => continue,
                FlatpakSource::Description(d) => d,
            };

            let git_url = match &source_description.url {
                Some(u) => u,
                None => continue,
            };

            all_git_urls.push(git_url.to_string());
        }
        all_git_urls
    }

    pub fn get_max_depth(&self) -> i32 {
        let mut max_depth: i32 = 0;
        for module in &self.modules {
            if let FlatpakModule::Description(module_description) = module {
                let module_depth = module_description.get_max_depth();
                if module_depth > max_depth {
                    max_depth = module_depth;
                }
            }
        }
        return max_depth + 1;
    }

    pub fn get_main_url(&self) -> Option<String> {
        if self.sources.len() < 1 {
            return None;
        }

        // Here we assume that the first source is the actual project, and
        // anything after is a patch or an additional file.
        let main_module_source = self.sources.first().unwrap();

        let main_module_source_url: Option<String> = main_module_source.get_url();

        match &main_module_source_url {
            Some(s) => Some(s.to_string()),
            None => None,
        }
    }

    pub fn get_all_modules_recursively(&self) -> Vec<&FlatpakModule> {
        let mut all_modules: Vec<&FlatpakModule> = vec![];
        let mut next_modules: Vec<&FlatpakModule> = vec![];
        for module in &self.modules {
            next_modules.push(module);
        }
        while !next_modules.is_empty() {
            let module = next_modules.pop().unwrap();
            all_modules.push(module);

            let module = match module {
                FlatpakModule::Description(d) => d,
                FlatpakModule::Path(_) => continue,
            };
            for next_module in &module.modules {
                next_modules.push(next_module);
            }
        }
        all_modules
    }
}

lazy_static! {
    pub static ref SOURCE_TYPES: Vec<String> = vec![
        "archive".to_string(),
        "git".to_string(),
        "bzr".to_string(),
        "svn".to_string(),
        "dir".to_string(),
        "file".to_string(),
        "script".to_string(),
        "shell".to_string(),
        "patch".to_string(),
        "extra-data".to_string(),
    ];
    pub static ref CODE_TYPES: Vec<String> = vec![
        "archive".to_string(),
        "git".to_string(),
        "bzr".to_string(),
        "svn".to_string(),
        "dir".to_string(),
    ];
    pub static ref VCS_TYPES: Vec<String> = vec!["git".to_string(), "bzr".to_string(), "svn".to_string(),];
}

pub const DEFAULT_SOURCE_TYPE: &str = "archive";

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Hash)]
#[serde(rename_all = "kebab-case")]
#[serde(untagged)]
/// The sources are a list pointer to the source code that needs to be extracted into
/// the build directory before the build starts.
/// They can be of several types, distinguished by the type property.
///
/// Additionally, the sources list can contain a plain string, which is interpreted as the name
/// of a separate json or yaml file that is read and inserted at this
/// point. The file can contain a single source, or an array of sources.
pub enum FlatpakSource {
    Path(String),
    Description(FlatpakSourceDescription),
}
impl FlatpakSource {
    pub fn get_url(&self) -> Option<String> {
        let source_description = match self {
            FlatpakSource::Path(_) => return None,
            FlatpakSource::Description(sd) => sd,
        };
        match &source_description.url {
            Some(s) => Some(s.to_string()),
            None => None,
        }
    }

    pub fn get_all_mirror_urls(&self) -> Vec<String> {
        let mut response: Vec<String> = vec![];

        let source_description = match self {
            FlatpakSource::Path(_) => return response,
            FlatpakSource::Description(sd) => sd,
        };
        if let Some(urls) = &source_description.mirror_urls {
            for url in urls {
                response.push(url.to_string());
            }
        }
        return response;
    }

    pub fn get_all_urls(&self) -> Vec<String> {
        let mut response: Vec<String> = vec![];
        let source_description = match self {
            FlatpakSource::Path(_) => return response,
            FlatpakSource::Description(sd) => sd,
        };
        if let Some(url) = &source_description.url {
            response.push(url.to_string());
        }
        if let Some(urls) = &source_description.mirror_urls {
            for url in urls {
                response.push(url.to_string());
            }
        }
        return response;
    }

    pub fn get_type_name(&self) -> String {
        return match self {
            FlatpakSource::Path(_) => "path".to_string(),
            FlatpakSource::Description(d) => {
                if let Some(t) = &d.r#type {
                    return t.to_string();
                }
                return "empty".to_string();
            }
        };
    }

    pub fn has_commit(&self) -> bool {
        return match self {
            FlatpakSource::Path(_) => false,
            FlatpakSource::Description(d) => d.commit.is_some(),
        };
    }

    pub fn has_tag(&self) -> bool {
        return match self {
            FlatpakSource::Path(_) => false,
            FlatpakSource::Description(d) => d.tag.is_some(),
        };
    }

    pub fn has_branch(&self) -> bool {
        return match self {
            FlatpakSource::Path(_) => false,
            FlatpakSource::Description(d) => d.branch.is_some(),
        };
    }

    pub fn type_is_valid(&self) -> bool {
        return match self {
            FlatpakSource::Path(_) => true,
            FlatpakSource::Description(d) => {
                if let Some(t) = &d.r#type {
                    return SOURCE_TYPES.contains(&t);
                }
                return false;
            }
        };
    }

    pub fn type_is_empty(&self) -> bool {
        return match self {
            FlatpakSource::Path(_) => false,
            FlatpakSource::Description(d) => d.r#type.is_none(),
        };
    }

    pub fn supports_mirror_urls(&self) -> bool {
        let type_name = self.get_type_name();
        // FIXME why are mirror urls not supported for types git, svn and bzr.
        if type_name == "archive" || type_name == "file" {
            return true;
        }
        return false;
    }
}

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Default)]
#[derive(Hash)]
#[serde(rename_all = "kebab-case")]
/// These contain a pointer to the source that will be extracted into the
/// source directory before the build starts. They can be of several types,
/// distinguished by the type property.
pub struct FlatpakSourceDescription {
    /// Defines the type of the source description.
    /// It is not explicit in the flatpak-manifest man page,
    /// but we only found 1 source in all our dataset with an empty
    /// type, so we assume that the field is actually required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<String>,

    /// An array of shell commands.
    /// types: script, shell
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commands: Option<Vec<String>>,

    /// Filename to use inside the source dir.
    /// types: script, archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dest_filename: Option<String>,

    /// The name to use for the downloaded extra data
    /// types: extra-data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,

    /// The url to the resource.
    /// types: extra-data, svn, bzr, git, archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// A list of alternative urls that are used if the main url fails.
    /// types: archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mirror_urls: Option<Vec<String>>,

    /// The md5 checksum of the file, verified after download
    /// Note that md5 is no longer considered a safe checksum, we recommend you use at least sha256.
    /// types: archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub md5: Option<String>,

    /// The sha1 checksum of the file, verified after download
    /// Note that sha1 is no longer considered a safe checksum, we recommend you use at least sha256.
    /// types: archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sha1: Option<String>,

    /// The sha256 of the resource.
    /// types: extra-data, archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sha256: Option<String>,

    /// The sha512 checksum of the file, verified after download
    /// types: archive, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sha512: Option<String>,

    /// The size of the extra data in bytes.
    /// types: extra-data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<i64>,

    /// Whether to initialise the repository as a git repository.
    /// types: archive
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_init: Option<bool>,

    /// The extra installed size this adds to the app (optional).
    /// types: extra-data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub installed_size: Option<i64>,

    /// A specific revision number to use
    /// types: svn, bzr
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,

    /// The branch to use from the git repository
    /// types: git
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,

    /// The type of archive if it cannot be guessed from the path.
    /// Possible values are:
    ///   * "rpm",
    ///   * "tar",
    ///   * "tar-gzip",
    ///   * "tar-compress",
    ///   * "tar-bzip2",
    ///   * "tar-lzip",
    ///   * "tar-lzma",
    ///   * "tar-lzop",
    ///   * "tar-xz",
    ///   * "zip",
    ///   * "7z",
    /// types: archive
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archive_type: Option<String>,

    /// The commit to use from the git repository.
    /// If branch is also specified, then it is verified that the branch/tag is at this specific commit.
    /// This is a readable way to document that you're using a particular tag,
    /// but verify that it does not change.
    /// types: git
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit: Option<String>,

    /// The tag to use from the git repository
    /// types: git
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,

    /// The path to associated with the resource.
    /// types: git, archive, dir, patch, file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,

    /// An list of paths to a patch files that will be applied in the source dir, in order
    /// types: patch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub paths: Option<Vec<String>>,

    /// Whether to use "git apply" rather than "patch" to apply the patch, required when the
    /// patch file contains binary diffs.
    /// types: patch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_git: Option<bool>,

    /// Whether to use "git am" rather than "patch" to apply the patch, required when the patch
    /// file contains binary diffs.
    /// You cannot use this at the same time as use-git.
    /// types: patch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_git_am: Option<bool>,

    /// Extra options to pass to the patch command.
    /// types: patch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<Vec<String>>,

    /// Don't use transfer.fsckObjects=1 to mirror git repository. This may be needed for some
    /// (broken) repositories.
    /// types: git
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_fsckobjects: Option<bool>,

    /// Don't optimize by making a shallow clone when downloading the git repo.
    /// types: git
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_shallow_clone: Option<bool>,

    /// Don't checkout the git submodules when cloning the repository.
    /// types: git
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_submodules: Option<bool>,

    /// The number of initial pathname components to strip.
    /// defaults to 1.
    /// types: archive, patch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strip_components: Option<i64>,

    /// Source files to ignore in the directory.
    /// types: dir
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skip: Option<Vec<String>>,

    /// If non-empty, only build the module on the arches listed.
    /// types: all
    #[serde(skip_serializing_if = "Option::is_none")]
    pub only_arches: Option<Vec<String>>,

    /// Don't build on any of the arches listed.
    /// types: all
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skip_arches: Option<Vec<String>>,

    /// Directory inside the source dir where this source will be extracted.
    /// types: all
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dest: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub x_checker_data: Option<FlatpakDataCheckerConfig>,
}
impl FlatpakSourceDescription {
    // The logic of this functions is based on the code from BuilderArchiveType.get_type
    // in the flatpak-builder project.
    pub fn detect_archive_type(url: &str) -> Option<String> {
        let url = url.to_lowercase();
        if url.ends_with(".tar") {
            return Some("tar".to_string());
        }
        if url.ends_with(".tar.gz") || url.ends_with(".tgz") || url.ends_with(".taz") {
            return Some("tar-gzip".to_string());
        }
        if url.ends_with(".tar.z") || url.ends_with(".taz") {
            return Some("tar-compress".to_string());
        }
        if url.ends_with(".tar.bz2") || url.ends_with(".tz2") {
            return Some("tar-bzip2".to_string());
        }
        if url.ends_with(".tbz2") || url.ends_with(".tbz") {
            return Some("tar-bzip2".to_string());
        }
        if url.ends_with(".tar.lz") {
            return Some("tar-lzip".to_string());
        }
        if url.ends_with(".tar.lzma") || url.ends_with(".tlz") {
            return Some("tar-lzma".to_string());
        }
        if url.ends_with(".tar.lzo") {
            return Some("tar-lzop".to_string());
        }
        if url.ends_with(".tar.xz") || url.ends_with(".txz") {
            return Some("tar-xz".to_string());
        }
        if url.ends_with(".zip") {
            return Some("zip".to_string());
        }
        if url.ends_with(".rpm") {
            return Some("rpm".to_string());
        }
        if url.ends_with(".7z") {
            return Some("sevenz".to_string());
        }
        None
    }

    pub fn file_path_matches(path: &str) -> bool {
        return FlatpakManifest::file_extension_matches(path);
    }

    pub fn load_from_file(path: String) -> Result<Vec<FlatpakSourceDescription>, String> {
        let file_path = path::Path::new(&path);
        if !file_path.is_file() {
            return Err(format!("{} is not a file.", path));
        }

        if FlatpakSourceDescription::file_path_matches(&file_path.to_str().unwrap()) {
            let source_content = match fs::read_to_string(file_path) {
                Ok(content) => content,
                Err(e) => {
                    return Err(format!(
                        "Could not read file {}: {}!",
                        file_path.to_str().unwrap(),
                        e
                    ))
                }
            };

            // A standalone source manifest can contain a single source, or an array
            // of sources!!
            if let Ok(source) = FlatpakSourceDescription::parse(&path, &source_content) {
                return Ok(vec![source]);
            }
            if let Ok(sources) = FlatpakSourceDescription::parse_many(&path, &source_content) {
                return Ok(sources);
            }

            return Err(format!("Failed to parse Flatpak source at {}.", path));
        } else {
            return Err(format!("{} is not a Flatpak module.", path));
        }
    }

    pub fn parse(source_path: &str, source_content: &str) -> Result<FlatpakSourceDescription, String> {
        let mut flatpak_source: FlatpakSourceDescription = FlatpakSourceDescription::default();

        if source_path.to_lowercase().ends_with("yaml") || source_path.to_lowercase().ends_with("yml") {
            flatpak_source = match serde_yaml::from_str(&source_content) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
        } else if source_path.to_lowercase().ends_with("json") {
            let json_content_without_comments = crate::utils::remove_comments_from_json(source_content);
            flatpak_source = match serde_json::from_str(&json_content_without_comments) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
        }

        if let Err(e) = flatpak_source.is_valid() {
            return Err(e);
        }
        Ok(flatpak_source)
    }

    pub fn parse_many(
        source_path: &str,
        source_content: &str,
    ) -> Result<Vec<FlatpakSourceDescription>, String> {
        let mut flatpak_sources: Vec<FlatpakSourceDescription> = vec![];

        if source_path.to_lowercase().ends_with("yaml") || source_path.to_lowercase().ends_with("yml") {
            flatpak_sources = match serde_yaml::from_str(&source_content) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
        } else if source_path.to_lowercase().ends_with("json") {
            let json_content_without_comments = crate::utils::remove_comments_from_json(source_content);
            flatpak_sources = match serde_json::from_str(&json_content_without_comments) {
                Ok(m) => m,
                Err(e) => {
                    return Err(format!("Failed to parse the Flatpak manifest: {}.", e));
                }
            };
        }

        for flatpak_source in &flatpak_sources {
            if let Err(e) = flatpak_source.is_valid() {
                return Err(e);
            }
        }
        Ok(flatpak_sources)
    }

    pub fn is_valid(&self) -> Result<(), String> {
        if self.r#type.is_none() {
            return Err("Required top-level field type is missing from Flatpak source.".to_string());
        }
        if let Some(source_type) = &self.r#type {
            if !SOURCE_TYPES.contains(&source_type) {
                return Err(format!("Invalid source type {}.", source_type));
            }
        }
        Ok(())
    }
}

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Default)]
#[derive(Hash)]
#[serde(rename_all = "kebab-case")]
#[serde(default)]
/// See <https://github.com/flathub/flatpak-external-data-checker#changes-to-flatpak-manifests>
/// for the specification
pub struct FlatpakDataCheckerConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub version_pattern: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_main_source: Option<bool>,
}

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Default)]
#[serde(rename_all = "kebab-case")]
#[serde(default)]
/// Extension define extension points in the app/runtime that can be implemented by extensions,
/// supplying extra files which are available during runtime.
///
/// Additionally the standard flatpak extension properties are supported, and put
/// directly into the metadata file: autodelete, no-autodownload, subdirectories,
/// add-ld-path, download-if, enable-if, merge-dirs, subdirectory-suffix, locale-subset,
/// version, versions. See the flatpak metadata documentation for more information on these.
pub struct FlatpakExtension {
    /// The directory where the extension is mounted. If the extension point is for an application,
    /// this path is relative to /app, otherwise it is relative to /usr.
    pub extension_directory: String,

    /// If this is true, then the data created in the extension directory is omitted from the result,
    /// and instead packaged in a separate extension.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bundle: Option<bool>,

    /// If this is true, the extension is removed during when finishing.
    /// This is only interesting for extensions in the add-build-extensions property.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remove_after_build: Option<bool>,

    /// Whether to automatically delete extensions matching this extension point
    /// when deleting a 'related' application or runtime.
    pub autodelete: Option<bool>,

    /// Whether to automatically download extensions matching this extension point
    /// when updating or installing a 'related' application or runtime.
    pub no_autodownload: Option<bool>,

    /// If this key is set to true, then flatpak will look for extensions whose name is a
    /// prefix of the extension point name, and mount them at the corresponding
    /// name below the subdirectory.
    pub subdirectories: Option<bool>,

    /// A path relative to the extension point directory that will be appended to LD_LIBRARY_PATH.
    pub add_ld_path: Option<String>,

    /// A list of conditions, separated by semi-colons, that must be true for the extension
    /// to be auto-downloaded.
    /// These are the supported conditions:
    ///  active-gl-driver
    ///     Is true if the name of the active GL driver matches the extension point basename.
    ///  active-gtk-theme
    ///     Is true if the name of the current GTK theme (via org.gnome.desktop.interface GSetting)
    ///     matches the extension point basename.
    ///  have-intel-gpu
    ///     Is true if the i915 kernel module is loaded.
    ///  on-xdg-desktop-*
    ///     Is true if the suffix (case-insensitively) is in the XDG_CURRENT_DESKTOP env var.
    ///     For example on-xdg-desktop-GNOME-classic.
    pub download_if: Option<String>,

    /// A list of conditions, separated by semi-colons, that must be true for the extension to be
    /// enabled. See download_if for available conditions.
    pub enable_if: Option<String>,

    /// A list of relative paths of directories below the extension point directory that will be merged.
    pub merge_dirs: Option<String>,

    /// A suffix that gets appended to the directory name.
    /// This is very useful when the extension point naming scheme is "reversed".
    /// For example, an extension point for GTK+ themes would be /usr/share/themes/$NAME/gtk-3.0,
    /// which could be achieved using subdirectory-suffix=gtk-3.0.
    pub subdirectory_suffix: Option<String>,

    /// If set, then the extensions are partially downloaded by default, based on the currently
    /// configured locales. This means that the extension contents should be
    /// a set of directories with the language code as name.
    pub locale_subset: Option<bool>,

    /// The branch to use when looking for the extension.
    /// If this is not specified, it defaults to the branch of the application or
    /// runtime that the extension point is for.
    pub version: Option<String>,

    /// The branches to use when looking for the extension.
    /// If this is not specified, it defaults to the branch of the application or
    /// runtime that the extension point is for.
    pub versions: Option<String>,
}

#[derive(Clone)]
#[derive(Deserialize)]
#[derive(Serialize)]
#[derive(Debug)]
#[derive(Default)]
#[derive(Hash)]
#[serde(rename_all = "kebab-case")]
#[serde(default)]
/// Build options specify the build environment of a module,
/// and can be specified globally as well as per-module.
/// Options can also be specified on a per-architecture basis using the arch property.
pub struct FlatpakBuildOptions {
    /// This is set in the environment variable CFLAGS during the build.
    /// Multiple specifications of this (in e.g. per-arch area) are concatenated, separated by spaces.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub cflags: String,

    /// If this is true, clear cflags from previous build options before adding it from these options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cflags_override: Option<bool>,

    /// This is set in the environment variable CPPFLAGS during the build.
    /// Multiple specifications of this (in e.g. per-arch area) are concatenated, separated by spaces.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub cppflags: String,

    /// If this is true, clear cppflags from previous build options before adding it from these options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cppflags_override: Option<bool>,

    /// This is set in the environment variable CXXFLAGS during the build.
    /// Multiple specifications of this (in e.g. per-arch area) are concatenated, separated by spaces.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub cxxflags: String,

    /// If this is true, clear cxxflags from previous build options before adding it from these options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cxxflags_override: Option<bool>,

    /// This is set in the environment variable LDFLAGS during the build.
    /// Multiple specifications of this (in e.g. per-arch area) are concatenated,
    /// separated by spaces.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub ldflags: String,

    /// If this is true, clear ldflags from previous build options before adding it from these options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ldflags_override: Option<bool>,

    /// The build prefix for the modules (defaults to /app for applications and /usr for runtimes).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub prefix: String,

    /// The build libdir for the modules (defaults to /app/lib for applications and /usr/lib for runtimes).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub libdir: String,

    /// This will get appended to PATH in the build environment (with an leading colon if needed).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub append_path: String,

    /// This will get prepended to PATH in the build environment (with an trailing colon if needed).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub prepend_path: String,

    /// This will get appended to LD_LIBRARY_PATH in the build environment (with an leading colon if needed).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub append_ld_library_path: String,

    /// This will get prepended to LD_LIBRARY_PATH in the build environment (with an trailing colon if needed).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub prepend_ld_library_path: String,

    /// This will get appended to PKG_CONFIG_PATH in the build environment (with an leading colon if needed).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub append_pkg_config_path: String,

    /// This will get prepended to PKG_CONFIG_PATH in the build environment (with an trailing colon if needed).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub prepend_pkg_config_path: String,

    // This is a dictionary defining environment variables to be set during the build.
    // Elements in this override the properties that set the environment, like
    // cflags and ldflags. Keys with a null value unset the corresponding variable.
    // FIXME the doc says this should be an object, but when defined in the modules,
    // it is actually an array with values like PPC_CONFIG_PATH=/app/etc.
    // pub env: BTreeMap<String, String>,
    /// This is an array containing extra options to pass to flatpak build.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub build_args: Vec<String>,

    /// Similar to build-args but affects the tests, not the normal build.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub test_args: Vec<String>,

    /// This is an array containing extra options to pass to configure.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub config_opts: Vec<String>,

    /// An array of extra arguments that will be passed to make
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub make_args: Vec<String>,

    /// An array of extra arguments that will be passed to make install
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub make_install_args: Vec<String>,

    /// If this is true (the default is false) then all ELF files will be stripped after install.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strip: Option<bool>,

    /// By default (if strip is not true) flatpak-builder extracts all debug info in ELF files to a
    /// separate files and puts this in an extension. If you want to disable this, set no-debuginfo
    /// to true.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_debuginfo: Option<bool>,

    /// By default when extracting debuginfo we compress the debug sections.
    /// If you want to disable this, set no-debuginfo-compression to true.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_debuginfo_compression: Option<bool>,

    /// This is a dictionary defining for each arch a separate build options object that override the main one.
    pub arch: BTreeMap<String, FlatpakBuildOptions>,
}

#[cfg(test)]
mod manifest_tests {
    use super::*;

    #[test]
    pub fn test_file_path_matches() {
        assert!(FlatpakManifest::file_path_matches("com.example.appName.yaml"));
        assert!(FlatpakManifest::file_path_matches("COM.EXAMPLE.APPNAME.YAML"));
        assert!(FlatpakManifest::file_path_matches(
            "io.github.user.repo.Devel.yaml"
        ));
        assert!(FlatpakManifest::file_path_matches(
            "/path/to/com.example.appName.yaml"
        ));
        assert!(FlatpakManifest::file_path_matches(
            "/path/to/com.example.appName.yml"
        ));
        assert!(FlatpakManifest::file_path_matches(
            "/path/to/com.example.department.product.yaml"
        ));
        assert!(FlatpakManifest::file_path_matches(
            "/path/to/com.example.department.name-of-product.yaml"
        ));
        assert!(FlatpakManifest::file_path_matches(
            "contrib/linux/com.dosbox_x.DOSBox-X.yaml"
        ));
        assert!(!FlatpakManifest::file_path_matches(
            "/tmp/com.github.flathub.org.freedesktop.LinuxAudio.Plugins.WolfShaper/flathub.json"
        ));
        assert!(!FlatpakManifest::file_path_matches("Firefox-62.0.3.update.json"));
        assert!(!FlatpakManifest::file_path_matches("/path/to/file.yaml"));
        assert!(!FlatpakManifest::file_path_matches("/path/to/file.json"));
        assert!(!FlatpakManifest::file_path_matches("/path/to/___432423fdsf.json"));
        assert!(!FlatpakManifest::file_path_matches("/path/to/example.com.json"));
        assert!(!FlatpakManifest::file_path_matches("/path/to/example.com.json."));
        assert!(!FlatpakManifest::file_path_matches(""));
        assert!(!FlatpakManifest::file_path_matches("/////////////"));
    }

    #[test]
    #[should_panic]
    pub fn test_parse_invalid_yaml() {
        FlatpakManifest::parse("manifest.yaml", "----------------------------").unwrap();
    }

    #[test]
    pub fn test_parse_missing_fields() {
        assert!(FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            "###
        )
        .is_err());
    }

    #[test]
    pub fn test_parse() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.louib.flatpak-review
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            tags: ["nightly"]
            modules:
              -
                name: "flatpak-review"
                buildsystem: simple
                cleanup: [ "*" ]
                config-opts: []
                sources:
                  -
                    type: git
                    url: https://github.com/louib/flatpak-review.git
                    branch: master
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.louib.flatpak-review");
            }
        }
    }

    #[test]
    pub fn test_parse_shared_modules() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.louib.flatpak-review
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            tags: ["nightly"]
            modules:
              -
                name: "flatpak-review"
                buildsystem: simple
                cleanup: [ "*" ]
                config-opts: []
                sources:
                  -
                    type: git
                    url: https://github.com/louib/flatpak-review.git
                    branch: master
              -
                "shared-modules/linux-audio/lv2.json"
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.louib.flatpak-review");
            }
        }
    }

    #[test]
    pub fn test_parse_add_extensions() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.pcsx2.PCSX2
            runtime: org.freedesktop.Platform
            runtime-version: "19.08"
            sdk: org.freedesktop.Sdk
            command: PCSX2
            tags: ["nightly"]
            modules: []
            add-extensions:
                "org.freedesktop.Platform.Compat.i386":
                    directory: "lib/i386-linux-gnu"
                    version: "19.08"
                "org.freedesktop.Platform.Compat.i386.Debug":
                    directory: "lib/debug/lib/i386-linux-gnu"
                    version: "19.08"
                    no-autodownload: true
                "org.freedesktop.Platform.GL32":
                    directory: "lib/i386-linux-gnu/GL"
                    version: "1.4"
                    versions: "19.08;1.4"
                    subdirectories: true
                    no-autodownload: true
                    autodelete: false
                    add-ld-path: "lib"
                    merge-dirs: "vulkan/icd.d;glvnd/egl_vendor.d"
                    download-if: "active-gl-driver"
                    enable-if: "active-gl-driver"
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.pcsx2.PCSX2");
                assert_eq!(manifest.add_extensions.len(), 3);
            }
        }
    }

    #[test]
    pub fn test_parse_string_source() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.louib.flatpak-review
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            tags: ["nightly"]
            modules:
              -
                name: "flatpak-review"
                buildsystem: simple
                cleanup: [ "*" ]
                config-opts: []
                sources:
                  -
                    "shared-modules/linux-audio/lv2.json"
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.louib.flatpak-review");
            }
        }
    }

    #[test]
    pub fn test_parse_source_without_type() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.louib.flatpak-review
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            tags: ["nightly"]
            modules:
              -
                name: "gcc"
                buildsystem: simple
                cleanup: [ "*" ]
                config-opts: []
                sources:
                  -
                    url: "https://ftp.gnu.org/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.xz"
                    sha256: "b81946e7f01f90528a1f7352ab08cc602b9ccc05d4e44da4bd501c5a189ee661"

            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.louib.flatpak-review");
            }
        }
    }

    #[test]
    pub fn test_parse_build_options() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.louib.flatpak-review
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            tags: ["nightly"]
            modules:
              -
                name: "flatpak-review"
                buildsystem: simple
                cleanup: [ "*" ]
                build-options:
                   cflags: "-O2 -g"
                   cxxflags: "-O2 -g"
                   env:
                       V: "1"
                   arch:
                       x86_64:
                           cflags: "-O3 -g"
                config-opts: []
                sources:
                  -
                    "shared-modules/linux-audio/lv2.json"
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.louib.flatpak-review");
            }
        }
    }

    #[test]
    pub fn test_parse_script_source() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: net.louib.flatpak-review
            runtime: org.gnome.Platform
            runtime-version: "3.36"
            sdk: org.gnome.Sdk
            command: flatpak-review
            tags: ["nightly"]
            modules:
              -
                name: "flatpak-review"
                buildsystem: simple
                cleanup: [ "*" ]
                config-opts: []
                sources:
                  -
                    url: "https://ftp.gnu.org/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.xz"
                    sha256: "b81946e7f01f90528a1f7352ab08cc602b9ccc05d4e44da4bd501c5a189ee661"
                  -
                    type: "shell"
                    commands:
                      -
                        sed -i -e 's/\${\${NAME}_BIN}-NOTFOUND/\${NAME}_BIN-NOTFOUND/' cpp/CMakeLists.txt
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "net.louib.flatpak-review");
            }
        }
    }

    #[test]
    pub fn test_parse_json() {
        match FlatpakManifest::parse(
            "manifest.json",
            r###"
            {
                "app-id": "org.gnome.SoundJuicer",
                "runtime": "org.gnome.Platform",
                "runtime-version": "master",
                "sdk": "org.gnome.Sdk",
                "command": "sound-juicer",
                "tags": [ "nightly" ],
                "desktop-file-name-suffix": " ☢️",
                "finish-args": [
                    "--talk-name=org.gtk.vfs", "--talk-name=org.gtk.vfs.*",
                    "--env=GST_PLUGIN_PATH=/app/lib/codecs/lib/gstreamer-1.0"
                ],
                "cleanup": [ "/include", "/share/bash-completion" ],
                "modules": [
                    {
                        "name": "cdparanoia",
                        "buildsystem": "simple",
                        "build-commands": [
                            "cp /usr/share/automake-*/config.{sub,guess} .",
                            "./configure --prefix=/app",
                            "make all slib",
                            "make install"
                        ],
                        "sources": [
                            {
                                "type": "archive",
                                "url": "http://downloads.xiph.org/releases/cdparanoia/cdparanoia-III-10.2.src.tgz",
                                "sha256": "005db45ef4ee017f5c32ec124f913a0546e77014266c6a1c50df902a55fe64df"
                            },
                            {
                                "type": "patch",
                                "path": "cdparanoia-use-proper-gnu-config-files.patch"
                            }
                        ]
                    },
                    {
                        "name": "gst-plugins-base",
                        "buildsystem": "meson",
                        "config-opts": [
                            "--prefix=/app",
                            "-Dauto_features=disabled",
                            "-Dcdparanoia=enabled"
                        ],
                        "cleanup": [ "*.la", "/share/gtk-doc" ],
                        "sources": [
                            {
                                "type": "git",
                                "url": "https://gitlab.freedesktop.org/gstreamer/gst-plugins-base.git",
                                "branch" : "1.16.2",
                                "commit" : "9d3581b2e6f12f0b7e790d1ebb63b90cf5b1ef4e"
                            }
                        ]
                    }
                ]
            }
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "org.gnome.SoundJuicer");
            }
        }
    }

    #[test]
    pub fn test_parse_json_with_comments() {
        match FlatpakManifest::parse(
            "manifest.json",
            r###"
            {
                "app-id": "org.gnome.SoundJuicer",
                "runtime": "org.gnome.Platform",
                "runtime-version": "master",
                "sdk": "org.gnome.Sdk",
                "command": "sound-juicer",
                "tags": [ "nightly" ],
                "desktop-file-name-suffix": " ☢️",
                "finish-args": [
                    /* X11 + XShm access */
                    "--share=ipc", "--socket=fallback-x11",
                    /* Wayland access */
                    "--socket=wayland",
                    /* audio CDs */
                    "--device=all",
                    /* Needs to talk to the network */
                    "--share=network",
                    /* Play sounds */
                    "--socket=pulseaudio",
                    /* Browse user's Music directory */
                    "--filesystem=xdg-music",
                    /* Migrate DConf settings from the host */
                    "--metadata=X-DConf=migrate-path=/org/gnome/sound-juicer/",
                    /* optical media detection */
                    "--talk-name=org.gtk.vfs", "--talk-name=org.gtk.vfs.*",
                    /* Ensure cdda gstreamer plugin is picked found for audio CD's */
                    "--env=GST_PLUGIN_PATH=/app/lib/codecs/lib/gstreamer-1.0"
                ],
                "cleanup": [ "/include", "/share/bash-completion" ],
                "modules": [
                    /* gst-plugins-base needs cdparanoia to add support for cdda */
                    {
                        "name": "cdparanoia",
                        "buildsystem": "simple",
                        "build-commands": [
                            "cp /usr/share/automake-*/config.{sub,guess} .",
                            "./configure --prefix=/app",
                            "make all slib",
                            "make install"
                        ],
                        "sources": [
                            {
                                "type": "archive",
                                "url": "http://downloads.xiph.org/releases/cdparanoia/cdparanoia-III-10.2.src.tgz",
                                "sha256": "005db45ef4ee017f5c32ec124f913a0546e77014266c6a1c50df902a55fe64df"
                            },
                            {
                                "type": "patch",
                                "path": "cdparanoia-use-proper-gnu-config-files.patch"
                            }
                        ]
                    },
                    /* To play cdda */
                    {
                        "name": "gst-plugins-base",
                        "buildsystem": "meson",
                        "config-opts": [
                            "--prefix=/app",
                            "-Dauto_features=disabled",
                            "-Dcdparanoia=enabled"
                        ],
                        "cleanup": [ "*.la", "/share/gtk-doc" ],
                        "sources": [
                            {
                                "type": "git",
                                "url": "https://gitlab.freedesktop.org/gstreamer/gst-plugins-base.git",
                                "branch" : "1.16.2",
                                "commit" : "9d3581b2e6f12f0b7e790d1ebb63b90cf5b1ef4e"
                            }
                        ]
                    }
                ]
            }
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "org.gnome.SoundJuicer");
            }
        }
    }

    #[test]
    pub fn test_parse_json_with_multi_line_comments() {
        match FlatpakManifest::parse(
            "manifest.json",
            r###"
            {
              "app-id": "org.gnome.Lollypop",
              "runtime": "org.gnome.Platform",
              "runtime-version": "40",
              "sdk": "org.gnome.Sdk",
              "command": "lollypop",
              "finish-args": [
                "--share=ipc",
                "--own-name=org.mpris.MediaPlayer2.Lollypop",
                "--metadata=X-DConf=migrate-path=/org/gnome/Lollypop/"
              ],
              /* FFmpeg-full and gst-plugins-ugly required for .wma support
               * Due to possible legal stubbornness in the USA, it can't be downloaded automatically
               */
              "add-extensions": {
                "org.freedesktop.Platform.ffmpeg-full": {
                  "directory": "lib/ffmpeg",
                  "version": "20.08",
                  "add-ld-path": ".",
                  "no-autodownload": true,
                  "autodelete": false
                }
              },
              "cleanup-commands": [
                "mkdir -p /app/lib/ffmpeg"
              ],
              "modules": [
                "pypi-dependencies.json",
                {
                  "name": "gst-plugins-ugly",
                  "buildsystem": "meson",
                  "cleanup": [
                    "*.la",
                    "/share/gtk-doc"
                  ],
                  "sources": [{
                    "type": "archive",
                    "url": "https://gstreamer.freedesktop.org/src/gst-plugins-ugly/gst-plugins-ugly-1.16.2.tar.xz",
                    "sha256": "5500415b865e8b62775d4742cbb9f37146a50caecfc0e7a6fc0160d3c560fbca"
                  }]
                }
              ]
            }
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "org.gnome.Lollypop");
            }
        }
    }

    #[test]
    pub fn test_parse_extension() {
        match FlatpakManifest::parse(
            "manifest.json",
            r###"
            {
                "id": "org.freedesktop.Platform.Icontheme.Paper",
                "branch": "1.0",
                "runtime": "org.freedesktop.Sdk",
                "build-extension": true,
                "sdk": "org.freedesktop.Sdk",
                "runtime-version": "1.6",
                "sdk-extensions": [],
                "separate-locales": false,
                "cleanup": [ "/share/info", "/share/man" ],
                "appstream-compose": false,
                "build-options" : {
                    "prefix": "/usr/share/runtime"
                },
                "modules": []
            }
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.id, "org.freedesktop.Platform.Icontheme.Paper");
                assert_eq!(manifest.get_id(), "org.freedesktop.Platform.Icontheme.Paper");
            }
        }
    }

    #[test]
    pub fn test_parse_recursive_modules() {
        match FlatpakManifest::parse(
            "manifest.yaml",
            r###"
            app-id: com.georgefb.haruna
            runtime: org.kde.Platform
            runtime-version: '5.15'
            sdk: org.kde.Sdk
            command: haruna
            finish-args:
              - '--share=ipc'
              - '--share=network'
              - '--socket=x11'
              - '--socket=wayland'
              - '--socket=pulseaudio'
              - '--device=dri'
              - '--filesystem=host'
              - '--talk-name=ca.desrt.dconf'
              - '--talk-name=org.freedesktop.ScreenSaver'
              - '--own-name=org.mpris.MediaPlayer2.haruna'
              - '--env=DCONF_USER_CONFIG_DIR=.config/dconf'
              - '--env=LC_NUMERIC=C'
              - '--env=XDG_DATA_DIRS=/usr/share:/app/share/'
            modules:
              - name: haruna
                buildsystem: cmake-ninja
                sources:
                  - type: archive
                    url: 'https://github.com/g-fb/haruna/archive/refs/tags/0.6.3.tar.gz'
                    sha256: 'c79ec1e351f47faf9a58a6ba7ec3cc05cfdc5423fde0584f2d4081f5058363e3'
                modules:
                  - name: taglib
                    buildsystem: cmake-ninja
                    config-opts:
                    - '-DBUILD_SHARED_LIBS=ON'
                    sources:
                    - type: archive
                      url: 'https://github.com/taglib/taglib/releases/download/v1.12/taglib-1.12.tar.gz'
                      sha256: '7fccd07669a523b07a15bd24c8da1bbb92206cb19e9366c3692af3d79253b703'
                  - name: ffmpegthumbs
                    buildsystem: cmake-ninja
                    sources:
                    - type: archive
                      url: 'https://invent.kde.org/multimedia/ffmpegthumbs/-/archive/v20.12.3/ffmpegthumbs-v20.12.3.tar.gz'
                      sha256: '9292a503808688b37e45ee336efcd28c39035d49c96e1df466b091f2eaf7a529'
                  - name: kio-extras
                    buildsystem: cmake-ninja
                    sources:
                    - type: archive
                      url: 'https://invent.kde.org/network/kio-extras/-/archive/v20.12.3/kio-extras-v20.12.3.tar.gz'
                      sha256: 'bedccdbf3664f2669270c2864c6f7c0e73237d18fae04067bc21ae5e12716b0b'
                  - name: libmpv
                    cleanup:
                      - /include
                      - /lib/pkgconfig
                      - /share/man
                    buildsystem: simple
                    build-commands:
                      - python3 waf configure --prefix=/app --enable-libmpv-shared --disable-cplayer --disable-build-date --disable-alsa
                      - python3 waf build
                      - python3 waf install
                    sources:
                      - type: archive
                        url: 'https://github.com/mpv-player/mpv/archive/v0.33.1.tar.gz'
                        sha256: '100a116b9f23bdcda3a596e9f26be3a69f166a4f1d00910d1789b6571c46f3a9'
                      - type: file
                        url: 'https://waf.io/waf-2.0.21'
                        sha256: '7cebf2c5efe53cbb9a4b5bdc4b49ae90ecd64a8fce7a3222d58e591b58215306'
                        dest-filename: waf
                    modules:
                      - name: luajit
                        no-autogen: true
                        cleanup:
                          - /bin
                          - /include
                          - /lib/pkgconfig
                          - /share/man
                        sources:
                          - type: archive
                            url: 'http://luajit.org/download/LuaJIT-2.1.0-beta3.tar.gz'
                            sha256: '1ad2e34b111c802f9d0cdf019e986909123237a28c746b21295b63c9e785d9c3'
                          - type: shell
                            commands:
                              - sed -i 's|/usr/local|/app|' ./Makefile
                      - name: libv4l2
                        cleanup:
                          - /sbin
                          - /bin
                          - /include
                          - /lib/pkgconfig
                          - /share/man
                        config-opts:
                          - '--disable-static'
                          - '--disable-bpf'
                          - '--with-udevdir=/app/lib/udev'
                        sources:
                          - type: archive
                            url: 'https://linuxtv.org/downloads/v4l-utils/v4l-utils-1.20.0.tar.bz2'
                            sha256: '956118713f7ccb405c55c7088a6a2490c32d54300dd9a30d8d5008c28d3726f7'
                      - name: nv-codec-headers
                        cleanup:
                          - '*'
                        no-autogen: true
                        make-install-args:
                          - PREFIX=/app
                        sources:
                          - type: archive
                            url: 'https://github.com/FFmpeg/nv-codec-headers/releases/download/n11.0.10.0/nv-codec-headers-11.0.10.0.tar.gz'
                            sha256: 'e5d1fe6b18254a3c8747a38714564030e4fda506961a11a7eafb94f2400419bb'
                      - name: ffmpeg
                        cleanup:
                          - /include
                          - /lib/pkgconfig
                          - /share/ffmpeg/examples
                        config-opts:
                          - '--enable-shared'
                          - '--disable-static'
                          - '--enable-gnutls'
                          - '--enable-gpl'
                          - '--disable-doc'
                          - '--disable-programs'
                          - '--disable-encoders'
                          - '--disable-muxers'
                          - '--enable-encoder=png,libwebp'
                          - '--enable-libv4l2'
                          - '--enable-libdav1d'
                          - '--enable-libfontconfig'
                          - '--enable-libfreetype'
                          - '--enable-libopus'
                          - '--enable-librsvg'
                          - '--enable-libvpx'
                          - '--enable-libmp3lame'
                          - '--enable-libwebp'
                        sources:
                          - type: archive
                            url: 'https://ffmpeg.org/releases/ffmpeg-4.3.2.tar.xz'
                            sha256: '46e4e64f1dd0233cbc0934b9f1c0da676008cad34725113fb7f802cfa84ccddb'
                      - name: libass
                        cleanup:
                          - /include
                          - /lib/pkgconfig
                        config-opts:
                          - '--disable-static'
                        sources:
                          - type: archive
                            url: 'https://github.com/libass/libass/releases/download/0.15.0/libass-0.15.0.tar.gz'
                            sha256: '9cbddee5e8c87e43a5fe627a19cd2aa4c36552156eb4edcf6c5a30bd4934fe58'
                      - name: uchardet
                        buildsystem: cmake-ninja
                        config-opts:
                          - '-DCMAKE_BUILD_TYPE=Release'
                          - '-DBUILD_STATIC=0'
                        cleanup:
                          - /bin
                          - /include
                          - /lib/pkgconfig
                          - /share/man
                        sources:
                          - type: archive
                            url: 'https://gitlab.freedesktop.org/uchardet/uchardet/-/archive/v0.0.7/uchardet-v0.0.7.tar.gz'
                            sha256: 'f3635d1d10e1470452bc42c1bf509451a9926b399a11740a9949e86069d69f58'
                  - name: youtube-dl
                    no-autogen: true
                    no-make-install: true
                    make-args:
                      - youtube-dl
                      - PYTHON=/usr/bin/python3
                    post-install:
                      - install youtube-dl /app/bin
                    sources:
                      - type: archive
                        url: 'https://github.com/ytdl-org/youtube-dl/archive/2021.04.26.tar.gz'
                        sha256: 'd80023ab221b3cb89229b632e247035a22c5afaee9a7b3c653bbd702f71c1083'
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(manifest) => {
                assert_eq!(manifest.app_id, "com.georgefb.haruna");
                assert_eq!(manifest.get_max_depth(), 3);
                assert_eq!(manifest.modules.len(), 1);
                assert_eq!(manifest.get_all_modules_recursively().len(), 12);
            }
        }
    }
}

#[cfg(test)]
mod modules_tests {
    use super::*;

    #[test]
    pub fn test_parse_extra_data() {
        match FlatpakModuleDescription::parse(
            "module.yaml",
            r###"
            name: wps
            buildsystem: simple
            build-commands:
              - install -Dm755 apply_extra.sh /app/bin/apply_extra
              - install -Dm755 wps.sh /app/bin/wps
              - ln -s wps /app/bin/et
              - ln -s wps /app/bin/wpp
              - ln -s wps /app/bin/wpspdf
              - install -Dm644 ${FLATPAK_ID}.metainfo.xml -t /app/share/metainfo/
              - install -Dm755 /usr/bin/desktop-file-edit -t /app/bin/
              - install -Dm755 /usr/bin/ar -t /app/bin/
              - install -Dm755 /usr/lib/$(gcc -print-multiarch)/libbfd-*.so -t /app/lib/
            sources:
              - type: file
                path: apply_extra.sh

              - type: file
                path: com.wps.Office.metainfo.xml

              - type: file
                path: wps.sh

              - type: extra-data
                filename: wps-office.deb
                only-arches:
                  - x86_64
                url: https://wdl1.pcfg.cache.wpscdn.com/wps-office_11.1.0.10702.XA_amd64.deb
                sha256: 390a8b358aaccdfda54740d10d5306c2543c5cd42a7a8fd5c776ccff38492992
                size: 275210770
                installed-size: 988671247
                x-checker-data:
                  type: html
                  url: https://linux.wps.com/js/meta.js
                  version-pattern: version\s*=\s*"([\d.-]+)"
                  url-pattern: download_link_deb\s*=\s*"(http[s]?://[\w\d$-_@.&+]+)"
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(module) => {
                assert_eq!(module.name, "wps");
            }
        }
    }

    #[test]
    pub fn test_parse_helm_files() {
        assert!(FlatpakModuleDescription::parse(
            "module.yaml",
            r###"
            name: wps
            sources:
              - "https://github.com/user/repo"
            "###,
        )
        .is_err())
    }
}

#[cfg(test)]
mod sources_tests {
    use super::*;

    #[test]
    pub fn test_parse_single_source() {
        match FlatpakSourceDescription::parse(
            "source.yaml",
            r###"
            type: file
            path: apply_extra.sh
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(source) => {
                assert_eq!(source.path, Some("apply_extra.sh".to_string()));
            }
        }
    }

    #[test]
    pub fn test_parse_multiple_sources() {
        match FlatpakSourceDescription::parse_many(
            "source.yaml",
            r###"
            - type: file
              path: apply_extra.sh

            - type: file
              path: com.wps.Office.metainfo.xml

            - type: file
              path: wps.sh

            - type: extra-data
              filename: wps-office.deb
              only-arches:
                - x86_64
              url: https://wdl1.pcfg.cache.wpscdn.com/wps-office_11.1.0.10702.XA_amd64.deb
              sha256: 390a8b358aaccdfda54740d10d5306c2543c5cd42a7a8fd5c776ccff38492992
              size: 275210770
              installed-size: 988671247
              x-checker-data:
                type: html
                url: https://linux.wps.com/js/meta.js
                version-pattern: version\s*=\s*"([\d.-]+)"
                url-pattern: download_link_deb\s*=\s*"(http[s]?://[\w\d$-_@.&+]+)"
            "###,
        ) {
            Err(e) => panic!(e),
            Ok(sources) => {
                assert_eq!(sources.len(), 4);
                let last_source = sources.last().unwrap();
                assert_eq!(last_source.filename, Some("wps-office.deb".to_string()));
            }
        }
    }
}