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
use crate::config::CargoConfig;
use crate::dependencies::resolve;
use crate::{dh_installsystemd, debian_architecture_from_rust_triple};
use crate::error::{CDResult, CargoDebError};
use crate::listener::Listener;
use crate::ok_or::OkOrThen;
use crate::pathbytes::AsUnixPathBytes;
use crate::util::read_file_to_bytes;
use cargo_toml::DebugSetting;
use log::{debug, warn};
use rayon::prelude::*;
use serde::Deserialize;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet, BTreeMap};
use std::env::consts::EXE_SUFFIX;
use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::SystemTime;


fn is_glob_pattern(s: &Path) -> bool {
    s.to_bytes().iter().any(|&c| c == b'*' || c == b'[' || c == b']' || c == b'!')
}

#[derive(Debug, Clone)]
pub enum AssetSource {
    /// Copy file from the path (and strip binary if needed).
    Path(PathBuf),
    /// A symlink existing in the file system
    Symlink(PathBuf),
    /// Write data to destination as-is.
    Data(Vec<u8>),
}

impl AssetSource {
    /// Symlink must exist on disk to be preserved
    #[must_use]
    pub fn from_path(path: impl Into<PathBuf>, preserve_existing_symlink: bool) -> Self {
        let path = path.into();
        if preserve_existing_symlink || !path.exists() { // !exists means a symlink to bogus path
            if let Ok(md) = fs::symlink_metadata(&path) {
                if md.is_symlink() {
                    return Self::Symlink(path)
                }
            }
        }
        Self::Path(path)
    }

    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        match self {
            AssetSource::Symlink(ref p) |
            AssetSource::Path(ref p) => Some(p),
            AssetSource::Data(_) => None,
        }
    }

    #[must_use] pub fn archive_as_symlink_only(&self) -> bool {
        matches!(self, AssetSource::Symlink(_))
    }

    #[must_use]
    pub fn file_size(&self) -> Option<u64> {
        match *self {
            // FIXME: may not be accurate if the executable is not stripped yet?
            AssetSource::Path(ref p) => fs::metadata(p).ok().map(|m| m.len()),
            AssetSource::Data(ref d) => Some(d.len() as u64),
            AssetSource::Symlink(_) => None,
        }
    }

    pub fn data(&self) -> CDResult<Cow<'_, [u8]>> {
        Ok(match self {
            AssetSource::Path(p) => {
                let data = read_file_to_bytes(p)
                    .map_err(|e| CargoDebError::IoFile("unable to read asset to add to archive", e, p.clone()))?;
                Cow::Owned(data)
            },
            AssetSource::Data(d) => Cow::Borrowed(d),
            AssetSource::Symlink(_) => return Err(CargoDebError::Str("Symlink unexpectedly used to read file data")),
        })
    }

    /// Return the file that will hold debug symbols for this asset.
    /// This is just `<original-file>.debug`
    #[must_use]
    pub fn debug_source(&self) -> Option<PathBuf> {
        match self {
            AssetSource::Path(p) |
            AssetSource::Symlink(p) => Some(debug_filename(p)),
            _ => None,
        }
    }
}

/// Configuration settings for the systemd_units functionality.
///
/// `unit_scripts`: (optional) relative path to a directory containing correctly
/// named systemd unit files. See `dh_lib::pkgfile()` and `dh_installsystemd.rs`
/// for more details on file naming. If not supplied, defaults to the
/// `maintainer_scripts` directory.
///
/// `unit_name`: (optjonal) in cases where the `unit_scripts` directory contains
/// multiple units, only process those matching this unit name.
///
/// For details on the other options please see `dh_installsystemd::Options`.
#[derive(Clone, Debug, Deserialize, Default)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) struct SystemdUnitsConfig {
    pub unit_scripts: Option<PathBuf>,
    pub unit_name: Option<String>,
    pub enable: Option<bool>,
    pub start: Option<bool>,
    pub restart_after_upgrade: Option<bool>,
    pub stop_on_upgrade: Option<bool>,
}

/// Match the official `dh_installsystemd` defaults and rename the confusing
/// `dh_installsystemd` option names to be consistently positive rather than
/// mostly, but not always, negative.
impl From<&SystemdUnitsConfig> for dh_installsystemd::Options {
    fn from(config: &SystemdUnitsConfig) -> Self {
        Self {
            no_enable: !config.enable.unwrap_or(true),
            no_start: !config.start.unwrap_or(true),
            restart_after_upgrade: config.restart_after_upgrade.unwrap_or(true),
            no_stop_on_upgrade: !config.stop_on_upgrade.unwrap_or(true),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Assets {
    pub unresolved: Vec<UnresolvedAsset>,
    pub resolved: Vec<Asset>,
}

impl Assets {
    fn new() -> Assets {
        Assets {
            unresolved: vec![],
            resolved: vec![],
        }
    }

    fn with_resolved_assets(assets: Vec<Asset>) -> Assets {
        Assets {
            unresolved: vec![],
            resolved: assets,
        }
    }

    fn with_unresolved_assets(assets: Vec<UnresolvedAsset>) -> Assets {
        Assets {
            unresolved: assets,
            resolved: vec![],
        }
    }

    fn is_empty(&self) -> bool {
        self.unresolved.is_empty() && self.resolved.is_empty()
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum IsBuilt {
    No,
    SamePackage,
    /// needs --workspace to build
    Workspace,
}

#[derive(Debug, Clone)]
pub struct UnresolvedAsset {
    pub source_path: PathBuf,
    pub c: AssetCommon,
}

#[derive(Debug, Clone)]
pub struct AssetCommon {
    pub target_path: PathBuf,
    pub chmod: u32,
    is_built: IsBuilt,
    is_example: bool,
}

#[derive(Debug, Clone)]
pub struct Asset {
    pub source: AssetSource,
    pub c: AssetCommon,
}

impl Asset {
    #[must_use]
    pub fn new(source: AssetSource, mut target_path: PathBuf, chmod: u32, is_built: IsBuilt, is_example: bool) -> Self {
        // is_dir() is only for paths that exist
        if target_path.to_string_lossy().ends_with('/') {
            let file_name = source.path().and_then(|p| p.file_name()).expect("source must be a file");
            target_path = target_path.join(file_name);
        }

        if target_path.is_absolute() || target_path.has_root() {
            target_path = target_path.strip_prefix("/").expect("no root dir").to_owned();
        }

        Self {
            source,
            c: AssetCommon {
                target_path, chmod, is_built, is_example,
            },
        }
    }
}

impl AssetCommon {
    fn is_executable(&self) -> bool {
        0 != self.chmod & 0o111
    }

    fn is_dynamic_library(&self) -> bool {
        is_dynamic_library_filename(&self.target_path)
    }

    /// Returns the target path for the debug symbol file, which will be
    /// /usr/lib/debug/<path-to-executable>.debug
    #[must_use]
    pub fn debug_target(&self) -> Option<PathBuf> {
        if self.is_built != IsBuilt::No {
            // Turn an absolute path into one relative to "/"
            let relative = match self.target_path.strip_prefix(Path::new("/")) {
                Ok(path) => path,
                Err(_) => self.target_path.as_path(),
            };

            // Prepend the debug location
            let debug_path = Path::new("/usr/lib/debug").join(relative);

            // Add `.debug` to the end of the filename
            Some(debug_filename(&debug_path))
        } else {
            None
        }
    }
}

/// Adds `.debug` to the end of a path to a filename
///
fn debug_filename(path: &Path) -> PathBuf {
    let mut debug_filename = path.as_os_str().to_os_string();
    debug_filename.push(".debug");
    Path::new(&debug_filename).to_path_buf()
}

fn is_dynamic_library_filename(path: &Path) -> bool {
    path.file_name()
        .and_then(|f| f.to_str())
        .map_or(false, |f| f.ends_with(DLL_SUFFIX))
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum ArchSpec {
    /// e.g. [armhf]
    Require(String),
    /// e.g. [!armhf]
    NegRequire(String),
}

fn get_architecture_specification(depend: &str) -> CDResult<(String, Option<ArchSpec>)> {
    use ArchSpec::{NegRequire, Require};
    let re = regex::Regex::new(r#"(.*)\[(!?)(.*)\]"#).unwrap();
    match re.captures(depend) {
        Some(caps) => {
            let spec = if &caps[2] == "!" {
                NegRequire(caps[3].to_string())
            } else {
                assert_eq!(&caps[2], "");
                Require(caps[3].to_string())
            };
            Ok((caps[1].trim().to_string(), Some(spec)))
        }
        None => Ok((depend.to_string(), None)),
    }
}

/// Architecture specification strings
/// <https://www.debian.org/doc/debian-policy/ch-customized-programs.html#s-arch-spec>
fn match_architecture(spec: ArchSpec, target_arch: &str) -> CDResult<bool> {
    let (neg, spec) = match spec {
        ArchSpec::NegRequire(pkg) => (true, pkg),
        ArchSpec::Require(pkg) => (false, pkg),
    };
    let output = Command::new("dpkg-architecture")
        .args(["-a", target_arch, "-i", &spec])
        .output()
        .map_err(|e| CargoDebError::CommandFailed(e, "dpkg-architecture"))?;
    if neg {
        Ok(!output.status.success())
    } else {
        Ok(output.status.success())
    }
}

#[derive(Debug)]
#[non_exhaustive]
/// Cargo deb configuration read from the manifest and cargo metadata
pub struct Config {
    /// Directory where `Cargo.toml` is located. It's a subdirectory in workspaces.
    pub package_manifest_dir: PathBuf,
    /// User-configured output path for *.deb
    pub deb_output_path: Option<String>,
    /// Triple. `None` means current machine architecture.
    pub target: Option<String>,
    /// `CARGO_TARGET_DIR`
    pub target_dir: PathBuf,
    /// The name of the project to build
    pub name: String,
    /// The name to give the Debian package; usually the same as the Cargo project name
    pub deb_name: String,
    /// The version to give the Debian package; usually the same as the Cargo version
    pub deb_version: String,
    /// The software license of the project (SPDX format).
    pub license: Option<String>,
    /// The location of the license file
    pub license_file: Option<PathBuf>,
    /// number of lines to skip when reading `license_file`
    pub license_file_skip_lines: usize,
    /// The copyright of the project
    /// (Debian's `copyright` file contents).
    pub copyright: String,
    pub changelog: Option<String>,
    /// The homepage URL of the project.
    pub homepage: Option<String>,
    /// Documentation URL from `Cargo.toml`. Fallback if `homepage` is missing.
    pub documentation: Option<String>,
    /// The URL of the software repository.
    pub repository: Option<String>,
    /// A short description of the project.
    pub description: String,
    /// An extended description of the project.
    pub extended_description: Option<String>,
    /// The maintainer of the Debian package.
    /// In Debian `control` file `Maintainer` field format.
    pub maintainer: String,
    /// The Debian dependencies required to run the project.
    pub depends: String,
    /// The Debian pre-dependencies.
    pub pre_depends: Option<String>,
    /// The Debian recommended dependencies.
    pub recommends: Option<String>,
    /// The Debian suggested dependencies.
    pub suggests: Option<String>,
    /// The list of packages this package can enhance.
    pub enhances: Option<String>,
    /// The Debian software category to which the package belongs.
    pub section: Option<String>,
    /// The Debian priority of the project. Typically 'optional'.
    pub priority: String,

    /// `Conflicts` Debian control field.
    ///
    /// See [PackageTransition](https://wiki.debian.org/PackageTransition).
    pub conflicts: Option<String>,
    /// `Breaks` Debian control field.
    ///
    /// See [PackageTransition](https://wiki.debian.org/PackageTransition).
    pub breaks: Option<String>,
    /// `Replaces` Debian control field.
    ///
    /// See [PackageTransition](https://wiki.debian.org/PackageTransition).
    pub replaces: Option<String>,
    /// `Provides` Debian control field.
    ///
    /// See [PackageTransition](https://wiki.debian.org/PackageTransition).
    pub provides: Option<String>,

    /// The Debian architecture of the target system.
    pub architecture: String,
    /// A list of configuration files installed by the package.
    pub conf_files: Option<String>,
    /// All of the files that are to be packaged.
    pub(crate) assets: Assets,
    /// The location of the triggers file
    pub triggers_file: Option<PathBuf>,
    /// The path where possible maintainer scripts live
    pub maintainer_scripts: Option<PathBuf>,
    /// List of Cargo features to use during build
    pub features: Vec<String>,
    pub default_features: bool,
    /// Should the binary be stripped from debug symbols?
    pub debug_enabled: bool,
    /// Should the debug symbols be moved to a separate file included in the package? (implies `strip:true`)
    pub separate_debug_symbols: bool,
    /// Should symlinks be preserved in the assets
    pub preserve_symlinks: bool,
    /// Details of how to install any systemd units
    pub(crate) systemd_units: Option<Vec<SystemdUnitsConfig>>,

    /// unix timestamp for generated files
    pub default_timestamp: u64,
}

impl Config {
    /// Makes a new config from `Cargo.toml` in the `manifest_path`
    ///
    /// `None` target means the host machine's architecture.
    pub fn from_manifest(root_manifest_path: Option<&Path>, selected_package_name: Option<&str>, output_path: Option<String>, target: Option<&str>, variant: Option<&str>, deb_version: Option<String>, deb_revision: Option<String>, listener: &dyn Listener, selected_profile: &str) -> CDResult<Config> {
        let metadata = cargo_metadata(root_manifest_path)?;
        let available_package_names = || {
            metadata.packages.iter()
                .filter(|p| metadata.workspace_members.iter().any(|w| w == &p.id))
                .map(|p| p.name.as_str())
                .collect::<Vec<_>>().join(", ")
        };
        let target_package = if let Some(name) = selected_package_name {
            metadata.packages.iter().find(|p| p.name == name)
                .ok_or_else(|| CargoDebError::PackageNotFoundInWorkspace(name.into(), available_package_names()))
        } else {
            metadata.resolve.root.as_ref().and_then(|root_id| {
                metadata.packages.iter()
                    .find(move |p| &p.id == root_id)
            })
            .ok_or_else(|| CargoDebError::NoRootFoundInWorkspace(available_package_names()))
        }?;
        let workspace_root_manifest_path = Path::new(&metadata.workspace_root).join("Cargo.toml");
        let workspace_root_manifest = cargo_toml::Manifest::<CargoPackageMetadata>::from_path_with_metadata(workspace_root_manifest_path).ok();

        let target_dir = Path::new(&metadata.target_directory);
        let manifest_path = Path::new(&target_package.manifest_path);
        let package_manifest_dir = manifest_path.parent().ok_or("bad path")?;
        let manifest_bytes =
            fs::read(manifest_path).map_err(|e| CargoDebError::IoFile("unable to read manifest", e, manifest_path.to_owned()))?;
        let manifest_mdate = std::fs::metadata(manifest_path)?.modified().unwrap_or_else(|_| SystemTime::now());
        let default_timestamp = if let Ok(source_date_epoch) = std::env::var("SOURCE_DATE_EPOCH") {
            source_date_epoch.parse().map_err(|e| CargoDebError::NumParse("SOURCE_DATE_EPOCH", e))?
        } else {
            manifest_mdate.duration_since(SystemTime::UNIX_EPOCH).map_err(CargoDebError::SystemTime)?.as_secs()
        };

        let mut manifest = cargo_toml::Manifest::<CargoPackageMetadata>::from_slice_with_metadata(&manifest_bytes)
            .map_err(|e| CargoDebError::TomlParsing(e, manifest_path.into()))?;
        let ws_root = workspace_root_manifest.as_ref().map(|ws| (ws, Path::new(&metadata.workspace_root)));
        manifest.complete_from_path_and_workspace(manifest_path, ws_root)
            .map_err(move |e| CargoDebError::TomlParsing(e, manifest_path.to_path_buf()))?;
        Self::from_manifest_inner(manifest, workspace_root_manifest.as_ref(), target_package, package_manifest_dir, output_path, target_dir, target, variant, deb_version, deb_revision, listener, selected_profile, default_timestamp)
    }

    /// Convert Cargo.toml/metadata information into internal config structure
    ///
    /// **IMPORTANT**: This function must not create or expect to see any files on disk!
    /// It's run before destination directory is cleaned up, and before the build start!
    fn from_manifest_inner(
        mut manifest: cargo_toml::Manifest<CargoPackageMetadata>,
        root_manifest: Option<&cargo_toml::Manifest<CargoPackageMetadata>>,
        cargo_metadata: &CargoMetadataPackage,
        package_manifest_dir: &Path,
        deb_output_path: Option<String>,
        target_dir: &Path,
        target: Option<&str>,
        variant: Option<&str>,
        deb_version: Option<String>,
        deb_revision: Option<String>,
        listener: &dyn Listener,
        selected_profile: &str,
        default_timestamp: u64,
    ) -> CDResult<Self> {
        // Cargo cross-compiles to a dir
        let target_dir = if let Some(target) = target {
            target_dir.join(target)
        } else {
            target_dir.to_owned()
        };

        // FIXME: support other named profiles
        let debug_enabled = if selected_profile == "release" {
            debug_flag(&manifest) || root_manifest.map_or(false, debug_flag)
        } else {
            false
        };
        let package = manifest.package.as_mut().unwrap();

        // If we build against a variant use that config and change the package name
        let mut deb = if let Some(variant) = variant {
            // Use dash as underscore is not allowed in package names
            package.name = format!("{}-{variant}", package.name);
            let mut deb = package.metadata.take()
                .and_then(|m| m.deb).unwrap_or_default();
            let variant = deb.variants
                .as_mut()
                .and_then(|v| v.remove(variant))
                .ok_or_else(|| CargoDebError::VariantNotFound(variant.to_string()))?;
            variant.inherit_from(deb)
        } else {
            package.metadata.take().and_then(|m| m.deb).unwrap_or_default()
        };

        let (license_file, license_file_skip_lines) = manifest_license_file(package, deb.license_file.as_ref())?;

        manifest_check_config(package, package_manifest_dir, &deb, listener);

        let extended_description_file = deb.extended_description_file.is_none()
            .then(|| package.readme().as_path()).flatten()
            .map(|readme_rel_path| package_manifest_dir.join(readme_rel_path));
        let extended_description = manifest_extended_description(
            deb.extended_description.take(),
            deb.extended_description_file.as_ref().map(Path::new).or(extended_description_file.as_deref()),
        )?;

        let mut config = Config {
            default_timestamp,
            package_manifest_dir: package_manifest_dir.to_owned(),
            deb_output_path,
            target: target.map(|t| t.to_string()),
            target_dir,
            name: package.name.clone(),
            deb_name: deb.name.take().unwrap_or_else(|| debian_package_name(&package.name)),
            deb_version: deb_version.unwrap_or_else(|| manifest_version_string(package, deb_revision.or(deb.revision).as_deref()).into_owned()),
            license: package.license.take().map(|v| v.unwrap()),
            license_file,
            license_file_skip_lines,
            copyright: deb.copyright.take().ok_or_then(|| {
                if package.authors().is_empty() {
                    return Err("The package must have a copyright or authors property".into());
                }
                Ok(package.authors().join(", "))
            })?,
            homepage: package.homepage().map(From::from),
            documentation: package.documentation().map(From::from),
            repository: package.repository.take().map(|v| v.unwrap()),
            description: package.description.take().map(|v| v.unwrap()).unwrap_or_else(||format!("[generated from Rust crate {}]", package.name)),
            extended_description,
            maintainer: deb.maintainer.take().ok_or_then(|| {
                Ok(package.authors().get(0)
                    .ok_or("The package must have a maintainer or authors property")?.to_owned())
            })?,
            depends: deb.depends.take().map(DependencyList::into_depends_string).unwrap_or_else(|| "$auto".to_owned()),
            pre_depends: deb.pre_depends.take().map(DependencyList::into_depends_string),
            recommends: deb.recommends.take().map(DependencyList::into_depends_string),
            suggests: deb.suggests.take().map(DependencyList::into_depends_string),
            enhances: deb.enhances.take(),
            conflicts: deb.conflicts.take(),
            breaks: deb.breaks.take(),
            replaces: deb.replaces.take(),
            provides: deb.provides.take(),
            section: deb.section.take(),
            priority: deb.priority.take().unwrap_or_else(|| "optional".to_owned()),
            architecture: debian_architecture_from_rust_triple(target.unwrap_or(crate::DEFAULT_TARGET)).to_owned(),
            conf_files: deb.conf_files.map(|x| format_conffiles(&x)),
            assets: Assets::new(),
            triggers_file: deb.triggers_file.map(PathBuf::from),
            changelog: deb.changelog.take(),
            maintainer_scripts: deb.maintainer_scripts.map(PathBuf::from),
            features: deb.features.take().unwrap_or_default(),
            default_features: deb.default_features.unwrap_or(true),
            separate_debug_symbols: deb.separate_debug_symbols.unwrap_or(false),
            debug_enabled,
            preserve_symlinks: deb.preserve_symlinks.unwrap_or(false),
            systemd_units: match deb.systemd_units {
                None => None,
                Some(SystemUnitsSingleOrMultiple::Single(s)) => Some(vec![s]),
                Some(SystemUnitsSingleOrMultiple::Multi(v)) => Some(v),
            },
        };
        config.take_assets(package, deb.assets.take(), &cargo_metadata.targets, selected_profile, listener)?;
        config.add_copyright_asset()?;
        config.add_changelog_asset()?;
        config.add_systemd_assets()?;

        Ok(config)
    }

    pub(crate) fn get_dependencies(&self, listener: &dyn Listener) -> CDResult<String> {
        let mut deps = HashSet::new();
        for word in self.depends.split(',') {
            let word = word.trim();
            if word == "$auto" {
                let bin = self.all_binaries();
                let resolved = bin.par_iter()
                    .filter(|bin| !bin.archive_as_symlink_only())
                    .filter_map(|p| p.path())
                    .filter_map(|bname| match resolve(bname, &self.target) {
                        Ok(bindeps) => Some(bindeps),
                        Err(err) => {
                            listener.warning(format!("{} (no auto deps for {})", err, bname.display()));
                            None
                        },
                    })
                    .collect::<Vec<_>>();
                for dep in resolved.into_iter().flat_map(|s| s.into_iter()) {
                    deps.insert(dep);
                }
            } else {
                let (dep, arch_spec) = get_architecture_specification(word)?;
                if let Some(spec) = arch_spec {
                    if match_architecture(spec, &self.architecture)? {
                        deps.insert(dep);
                    }
                } else {
                    deps.insert(dep);
                }
            }
        }
        Ok(deps.into_iter().collect::<Vec<_>>().join(", "))
    }

    pub fn extend_cargo_build_flags(&self, flags: &mut Vec<String>) {
        if flags.iter().any(|f| f == "--workspace" || f == "--all") {
            return;
        }

        for a in self.assets.unresolved.iter().filter(|a| a.c.is_built != IsBuilt::No) {
            if is_glob_pattern(&a.source_path) {
                log::debug!("building entire workspace because of glob {}", a.source_path.display());
                flags.push("--workspace".into());
                return;
            }
        }

        let mut build_bins = vec![];
        let mut build_examples = vec![];
        let mut build_libs = false;
        let mut same_package = true;
        let resolved = self.assets.resolved.iter().map(|a| (&a.c, a.source.path()));
        let unresolved = self.assets.unresolved.iter().map(|a| (&a.c, Some(a.source_path.as_ref())));
        for (asset_target, source_path) in resolved.chain(unresolved).filter(|(c,_)| c.is_built != IsBuilt::No) {
            if asset_target.is_built != IsBuilt::SamePackage {
                log::debug!("building workspace because {} is from another package", source_path.unwrap_or(&asset_target.target_path).display());
                same_package = false;
            }
            if asset_target.is_dynamic_library() || source_path.map_or(false, is_dynamic_library_filename) {
                log::debug!("building libs for {}", source_path.unwrap_or(&asset_target.target_path).display());
                build_libs = true;
            } else if asset_target.is_executable() {
                if let Some(source_path) = source_path {
                    let name = source_path.file_name().unwrap().to_str().expect("utf-8 target name");
                    let name = name.strip_suffix(EXE_SUFFIX).unwrap_or(name);
                    if asset_target.is_example {
                        build_examples.push(name);
                    } else {
                        build_bins.push(name);
                    }
                }
            }
        }

        if !same_package {
            flags.push("--workspace".into());
        }
        flags.extend(build_bins.iter().map(|name| {
            log::debug!("building bin for {}", name);
            format!("--bin={name}")
        }));
        flags.extend(build_examples.iter().map(|name| {
            log::debug!("building example for {}", name);
            format!("--example={name}")
        }));
        if build_libs {
            flags.push("--lib".into());
        }
    }

    pub fn resolve_assets(&mut self) -> CDResult<()> {
        for UnresolvedAsset { source_path, c: AssetCommon { target_path, chmod, is_built, is_example } } in self.assets.unresolved.drain(..) {
            let source_prefix: PathBuf = source_path.iter()
                .take_while(|part| !is_glob_pattern(part.as_ref()))
                .collect();
            let source_is_glob = is_glob_pattern(&source_path);
            let file_matches = glob::glob(source_path.to_str().expect("utf8 path"))?
                // Remove dirs from globs without throwing away errors
                .map(|entry| {
                    let source_file = entry?;
                    Ok(if source_file.is_dir() { None } else { Some(source_file) })
                })
                .filter_map(|res| match res {
                    Ok(None) => None,
                    Ok(Some(x)) => Some(Ok(x)),
                    Err(x) => Some(Err(x)),
                })
                .collect::<CDResult<Vec<_>>>()?;

            // If glob didn't match anything, it's likely an error
            // as all files should exist when called to resolve
            if file_matches.is_empty() {
                return Err(CargoDebError::AssetFileNotFound(source_path));
            }

            for source_file in file_matches {
                // XXX: how do we handle duplicated assets?
                let target_file = if source_is_glob {
                    target_path.join(source_file.strip_prefix(&source_prefix).unwrap())
                } else {
                    target_path.clone()
                };
                log::debug!("asset {} -> {} {} {:o}", source_file.display(), target_file.display(), if is_built == IsBuilt::No {"copy"} else {"build"}, chmod);
                self.assets.resolved.push(Asset::new(
                    AssetSource::from_path(source_file, self.preserve_symlinks),
                    target_file,
                    chmod,
                    is_built,
                    is_example,
                ));
            }
        }

        self.sort_assets_by_type();
        Ok(())
    }

    pub(crate) fn add_copyright_asset(&mut self) -> CDResult<()> {
        let copyright_file = crate::data::generate_copyright_asset(self)?;
        log::debug!("added copyright");
        self.assets.resolved.push(Asset::new(
            AssetSource::Data(copyright_file),
            Path::new("usr/share/doc").join(&self.deb_name).join("copyright"),
            0o644,
            IsBuilt::No,
            false,
        ));
        Ok(())
    }

    pub fn add_debug_assets(&mut self, original_binaries: Vec<Asset>) {
        let mut assets_to_add: Vec<Asset> = Vec::new();
        for asset in original_binaries.into_iter().filter(|a| a.source.path().is_some()) {
            let debug_source = asset.source.debug_source().expect("debug asset");
            if debug_source.exists() {
                log::debug!("added debug file {}", debug_source.display());
                let debug_target = asset.c.debug_target().expect("debug asset");
                assets_to_add.push(Asset::new(
                    AssetSource::Path(debug_source),
                    debug_target,
                    0o644,
                    IsBuilt::No,
                    false,
                ));
            } else {
                log::debug!("no debug file {}", debug_source.display());
            }
        }
        self.assets.resolved.append(&mut assets_to_add);
    }

    fn add_changelog_asset(&mut self) -> CDResult<()> {
        // The file is autogenerated later
        if self.changelog.is_some() {
            if let Some(changelog_file) = crate::data::generate_changelog_asset(self)? {
                log::debug!("added changelog");
                self.assets.resolved.push(Asset::new(
                    AssetSource::Data(changelog_file),
                    Path::new("usr/share/doc").join(&self.deb_name).join("changelog.Debian.gz"),
                    0o644,
                    IsBuilt::No,
                    false,
                ));
            }
        }
        Ok(())
    }

    fn add_systemd_assets(&mut self) -> CDResult<()> {
        if let Some(ref config_vec) = self.systemd_units {
            for config in config_vec {
                let units_dir_option = config.unit_scripts.as_ref()
                    .or(self.maintainer_scripts.as_ref());
                if let Some(unit_dir) = units_dir_option {
                    let search_path = self.path_in_package(unit_dir);
                    let package = &self.name;
                    let unit_name = config.unit_name.as_deref();

                    let units = dh_installsystemd::find_units(&search_path, package, unit_name);

                    for (source, target) in units {
                        self.assets.resolved.push(Asset::new(
                            AssetSource::from_path(source, self.preserve_symlinks), // should this even support symlinks at all?
                            target.path,
                            target.mode,
                            IsBuilt::No,
                            false,
                        ));
                    }
                }
            }
        } else {
            log::debug!("no systemd units to generate");
        }
        Ok(())
    }

    /// Executables AND dynamic libraries. May include symlinks.
    fn all_binaries(&self) -> Vec<&AssetSource> {
        self.assets.resolved.iter()
            .filter(|asset| {
                // Assumes files in build dir which have executable flag set are binaries
                asset.c.is_dynamic_library() || asset.c.is_executable()
            })
            .map(|asset| &asset.source)
            .collect()
    }

    /// Executables AND dynamic libraries, but only in `target/release`
    pub(crate) fn built_binaries_mut(&mut self) -> Vec<&mut Asset> {
        self.assets.resolved.iter_mut()
            .filter(move |asset| {
                // Assumes files in build dir which have executable flag set are binaries
                asset.c.is_built != IsBuilt::No && (asset.c.is_dynamic_library() || asset.c.is_executable())
            })
            .collect()
    }

    /// Tries to guess type of source control used for the repo URL.
    /// It's a guess, and it won't be 100% accurate, because Cargo suggests using
    /// user-friendly URLs or webpages instead of tool-specific URL schemes.
    pub(crate) fn repository_type(&self) -> Option<&str> {
        if let Some(ref repo) = self.repository {
            if repo.starts_with("git+")
                || repo.ends_with(".git")
                || repo.contains("git@")
                || repo.contains("github.com")
                || repo.contains("gitlab.com")
            {
                return Some("Git");
            }
            if repo.starts_with("cvs+") || repo.contains("pserver:") || repo.contains("@cvs.") {
                return Some("Cvs");
            }
            if repo.starts_with("hg+") || repo.contains("hg@") || repo.contains("/hg.") {
                return Some("Hg");
            }
            if repo.starts_with("svn+") || repo.contains("/svn.") {
                return Some("Svn");
            }
            return None;
        }
        None
    }

    pub(crate) fn path_in_build<P: AsRef<Path>>(&self, rel_path: P, profile: &str) -> PathBuf {
        self.path_in_build_(rel_path.as_ref(), profile)
    }

    pub(crate) fn path_in_build_(&self, rel_path: &Path, profile: &str) -> PathBuf {
        let profile = match profile {
            "dev" => "debug",
            p => p,
        };

        let mut path = self.target_dir.join(profile);
        path.push(rel_path);
        path
    }

    pub(crate) fn path_in_package<P: AsRef<Path>>(&self, rel_path: P) -> PathBuf {
        self.package_manifest_dir.join(rel_path)
    }

    /// Store intermediate files here
    pub(crate) fn deb_temp_dir(&self) -> PathBuf {
        self.target_dir.join("debian").join(&self.name)
    }

    /// Save final .deb here
    pub(crate) fn deb_output_path(&self, filename: &str) -> PathBuf {
        if let Some(ref path_str) = self.deb_output_path {
            let path = Path::new(path_str);
            if path_str.ends_with('/') || path.is_dir() {
                path.join(filename)
            } else {
                path.to_owned()
            }
        } else {
            self.default_deb_output_dir().join(filename)
        }
    }

    pub(crate) fn default_deb_output_dir(&self) -> PathBuf {
        self.target_dir.join("debian")
    }

    pub(crate) fn cargo_config(&self) -> CDResult<Option<CargoConfig>> {
        CargoConfig::new(&self.package_manifest_dir)
    }

    /// similar files next to each other improve tarball compression
    pub(crate) fn sort_assets_by_type(&mut self) {
        self.assets.resolved.sort_by(|a,b| {
            a.c.is_executable().cmp(&b.c.is_executable())
            .then(a.c.is_dynamic_library().cmp(&b.c.is_dynamic_library()))
            .then(a.c.target_path.extension().cmp(&b.c.target_path.extension()))
            .then(a.c.target_path.parent().cmp(&b.c.target_path.parent()))
        });
    }
}

/// Debian doesn't like `_` in names
fn debian_package_name(crate_name: &str) -> String {
    // crate names are ASCII only
    crate_name.bytes().map(|c| {
        if c != b'_' {c.to_ascii_lowercase() as char} else {'-'}
    }).collect()
}

fn debug_flag(manifest: &cargo_toml::Manifest<CargoPackageMetadata>) -> bool {
    manifest.profile.release.as_ref()
        .and_then(|r| r.debug.as_ref())
        .map_or(false, |debug| *debug != DebugSetting::None)
}

fn manifest_check_config(package: &cargo_toml::Package<CargoPackageMetadata>, manifest_dir: &Path, deb: &CargoDeb, listener: &dyn Listener) {
    let readme_rel_path = package.readme().as_path();
    if package.description().is_none() {
        listener.warning("description field is missing in Cargo.toml".to_owned());
    }
    if package.license().is_none() && package.license_file().is_none() {
        listener.warning("license field is missing in Cargo.toml".to_owned());
    }
    if let Some(readme_rel_path) = readme_rel_path {
        let ext = readme_rel_path.extension().unwrap_or("".as_ref());
        if deb.extended_description.is_none() && deb.extended_description_file.is_none() && (ext == "md" || ext == "markdown") {
            listener.info(format!("extended-description field missing. Using {}, but markdown may not render well.", readme_rel_path.display()));
        }
    } else {
        for p in &["README.md", "README.markdown", "README.txt", "README"] {
            if manifest_dir.join(p).exists() {
                listener.warning(format!("{p} file exists, but is not specified in `readme` Cargo.toml field"));
                break;
            }
        }
    }
}

fn manifest_extended_description(desc: Option<String>, desc_file: Option<&Path>) -> CDResult<Option<String>> {
    Ok(if desc.is_some() {
        desc
    } else if let Some(desc_file) = desc_file {
        Some(fs::read_to_string(desc_file)
            .map_err(|err| CargoDebError::IoFile(
                    "unable to read extended description from file", err, PathBuf::from(desc_file)))?)
    } else {
        None
    })
}

fn manifest_license_file(package: &cargo_toml::Package<CargoPackageMetadata>, license_file: Option<&LicenseFile>) -> CDResult<(Option<PathBuf>, usize)> {
    Ok(match license_file {
        Some(LicenseFile::Vec(args)) => {
            let mut args = args.iter();
            let file = args.next();
            let lines = if let Some(lines) = args.next() {
                lines.parse().map_err(|e| CargoDebError::NumParse("invalid number of lines", e))?
            } else {0};
            (file.map(|s|s.into()), lines)
        },
        Some(LicenseFile::String(s)) => {
            (Some(s.into()), 0)
        }
        None => {
            (package.license_file().as_ref().map(|s| s.into()), 0)
        }
    })
}

impl Config {
fn take_assets(&mut self, package: &cargo_toml::Package<CargoPackageMetadata>, assets: Option<Vec<Vec<String>>>, build_targets: &[CargoMetadataTarget], profile: &str, listener: &dyn Listener) -> CDResult<()> {
    let assets = if let Some(assets) = assets {
        let profile_target_dir = format!("target/{profile}");
        // Treat all explicit assets as unresolved until after the build step
        let mut unresolved_assets = Vec::with_capacity(assets.len());
        for mut asset_line in assets {
            let mut asset_parts = asset_line.drain(..);
            let source_path = PathBuf::from(asset_parts.next()
                .ok_or("missing path (first array entry) for asset in Cargo.toml")?);
            if source_path.starts_with("target/debug/") {
                listener.warning(format!("Packaging of development-only binaries is intentionally unsupported in cargo-deb.
Please only use `target/release/` directory for built products, not `{}`.
To add debug information or additional assertions use `[profile.release]` in `Cargo.toml` instead.
This will be hard error in a future release of cargo-deb.", source_path.display()));
            }
            // target/release is treated as a magic prefix that resolves to any profile
            let (is_built, source_path, is_example) = if let Ok(rel_path) = source_path.strip_prefix("target/release").or_else(|_| source_path.strip_prefix(&profile_target_dir)) {
                let is_example = rel_path.starts_with("examples");

                (self.find_is_built_file_in_package(rel_path, build_targets, if is_example { "example" } else { "bin" }), self.path_in_build(rel_path, profile), is_example)
            } else {
                (IsBuilt::No, self.path_in_package(&source_path), false)
            };
            let target_path = PathBuf::from(asset_parts.next().ok_or("missing target (second array entry) for asset in Cargo.toml. Use something like \"usr/local/bin/\".")?);
            let chmod = u32::from_str_radix(&asset_parts.next().ok_or("missing chmod (third array entry) for asset in Cargo.toml. Use an octal string like \"777\".")?, 8)
                .map_err(|e| CargoDebError::NumParse("unable to parse chmod argument", e))?;

            unresolved_assets.push(UnresolvedAsset {
                source_path,
                c: AssetCommon { target_path, chmod, is_built, is_example },
            });
        }
        Assets::with_unresolved_assets(unresolved_assets)
    } else {
        let mut implied_assets: Vec<_> = build_targets.iter()
            .filter_map(|t| {
                if t.crate_types.iter().any(|ty| ty == "bin") && t.kind.iter().any(|k| k == "bin") {
                    Some(Asset::new(
                        AssetSource::Path(self.path_in_build(&t.name, profile)),
                        Path::new("usr/bin").join(&t.name),
                        0o755,
                        self.is_built_file_in_package(t),
                        false,
                    ))
                } else if t.crate_types.iter().any(|ty| ty == "cdylib") && t.kind.iter().any(|k| k == "cdylib") {
                    // FIXME: std has constants for the host arch, but not for cross-compilation
                    let lib_name = format!("{DLL_PREFIX}{}{DLL_SUFFIX}", t.name);
                    Some(Asset::new(
                        AssetSource::Path(self.path_in_build(&lib_name, profile)),
                        Path::new("usr/lib").join(lib_name),
                        0o644,
                        self.is_built_file_in_package(t),
                        false,
                    ))
                } else {
                    None
                }
            })
            .collect();
        if let Some(readme_rel_path) = package.readme().as_path() {
            let path = self.path_in_package(readme_rel_path);
            let target_path = Path::new("usr/share/doc")
                .join(&package.name)
                .join(path.file_name().ok_or("bad README path")?);
            implied_assets.push(Asset::new(AssetSource::Path(path), target_path, 0o644, IsBuilt::No, false));
        }
        Assets::with_resolved_assets(implied_assets)
    };
    if assets.is_empty() {
        return Err("No binaries or cdylibs found. The package is empty. Please specify some assets to package in Cargo.toml".into());
    }
    self.assets = assets;
    Ok(())
}
    fn find_is_built_file_in_package(&self, rel_path: &Path, build_targets: &[CargoMetadataTarget], expected_kind: &str) -> IsBuilt {
        let source_name = rel_path.file_name().expect("asset filename").to_str().expect("utf-8 names");
        let source_name = source_name.strip_suffix(EXE_SUFFIX).unwrap_or(source_name);

        if build_targets.iter()
            .filter(|t| t.name == source_name && t.kind.iter().any(|k| k == expected_kind))
            .any(|t| self.is_built_file_in_package(t) == IsBuilt::SamePackage)
        {
            IsBuilt::SamePackage
        } else {
            IsBuilt::Workspace
        }
    }

    fn is_built_file_in_package(&self, build_target: &CargoMetadataTarget) -> IsBuilt {
        if build_target.src_path.starts_with(&self.package_manifest_dir) {
            IsBuilt::SamePackage
        } else {
            IsBuilt::Workspace
        }
    }
}


/// Debian-compatible version of the semver version
fn manifest_version_string<'a>(package: &'a cargo_toml::Package<CargoPackageMetadata>, revision: Option<&str>) -> Cow<'a, str> {
    let mut version = Cow::Borrowed(package.version());

    // Make debian's version ordering (newer versions) more compatible with semver's.
    // Keep "semver-1" and "semver-xxx" as-is (assuming these are irrelevant, or debian revision already),
    // but change "semver-beta.1" to "semver~beta.1"
    let mut parts = version.splitn(2, '-');
    let semver_main = parts.next().unwrap();
    if let Some(semver_pre) = parts.next() {
        let pre_ascii = semver_pre.as_bytes();
        if pre_ascii.iter().any(|c| !c.is_ascii_digit()) && pre_ascii.iter().any(u8::is_ascii_digit) {
            version = Cow::Owned(format!("{semver_main}~{semver_pre}"));
        }
    }

    match revision {
        None => format!("{version}-1").into(),
        Some("") => version,
        Some(revision) => format!("{version}-{revision}").into()
    }
}

#[derive(Clone, Debug, Deserialize, Default)]
struct CargoPackageMetadata {
    pub deb: Option<CargoDeb>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum LicenseFile {
    String(String),
    Vec(Vec<String>),
}

#[derive(Deserialize)]
#[derive(Clone, Debug)]
#[serde(untagged)]
enum SystemUnitsSingleOrMultiple {
    Single(SystemdUnitsConfig),
    Multi(Vec<SystemdUnitsConfig>)
}

#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum DependencyList {
    String(String),
    Vec(Vec<String>),
}

impl DependencyList {
    fn into_depends_string(self) -> String {
        match self {
            Self::String(s) => s,
            Self::Vec(vals) => vals.join(", "),
        }
    }
}

/// Type-alias for list of assets
/// 
type AssetList = Vec<Vec<String>>;

/// Type-alias for a merge map,
/// 
type MergeMap<'a> = BTreeMap<&'a str, [&'a str; 2]>;

#[derive(Clone, Debug, Deserialize, Default)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct CargoDeb {
    pub name: Option<String>,
    pub maintainer: Option<String>,
    pub copyright: Option<String>,
    pub license_file: Option<LicenseFile>,
    pub changelog: Option<String>,
    pub depends: Option<DependencyList>,
    pub pre_depends: Option<DependencyList>,
    pub recommends: Option<DependencyList>,
    pub suggests: Option<DependencyList>,
    pub enhances: Option<String>,
    pub conflicts: Option<String>,
    pub breaks: Option<String>,
    pub replaces: Option<String>,
    pub provides: Option<String>,
    pub extended_description: Option<String>,
    pub extended_description_file: Option<String>,
    pub section: Option<String>,
    pub priority: Option<String>,
    pub revision: Option<String>,
    pub conf_files: Option<Vec<String>>,
    pub assets: Option<AssetList>,
    pub merge_assets: Option<MergeAssets>,
    pub triggers_file: Option<String>,
    pub maintainer_scripts: Option<String>,
    pub features: Option<Vec<String>>,
    pub default_features: Option<bool>,
    pub separate_debug_symbols: Option<bool>,
    pub preserve_symlinks: Option<bool>,
    pub systemd_units: Option<SystemUnitsSingleOrMultiple>,
    pub variants: Option<HashMap<String, CargoDeb>>,
}

/// Struct containing merge configuration
/// 
#[derive(Clone, Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct MergeAssets {
    /// Merge assets by appending this list,
    /// 
    append: Option<AssetList>,
    /// Merge assets using the src as the key,
    /// 
    by: Option<MergeByKey>,
}

/// Enumeration of merge by key strategies
/// 
#[derive(Clone, Debug, Deserialize)]
enum MergeByKey {
    #[serde(rename = "src")]
    Src(AssetList),
    #[serde(rename = "dest")]
    Dest(AssetList),
}

impl MergeByKey {
    /// Merges w/ a parent asset list
    /// 
    fn merge(self, parent: &AssetList) -> AssetList {
        let merge_map = { 
            parent.iter().fold(BTreeMap::new(), |parent, asset| {
                self.prep_parent_item(parent, asset)
            })
        };

        self.merge_with(merge_map)
    }


    /// Folds the parent asset into a merge-map preparing to prepare for a merge,
    /// 
    fn prep_parent_item<'a>(&'a self, mut parent: MergeMap<'a>, asset: &'a Vec<String>) -> MergeMap {
        if let [src, dest, perm, ..] = &asset[..] {
            match &self {
                MergeByKey::Src(_) => {
                    parent.insert(src, [dest, perm]);
                },
                MergeByKey::Dest(_) => {
                    parent.insert(dest, [src, perm]);
                },
            }
            parent
        } else {
            warn!("Incomplete asset entry {:?}", asset);
            parent
        }
    }

    /// Merges w/ a parent merge map and returns the resulting asset list,
    /// 
    fn merge_with(&self, parent: MergeMap) -> AssetList {
        match self {
            MergeByKey::Src(assets) => {
               assets.iter().fold(parent, |mut acc, asset| {
                    if let [src, dest, perm, ..] = &asset[..] {
                        if let Some([replaced_dest, replaced_perm]) = acc.insert(src, [dest, perm]) {
                            debug!("Replacing {:?} w/ {:?}", [replaced_dest, replaced_perm], [dest, perm]);
                        }
                        acc
                    } else {
                        warn!("Incomplete asset entry {:?}", asset);
                        acc
                    }
                }).iter().map(|(src, [dest, perm])| {
                    vec![src.to_string(), dest.to_string(), perm.to_string()]
                }).collect()
            },
            MergeByKey::Dest(assets) => {
                assets.iter().fold(parent, |mut acc, asset| {
                    if let [src, dest, perm, ..] = &asset[..] {
                        if let Some([replaced_src, replaced_perm]) = acc.insert(dest, [src, perm]) {
                            debug!("Replacing {:?} w/ {:?}", [replaced_src, replaced_perm], [src, perm]);
                        }
                        acc
                    } else {
                        warn!("Incomplete asset entry {:?}", asset);
                        acc
                    }
                }).iter().map(|(dest, [src, perm])| {
                    vec![src.to_string(), dest.to_string(), perm.to_string()]
                }).collect()
            },
        }
    }
}

impl CargoDeb {
    /// Inherit unset fields from parent,
    /// 
    /// **Note**: For backwards compat, if merge_assets is set, this will apply **after** the variant has overridden the assets.
    /// 
    fn inherit_from(self, parent: CargoDeb) -> CargoDeb {
        let mut assets = self.assets.or(parent.assets);

        if let (Some(merge_assets), Some(_assets)) = (self.merge_assets, assets.as_mut()) {
            if let Some(mut append) = merge_assets.append {
                _assets.append(&mut append);
            }
            
            if let Some(strategy) = merge_assets.by {
                assets = Some(strategy.merge(_assets));
            }
        }

        CargoDeb {
            name: self.name.or(parent.name),
            maintainer: self.maintainer.or(parent.maintainer),
            copyright: self.copyright.or(parent.copyright),
            license_file: self.license_file.or(parent.license_file),
            changelog: self.changelog.or(parent.changelog),
            depends: self.depends.or(parent.depends),
            pre_depends: self.pre_depends.or(parent.pre_depends),
            recommends: self.recommends.or(parent.recommends),
            suggests: self.suggests.or(parent.suggests),
            enhances: self.enhances.or(parent.enhances),
            conflicts: self.conflicts.or(parent.conflicts),
            breaks: self.breaks.or(parent.breaks),
            replaces: self.replaces.or(parent.replaces),
            provides: self.provides.or(parent.provides),
            extended_description: self.extended_description.or(parent.extended_description),
            extended_description_file: self.extended_description_file.or(parent.extended_description_file),
            section: self.section.or(parent.section),
            priority: self.priority.or(parent.priority),
            revision: self.revision.or(parent.revision),
            conf_files: self.conf_files.or(parent.conf_files),
            assets,
            merge_assets: None,
            triggers_file: self.triggers_file.or(parent.triggers_file),
            maintainer_scripts: self.maintainer_scripts.or(parent.maintainer_scripts),
            features: self.features.or(parent.features),
            default_features: self.default_features.or(parent.default_features),
            separate_debug_symbols: self.separate_debug_symbols.or(parent.separate_debug_symbols),
            preserve_symlinks: self.preserve_symlinks.or(parent.preserve_symlinks),
            systemd_units: self.systemd_units.or(parent.systemd_units),
            variants: self.variants.or(parent.variants),
        }
    }
}

#[derive(Deserialize)]
struct CargoMetadata {
    packages: Vec<CargoMetadataPackage>,
    resolve: CargoMetadataResolve,
    #[serde(default)]
    workspace_members: Vec<String>,
    target_directory: String,
    #[serde(default)]
    workspace_root: String,
}

#[derive(Deserialize)]
struct CargoMetadataResolve {
    root: Option<String>,
}

#[derive(Deserialize)]
struct CargoMetadataPackage {
    pub id: String,
    pub name: String,
    pub targets: Vec<CargoMetadataTarget>,
    pub manifest_path: String,
}

#[derive(Deserialize)]
struct CargoMetadataTarget {
    pub name: String,
    pub kind: Vec<String>,
    pub crate_types: Vec<String>,
    pub src_path: PathBuf,
}

/// Returns the path of the `Cargo.toml` that we want to build.
fn cargo_metadata(manifest_path: Option<&Path>) -> CDResult<CargoMetadata> {
    let mut cmd = Command::new("cargo");
    cmd.arg("metadata");
    cmd.arg("--format-version=1");
    if let Some(path) = manifest_path {
        cmd.arg("--manifest-path");
        cmd.arg(path);
    }

    let output = cmd.output()
        .map_err(|e| CargoDebError::CommandFailed(e, "cargo (is it in your PATH?)"))?;
    if !output.status.success() {
        return Err(CargoDebError::CommandError("cargo", "metadata".to_owned(), output.stderr));
    }

    let stdout = String::from_utf8(output.stdout).unwrap();
    let metadata = serde_json::from_str(&stdout)?;
    Ok(metadata)
}

/// Format conffiles section, ensuring each path has a leading slash
///
/// Starting with [dpkg 1.20.1](https://github.com/guillemj/dpkg/blob/68ab722604217d3ab836276acfc0ae1260b28f5f/debian/changelog#L393),
/// which is what Ubuntu 21.04 uses, relative conf-files are no longer
/// accepted (the deb-conffiles man page states that "they should be listed as
/// absolute pathnames"). So we prepend a leading slash to the given strings
/// as needed
fn format_conffiles<S: AsRef<str>>(files: &[S]) -> String {
    files.iter().fold(String::new(), |mut acc, x| {
        let pth = x.as_ref();
        if !pth.starts_with('/') {
            acc.push('/');
        }
        acc + pth + "\n"
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::tests::add_test_fs_paths;

    #[test]
    fn match_arm_arch() {
        assert_eq!("armhf", debian_architecture_from_rust_triple("arm-unknown-linux-gnueabihf"));
    }

    #[test]
    fn arch_spec() {
        use ArchSpec::*;
        // req
        assert_eq!(
            get_architecture_specification("libjpeg64-turbo [armhf]").expect("arch"),
            ("libjpeg64-turbo".to_owned(), Some(Require("armhf".to_owned()))));
        // neg
        assert_eq!(
            get_architecture_specification("libjpeg64-turbo [!amd64]").expect("arch"),
            ("libjpeg64-turbo".to_owned(), Some(NegRequire("amd64".to_owned()))));
    }

    #[test]
    fn assets() {
        let a = Asset::new(
            AssetSource::Path(PathBuf::from("target/release/bar")),
            PathBuf::from("baz/"),
            0o644,
            IsBuilt::SamePackage,
            false,
        );
        assert_eq!("baz/bar", a.c.target_path.to_str().unwrap());
        assert!(a.c.is_built != IsBuilt::No);

        let a = Asset::new(
            AssetSource::Path(PathBuf::from("foo/bar")),
            PathBuf::from("/baz/quz"),
            0o644,
            IsBuilt::No,
            false,
        );
        assert_eq!("baz/quz", a.c.target_path.to_str().unwrap());
        assert!(a.c.is_built == IsBuilt::No);
    }

    /// Tests that getting the debug filename from a path returns the same path
    /// with ".debug" appended
    #[test]
    fn test_debug_filename() {
        let path = Path::new("/my/test/file");
        assert_eq!(debug_filename(path), Path::new("/my/test/file.debug"));
    }

    /// Tests that getting the debug target for an Asset that `is_built` returns
    /// the path "/usr/lib/debug/<path-to-target>.debug"
    #[test]
    fn test_debug_target_ok() {
        let a = Asset::new(
            AssetSource::Path(PathBuf::from("target/release/bar")),
            PathBuf::from("/usr/bin/baz/"),
            0o644,
            IsBuilt::SamePackage,
            false,
        );
        let debug_target = a.c.debug_target().expect("Got unexpected None");
        assert_eq!(debug_target, Path::new("/usr/lib/debug/usr/bin/baz/bar.debug"));
    }

    /// Tests that getting the debug target for an Asset that `is_built` and that
    /// has a relative path target returns the path "/usr/lib/debug/<path-to-target>.debug"
    #[test]
    fn test_debug_target_ok_relative() {
        let a = Asset::new(
            AssetSource::Path(PathBuf::from("target/release/bar")),
            PathBuf::from("baz/"),
            0o644,
            IsBuilt::Workspace,
            false,
        );
        let debug_target = a.c.debug_target().expect("Got unexpected None");
        assert_eq!(debug_target, Path::new("/usr/lib/debug/baz/bar.debug"));
    }

    /// Tests that getting the debug target for an Asset that with `is_built` false
    /// returns None
    #[test]
    fn test_debug_target_not_built() {
        let a = Asset::new(
            AssetSource::Path(PathBuf::from("target/release/bar")),
            PathBuf::from("baz/"),
            0o644,
            IsBuilt::No,
            false,
        );

        assert_eq!(a.c.debug_target(), None);
    }

    /// Tests that debug_source() for an AssetSource::Path returns the same path
    /// but with ".debug" appended
    #[test]
    fn test_debug_source_path() {
        let a = AssetSource::Path(PathBuf::from("target/release/bar"));

        let debug_source = a.debug_source().expect("Got unexpected None");
        assert_eq!(debug_source, Path::new("target/release/bar.debug"));
    }

    /// Tests that debug_source() for an AssetSource::Data returns None
    #[test]
    fn test_debug_source_data() {
        let data: Vec<u8> = Vec::new();
        let a = AssetSource::Data(data);

        assert_eq!(a.debug_source(), None);
    }

    fn to_canon_static_str(s: &str) -> &'static str {
        let cwd = std::env::current_dir().unwrap();
        let abs_path = cwd.join(s);
        let abs_path_string = abs_path.to_string_lossy().into_owned();
        Box::leak(abs_path_string.into_boxed_str())
    }

    #[test]
    fn add_systemd_assets_with_no_config_does_nothing() {
        let mut mock_listener = crate::listener::MockListener::new();
        mock_listener.expect_info().return_const(());

        // supply a systemd unit file as if it were available on disk
        let _g = add_test_fs_paths(&[to_canon_static_str("cargo-deb.service")]);

        let config = Config::from_manifest(Some(Path::new("Cargo.toml")), None, None, None, None, None, None, &mock_listener, "release").unwrap();

        let num_unit_assets = config.assets.resolved.iter()
            .filter(|a| a.c.target_path.starts_with("lib/systemd/system/"))
            .count();

        assert_eq!(0, num_unit_assets);
    }

    #[test]
    fn add_systemd_assets_with_config_adds_unit_assets() {
        let mut mock_listener = crate::listener::MockListener::new();
        mock_listener.expect_info().return_const(());

        // supply a systemd unit file as if it were available on disk
        let _g = add_test_fs_paths(&[to_canon_static_str("cargo-deb.service")]);

        let mut config = Config::from_manifest(Some(Path::new("Cargo.toml")), None, None, None, None, None, None, &mock_listener, "release").unwrap();

        config.systemd_units.get_or_insert(vec![SystemdUnitsConfig::default()]);
        config.maintainer_scripts.get_or_insert(PathBuf::new());

        config.add_systemd_assets().unwrap();

        let num_unit_assets = config.assets.resolved
            .iter()
            .filter(|a| a.c.target_path.starts_with("lib/systemd/system/"))
            .count();

        assert_eq!(1, num_unit_assets);
    }

    #[test]
    fn format_conffiles_empty() {
        let actual = format_conffiles::<String>(&[]);
        assert_eq!("", actual);
    }

    #[test]
    fn format_conffiles_one() {
        let actual = format_conffiles(&["/etc/my-pkg/conf.toml"]);
        assert_eq!("/etc/my-pkg/conf.toml\n", actual);
    }

    #[test]
    fn format_conffiles_multiple() {
        let actual = format_conffiles(&["/etc/my-pkg/conf.toml", "etc/my-pkg/conf2.toml"]);

        assert_eq!("/etc/my-pkg/conf.toml\n/etc/my-pkg/conf2.toml\n", actual);
    }

    #[test]
    fn test_merge_assets() {
        // Test merging assets by dest
        fn create_test_asset(src: impl Into<String>, dest: impl Into<String>, perm: impl Into<String>) -> Vec<String> {
            vec![src.into(), dest.into(), perm.into()]
        }

        // Test merging assets by dest
        let original_asset = create_test_asset(
            "lib/test/empty.txt",
            "/opt/test/empty.txt",
            "777"
        );

        let merge_asset = create_test_asset(
            "lib/test_variant/empty.txt",
            "/opt/test/empty.txt",
            "655"
        );

        let parent = CargoDeb { assets: Some(vec![ original_asset ]), .. Default::default() };
        let variant = CargoDeb { merge_assets: Some(MergeAssets { append: None, by: Some(MergeByKey::Dest(vec![ merge_asset ])) }), .. Default::default() };

        let merged = variant.inherit_from(parent);
        let mut merged = merged.assets.expect("should have assets");
        let merged_asset = merged.pop().expect("should have an asset");
        assert_eq!("lib/test_variant/empty.txt", merged_asset[0].as_str(), "should have merged the source location");
        assert_eq!("/opt/test/empty.txt", merged_asset[1].as_str(), "should preserve dest location");
        assert_eq!("655", merged_asset[2].as_str(), "should have merged the dest location");

        // Test merging assets by src
        let original_asset = create_test_asset(
            "lib/test/empty.txt",
            "/opt/test/empty.txt",
            "777"
        );

        let merge_asset = create_test_asset(
            "lib/test/empty.txt",
            "/opt/test_variant/empty.txt",
            "655"
        );

        let parent = CargoDeb { assets: Some(vec![ original_asset ]), .. Default::default() };
        let variant = CargoDeb { merge_assets: Some(MergeAssets { append: None, by: Some(MergeByKey::Src(vec![ merge_asset ])) }), .. Default::default() };

        let merged = variant.inherit_from(parent);
        let mut merged = merged.assets.expect("should have assets");
        let merged_asset = merged.pop().expect("should have an asset");
        assert_eq!("lib/test/empty.txt", merged_asset[0].as_str(), "should have merged the source location");
        assert_eq!("/opt/test_variant/empty.txt", merged_asset[1].as_str(), "should preserve dest location");
        assert_eq!("655", merged_asset[2].as_str(), "should have merged the dest location");

        // Test merging assets by appending
        let original_asset = create_test_asset(
            "lib/test/empty.txt",
            "/opt/test/empty.txt",
            "777"
        );

        let merge_asset = create_test_asset(
            "lib/test/empty.txt",
            "/opt/test_variant/empty.txt",
            "655"
        );
        
        let parent = CargoDeb { assets: Some(vec![ original_asset ]), .. Default::default() };
        let variant = CargoDeb { merge_assets: Some(MergeAssets { append: Some(vec![merge_asset]), by: None }), .. Default::default() };
        
        let merged = variant.inherit_from(parent);
        let mut merged = merged.assets.expect("should have assets");
        
        let merged_asset = merged.pop().expect("should have an asset");
        assert_eq!("lib/test/empty.txt", merged_asset[0].as_str(), "should have merged the source location");
        assert_eq!("/opt/test_variant/empty.txt", merged_asset[1].as_str(), "should preserve dest location");
        assert_eq!("655", merged_asset[2].as_str(), "should have merged the dest location");

        let merged_asset = merged.pop().expect("should have an asset");
        assert_eq!("lib/test/empty.txt", merged_asset[0].as_str(), "should have merged the source location");
        assert_eq!("/opt/test/empty.txt", merged_asset[1].as_str(), "should preserve dest location");
        assert_eq!("777", merged_asset[2].as_str(), "should have merged the dest location");

        // Test backwards compatibility for variants that have set assets
        let original_asset = create_test_asset(
            "lib/test/empty.txt",
            "/opt/test/empty.txt",
            "777"
        );

        let merge_asset = create_test_asset(
            "lib/test_variant/empty.txt",
            "/opt/test/empty.txt",
            "655"
        );

        let additional_asset = create_test_asset(
            "lib/test/other-empty.txt",
            "/opt/test/other-empty.txt",
            "655"
        );

        let parent = CargoDeb { assets: Some(vec![ original_asset ]), .. Default::default() };
        let variant = CargoDeb { merge_assets: Some(MergeAssets { append: None, by: Some(MergeByKey::Dest(vec![ merge_asset.clone() ])) }), assets: Some(vec![ merge_asset, additional_asset ]), .. Default::default() };

        let merged = variant.inherit_from(parent);
        let mut merged = merged.assets.expect("should have assets");
        let merged_asset = merged.remove(0);
        assert_eq!("lib/test_variant/empty.txt", merged_asset[0].as_str(), "should have merged the source location");
        assert_eq!("/opt/test/empty.txt", merged_asset[1].as_str(), "should preserve dest location");
        assert_eq!("655", merged_asset[2].as_str(), "should have merged the dest location");

        let additional_asset = merged.remove(0);
        assert_eq!("lib/test/other-empty.txt", additional_asset[0].as_str(), "should have merged the source location");
        assert_eq!("/opt/test/other-empty.txt", additional_asset[1].as_str(), "should preserve dest location");
        assert_eq!("655", additional_asset[2].as_str(), "should have merged the dest location");
    }
}

#[test]
fn deb_ver() {
    let mut c = cargo_toml::Package::new("test", "1.2.3-1");
    assert_eq!("1.2.3-1-1", manifest_version_string(&c, None));
    assert_eq!("1.2.3-1-2", manifest_version_string(&c, Some("2")));
    assert_eq!("1.2.3-1", manifest_version_string(&c, Some("")));
    c.version = cargo_toml::Inheritable::Set("1.2.0-beta.3".into());
    assert_eq!("1.2.0~beta.3-1", manifest_version_string(&c, None));
    assert_eq!("1.2.0~beta.3-4", manifest_version_string(&c, Some("4")));
    assert_eq!("1.2.0~beta.3", manifest_version_string(&c, Some("")));
    c.version = cargo_toml::Inheritable::Set("1.2.0-new".into());
    assert_eq!("1.2.0-new-1", manifest_version_string(&c, None));
    assert_eq!("1.2.0-new-11", manifest_version_string(&c, Some("11")));
    assert_eq!("1.2.0-new", manifest_version_string(&c, Some("")));
}