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
use crate::dh_installsystemd;
use crate::dh_lib;
use crate::error::*;
use crate::listener::Listener;
use crate::manifest::Config;
use crate::pathbytes::*;
use crate::tararchive::Archive;
use crate::util::{is_path_file, read_file_to_bytes};
use crate::wordsplit::WordSplit;
use dh_lib::ScriptFragments;
use md5::Digest;
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
pub fn generate_archive<W: Write>(dest: W, options: &Config, time: u64, asset_hashes: HashMap<PathBuf, Digest>, listener: &dyn Listener) -> CDResult<W> {
let mut archive = Archive::new(dest, time);
generate_md5sums(&mut archive, options, asset_hashes)?;
generate_control(&mut archive, options, listener)?;
if let Some(ref files) = options.conf_files {
generate_conf_files(&mut archive, files)?;
}
generate_scripts(&mut archive, options, listener)?;
if let Some(ref file) = options.triggers_file {
let triggers_file = &options.pacakge_manifest_dir.as_path().join(file);
if !triggers_file.exists() {
return Err(CargoDebError::AssetFileNotFound(file.to_path_buf()));
}
generate_triggers_file(&mut archive, triggers_file)?;
}
Ok(archive.into_inner()?)
}
fn generate_scripts<W: Write>(archive: &mut Archive<W>, option: &Config, listener: &dyn Listener) -> CDResult<()> {
if let Some(ref maintainer_scripts_dir) = option.maintainer_scripts {
let maintainer_scripts_dir = option.pacakge_manifest_dir.as_path().join(maintainer_scripts_dir);
let mut scripts;
if let Some(systemd_units_config) = &option.systemd_units {
scripts = dh_installsystemd::generate(
&option.name,
&option.assets.resolved,
&dh_installsystemd::Options::from(systemd_units_config),
listener,
)?;
let unit_name = systemd_units_config.unit_name.as_deref();
dh_lib::apply(
&maintainer_scripts_dir,
&mut scripts,
&option.name,
unit_name,
listener)?;
} else {
scripts = ScriptFragments::with_capacity(0);
}
for name in &["config", "preinst", "postinst", "prerm", "postrm", "templates"] {
let mut script = scripts.remove(&name.to_string());
if script.is_none() {
let script_path = maintainer_scripts_dir.join(name);
if is_path_file(&script_path) {
script = Some(read_file_to_bytes(&script_path)?);
}
}
if let Some(contents) = script {
let permissions = if *name == "templates" { 0o644 } else { 0o755 };
archive.file(name, &contents, permissions)?;
}
}
}
Ok(())
}
fn generate_md5sums<W: Write>(archive: &mut Archive<W>, options: &Config, asset_hashes: HashMap<PathBuf, Digest>) -> CDResult<()> {
let mut md5sums: Vec<u8> = Vec::new();
for asset in &options.assets.resolved {
if let Some(value) = asset_hashes.get(&asset.c.target_path) {
write!(md5sums, "{:x}", value)?;
md5sums.write_all(b" ")?;
md5sums.write_all(&asset.c.target_path.as_path().as_unix_path())?;
md5sums.write_all(&[b'\n'])?;
}
}
archive.file("./md5sums", &md5sums, 0o644)?;
Ok(())
}
fn generate_control<W: Write>(archive: &mut Archive<W>, options: &Config, listener: &dyn Listener) -> CDResult<()> {
let mut control: Vec<u8> = Vec::with_capacity(1024);
writeln!(&mut control, "Package: {}", options.deb_name)?;
writeln!(&mut control, "Version: {}", options.deb_version)?;
writeln!(&mut control, "Architecture: {}", options.architecture)?;
if let Some(ref repo) = options.repository {
if repo.starts_with("http") {
writeln!(&mut control, "Vcs-Browser: {repo}")?;
}
if let Some(kind) = options.repository_type() {
writeln!(&mut control, "Vcs-{kind}: {repo}")?;
}
}
if let Some(homepage) = options.homepage.as_ref().or(options.documentation.as_ref()) {
writeln!(&mut control, "Homepage: {homepage}")?;
}
if let Some(ref section) = options.section {
writeln!(&mut control, "Section: {section}")?;
}
writeln!(&mut control, "Priority: {}", options.priority)?;
writeln!(&mut control, "Maintainer: {}", options.maintainer)?;
let installed_size = options.assets.resolved
.iter()
.map(|m| (m.source.file_size().unwrap_or(0)+2047)/1024) .sum::<u64>();
writeln!(&mut control, "Installed-Size: {installed_size}")?;
let deps = options.get_dependencies(listener)?;
if !deps.is_empty() {
writeln!(&mut control, "Depends: {deps}")?;
}
if let Some(ref pre_depends) = options.pre_depends {
let pre_depends_normalized = pre_depends.trim();
if !pre_depends_normalized.is_empty() {
writeln!(&mut control, "Pre-Depends: {pre_depends_normalized}")?;
}
}
if let Some(ref recommends) = options.recommends {
let recommends_normalized = recommends.trim();
if !recommends_normalized.is_empty() {
writeln!(&mut control, "Recommends: {recommends_normalized}")?;
}
}
if let Some(ref suggests) = options.suggests {
let suggests_normalized = suggests.trim();
if !suggests_normalized.is_empty() {
writeln!(&mut control, "Suggests: {suggests_normalized}")?;
}
}
if let Some(ref enhances) = options.enhances {
let enhances_normalized = enhances.trim();
if !enhances_normalized.is_empty() {
writeln!(&mut control, "Enhances: {enhances_normalized}")?;
}
}
if let Some(ref conflicts) = options.conflicts {
writeln!(&mut control, "Conflicts: {conflicts}")?;
}
if let Some(ref breaks) = options.breaks {
writeln!(&mut control, "Breaks: {breaks}")?;
}
if let Some(ref replaces) = options.replaces {
writeln!(&mut control, "Replaces: {replaces}")?;
}
if let Some(ref provides) = options.provides {
writeln!(&mut control, "Provides: {provides}")?;
}
write!(&mut control, "Description:")?;
for line in options.description.split_by_chars(79) {
writeln!(&mut control, " {line}")?;
}
if let Some(ref desc) = options.extended_description {
for line in desc.split_by_chars(79) {
writeln!(&mut control, " {line}")?;
}
}
control.push(10);
archive.file("./control", &control, 0o644)?;
Ok(())
}
fn generate_conf_files<W: Write>(archive: &mut Archive<W>, files: &str) -> CDResult<()> {
let mut data = Vec::new();
data.write_all(files.as_bytes())?;
data.push(b'\n');
archive.file("./conffiles", &data, 0o644)?;
Ok(())
}
fn generate_triggers_file<W: Write>(archive: &mut Archive<W>, path: &Path) -> CDResult<()> {
if let Ok(content) = fs::read(path) {
archive.file("./triggers", &content, 0o644)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::manifest::{Asset, AssetSource, SystemdUnitsConfig, IsBuilt};
use crate::util::tests::{add_test_fs_paths, set_test_fs_path_content};
use std::io::prelude::Read;
fn filename_from_path_str(path: &str) -> String {
Path::new(path)
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
}
fn decode_name<R>(entry: &tar::Entry<R>) -> String where R: Read {
std::str::from_utf8(&entry.path_bytes()).unwrap().to_string()
}
fn decode_names<R>(ar: &mut tar::Archive<R>) -> Vec<String> where R: Read {
ar.entries().unwrap().map(|e| decode_name(&e.unwrap())).collect()
}
fn extract_contents<R>(ar: &mut tar::Archive<R>) -> HashMap<String, String> where R: Read {
let mut out = HashMap::new();
for entry in ar.entries().unwrap() {
let mut unwrapped = entry.unwrap();
let name = decode_name(&unwrapped);
let mut buf = Vec::new();
unwrapped.read_to_end(&mut buf).unwrap();
let content = String::from_utf8(buf).unwrap();
out.insert(name, content);
}
out
}
fn prepare<W: Write>(dest: W, package_name: Option<&str>) -> (Config, crate::listener::MockListener, Archive<W>) {
let mut mock_listener = crate::listener::MockListener::new();
mock_listener.expect_info().return_const(());
let mut config = Config::from_manifest(
Path::new("test-resources/testroot/Cargo.toml"),
package_name,
None,
None,
None,
None,
None,
&mock_listener,
"release",
)
.unwrap();
config.pacakge_manifest_dir = config.pacakge_manifest_dir.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().to_path_buf();
let ar = Archive::new(dest, 0);
(config, mock_listener, ar)
}
#[test]
fn generate_scripts_does_nothing_if_maintainer_scripts_is_not_set() {
let (config, mock_listener, mut in_ar) = prepare(vec![], None);
let _g = add_test_fs_paths(&["debian/postinst"]);
generate_scripts(&mut in_ar, &config, &mock_listener).unwrap();
let archive_bytes = in_ar.into_inner().unwrap();
let mut out_ar = tar::Archive::new(&archive_bytes[..]);
let archived_file_names = decode_names(&mut out_ar);
assert!(archived_file_names.is_empty());
}
#[test]
fn generate_scripts_archives_user_supplied_maintainer_scripts_in_root_package() {
let maintainer_script_paths = vec![
"test-resources/testroot/debian/config",
"test-resources/testroot/debian/preinst",
"test-resources/testroot/debian/postinst",
"test-resources/testroot/debian/prerm",
"test-resources/testroot/debian/postrm",
"test-resources/testroot/debian/templates",
];
generate_scripts_for_package_without_systemd_unit(None, &maintainer_script_paths);
}
#[test]
fn generate_scripts_archives_user_supplied_maintainer_scripts_in_workspace_package() {
let maintainer_script_paths = vec![
"test-resources/testroot/testchild/debian/config",
"test-resources/testroot/testchild/debian/preinst",
"test-resources/testroot/testchild/debian/postinst",
"test-resources/testroot/testchild/debian/prerm",
"test-resources/testroot/testchild/debian/postrm",
"test-resources/testroot/testchild/debian/templates",
];
generate_scripts_for_package_without_systemd_unit(Some("testchild"), &maintainer_script_paths);
}
fn generate_scripts_for_package_without_systemd_unit(package_name: Option<&str>, maintainer_script_paths: &[&'static str]) {
let (mut config, mock_listener, mut in_ar) = prepare(vec![], package_name);
let mut maintainer_script_contents = Vec::new();
for script in maintainer_script_paths.iter() {
let content = format!("some contents: {script}");
set_test_fs_path_content(script, content.clone());
maintainer_script_contents.push(content);
}
config.maintainer_scripts.get_or_insert(PathBuf::from("debian"));
generate_scripts(&mut in_ar, &config, &mock_listener).unwrap();
let archive_bytes = in_ar.into_inner().unwrap();
let mut out_ar = tar::Archive::new(&archive_bytes[..]);
let archived_content = extract_contents(&mut out_ar);
assert_eq!(maintainer_script_paths.len(), archived_content.len());
for script in maintainer_script_paths.iter() {
let expected_content = &format!("some contents: {script}");
let filename = filename_from_path_str(script);
let actual_content = archived_content.get(&filename).unwrap();
assert_eq!(expected_content, actual_content);
}
}
#[test]
fn generate_scripts_augments_maintainer_scripts_for_unit_in_root_package() {
let maintainer_scripts = vec![
("test-resources/testroot/debian/config", Some("dummy content")),
("test-resources/testroot/debian/preinst", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/debian/postinst", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/debian/prerm", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/debian/postrm", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/debian/templates", Some("dummy content")),
];
generate_scripts_for_package_with_systemd_unit(None, &maintainer_scripts, "test-resources/testroot/debian/some.service");
}
#[test]
fn generate_scripts_augments_maintainer_scripts_for_unit_in_workspace_package() {
let maintainer_scripts = vec![
("test-resources/testroot/testchild/debian/config", Some("dummy content")),
("test-resources/testroot/testchild/debian/preinst", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/testchild/debian/postinst", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/testchild/debian/prerm", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/testchild/debian/postrm", Some("dummy content\n#DEBHELPER#")),
("test-resources/testroot/testchild/debian/templates", Some("dummy content")),
];
generate_scripts_for_package_with_systemd_unit(
Some("testchild"),
&maintainer_scripts,
"test-resources/testroot/testchild/debian/some.service",
);
}
#[test]
fn generate_scripts_generates_missing_maintainer_scripts_for_unit_in_root_package() {
let maintainer_scripts = vec![
("test-resources/testroot/debian/postinst", None),
("test-resources/testroot/debian/prerm", None),
("test-resources/testroot/debian/postrm", None),
];
generate_scripts_for_package_with_systemd_unit(None, &maintainer_scripts, "test-resources/testroot/debian/some.service");
}
#[test]
fn generate_scripts_generates_missing_maintainer_scripts_for_unit_in_workspace_package() {
let maintainer_scripts = vec![
("test-resources/testroot/testchild/debian/postinst", None),
("test-resources/testroot/testchild/debian/prerm", None),
("test-resources/testroot/testchild/debian/postrm", None),
];
generate_scripts_for_package_with_systemd_unit(
Some("testchild"),
&maintainer_scripts,
"test-resources/testroot/testchild/debian/some.service",
);
}
fn generate_scripts_for_package_with_systemd_unit(
package_name: Option<&str>,
maintainer_scripts: &[(&'static str, Option<&'static str>)],
service_file: &'static str,
) {
let (mut config, mock_listener, mut in_ar) = prepare(vec![], package_name);
let mut maintainer_script_contents = Vec::new();
for (script, content) in maintainer_scripts.iter() {
if let Some(content) = content {
set_test_fs_path_content(script, content.to_string());
maintainer_script_contents.push(content);
}
}
set_test_fs_path_content(service_file, "mock service file".to_string());
let source = AssetSource::Path(PathBuf::from(service_file));
let target_path = PathBuf::from(format!("lib/systemd/system/{}", filename_from_path_str(service_file)));
config.assets.resolved.push(Asset::new(source, target_path, 0o000, IsBuilt::No));
config.maintainer_scripts.get_or_insert(PathBuf::from("debian"));
config.systemd_units.get_or_insert(SystemdUnitsConfig::default());
generate_scripts(&mut in_ar, &config, &mock_listener).unwrap();
let archive_bytes = in_ar.into_inner().unwrap();
let mut out_ar = tar::Archive::new(&archive_bytes[..]);
let mut archived_file_names = decode_names(&mut out_ar);
archived_file_names.sort();
let mut expected_maintainer_scripts = maintainer_scripts
.iter()
.map(|(script, _)| filename_from_path_str(script))
.collect::<Vec<String>>();
expected_maintainer_scripts.sort();
assert_eq!(expected_maintainer_scripts, archived_file_names);
let mut out_ar = tar::Archive::new(&archive_bytes[..]);
let unreplaced_placeholders = out_ar
.entries()
.unwrap()
.map(Result::unwrap)
.map(|mut entry| {
let mut v = String::new();
entry.read_to_string(&mut v).unwrap();
v
})
.any(|v| v.contains("#DEBHELPER#"));
assert!(!unreplaced_placeholders);
}
}