cabinpkg 0.15.0

A package manager and build system for C/C++
Documentation
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
use super::*;
use flate2::Compression;
use flate2::write::GzEncoder;
use sha2::Digest;
use std::fs::File;
use std::io::Write;

fn manifest_for(name: &str, version: &str, deps: &[(&str, &str)]) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    writeln!(out, "[package]\nname = \"{name}\"\nversion = \"{version}\"").unwrap();
    if !deps.is_empty() {
        out.push_str("\n[dependencies]\n");
        for (name, req) in deps {
            writeln!(out, "{name} = \"{req}\"").unwrap();
        }
    }
    out
}

/// Build a `.tar.gz` containing the given file entries (relative
/// path -> body). Returns the archive path and its `sha256` hex.
/// Same as [`make_archive`] but the caller chooses the entry type
/// and writes the path bytes directly so we can construct unsafe
/// archive entries that the tar crate's safe API would refuse.
fn make_archive_with_raw_name(
    path: &Path,
    raw_name: &str,
    entry_type: tar::EntryType,
    body: &[u8],
) -> String {
    if let Some(parent) = path.parent() {
        assert_fs::fixture::ChildPath::new(parent)
            .create_dir_all()
            .unwrap();
    }
    let f = File::create(path).unwrap();
    let enc = GzEncoder::new(f, Compression::default());
    let mut builder = tar::Builder::new(enc);
    let mut header = tar::Header::new_old();
    header.set_size(body.len() as u64);
    header.set_mode(0o644);
    header.set_entry_type(entry_type);
    {
        let bytes = raw_name.as_bytes();
        let old = header.as_old_mut();
        for b in &mut old.name[..] {
            *b = 0;
        }
        let n = bytes.len().min(old.name.len());
        old.name[..n].copy_from_slice(&bytes[..n]);
    }
    header.set_cksum();
    builder.append(&header, body).unwrap();
    let enc = builder.into_inner().unwrap();
    enc.finish().unwrap().flush().unwrap();
    sha256_hex(path)
}

fn sha256_hex(path: &Path) -> String {
    let bytes = fs::read(path).unwrap();
    let mut hasher = sha2::Sha256::new();
    hasher.update(&bytes);
    cabin_core::hash::hex_digest(&hasher.finalize())
}

fn fmt_archive_entries() -> Vec<(&'static str, &'static str)> {
    vec![
        ("cabin.toml", FMT_PKG_MANIFEST),
        ("include/fmt.h", FMT_HEADER),
        ("src/fmt.cc", FMT_SRC),
    ]
}

const FMT_PKG_MANIFEST: &str = r#"[package]
name = "fmt"
version = "10.2.1"

[target.fmt]
type = "library"
sources = ["src/fmt.cc"]
include_dirs = ["include"]
"#;

const FMT_HEADER: &str = "#pragma once\nvoid say_hello();\n";

const FMT_SRC: &str = "#include <iostream>\n#include \"fmt.h\"\nvoid say_hello() { std::cout << \"hello from fmt\\n\"; }\n";

const APP_MAIN: &str = "#include \"fmt.h\"\nint main() { say_hello(); return 0; }\n";

/// Write an `app/` package whose root manifest depends on
/// `fmt = ">=10 <11"` plus a `[target.app]` linking against `fmt`.
fn write_app_using_fmt(dir: &Path) {
    let manifest = r#"[package]
name = "app"
version = "0.1.0"

[dependencies]
fmt = ">=10.0.0 <11.0.0"

[target.app]
type = "executable"
sources = ["src/main.cc"]
deps = ["fmt"]
"#;
    assert_fs::fixture::ChildPath::new(dir.join("app/cabin.toml"))
        .write_str(manifest)
        .unwrap();
    assert_fs::fixture::ChildPath::new(dir.join("app/src/main.cc"))
        .write_str(APP_MAIN)
        .unwrap();
}

#[test]
fn fetch_extracts_registry_package_into_cache() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );

    let cache = dir.path().join("cache");
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .success();

    // Lockfile written next to root manifest.
    let lock_path = dir.path().join("app/cabin.lock");
    assert!(lock_path.is_file(), "cabin.lock should exist");
    let lock_body = fs::read_to_string(&lock_path).unwrap();
    assert!(lock_body.contains(r#"name = "fmt""#));
    assert!(lock_body.contains(&format!("checksum = \"sha256:{hex}\"")));

    // Archive present in the checksum-addressed cache.
    let archive_in_cache = cache.join("archives/sha256").join(format!("{hex}.tar.gz"));
    assert!(archive_in_cache.is_file(), "archive should be cached");
    // Source extracted with cabin.toml at root.
    let source_in_cache = cache.join("sources/sha256").join(&hex);
    assert!(source_in_cache.join("cabin.toml").is_file());
}

#[test]
fn fetch_emits_json_when_requested() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );
    let cache = dir.path().join("cache");
    let value = run_json(
        cabin()
            .args(["fetch", "--manifest-path"])
            .arg(dir.path().join("app/cabin.toml"))
            .arg("--index-path")
            .arg(dir.path().join("index"))
            .arg("--cache-dir")
            .arg(&cache)
            .args(["--format", "json"]),
    );
    let pkgs = value["packages"].as_array().unwrap();
    assert_eq!(pkgs.len(), 1);
    assert_eq!(pkgs[0]["name"], "fmt");
    assert_eq!(pkgs[0]["version"], "10.2.1");
    assert_eq!(pkgs[0]["checksum"], format!("sha256:{hex}"));
}

#[test]
fn build_links_against_registry_package() {
    require_cxx_build_tools();
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );

    let build_dir = dir.path().join("build");
    let cache = dir.path().join("cache");
    cabin()
        .args(["build", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .arg("--build-dir")
        .arg(&build_dir)
        .assert()
        .success();

    assert!(build_dir.join("dev").join("build.ninja").is_file());
    assert!(
        build_dir
            .join("dev")
            .join("compile_commands.json")
            .is_file()
    );
    let exe = build_dir.join("dev/packages/app").join(host_exe("app"));
    assert!(exe.is_file(), "executable should exist at {exe:?}");
    let output = std::process::Command::new(&exe).output().unwrap();
    assert!(String::from_utf8_lossy(&output.stdout).contains("hello from fmt"));
}

#[test]
fn build_handles_transitive_registry_dependency() {
    require_cxx_build_tools();
    let dir = TempDir::new().unwrap();

    // Root depends only on spdlog; spdlog depends on fmt.
    let app_manifest = r#"[package]
name = "app"
version = "0.1.0"

[dependencies]
spdlog = ">=1.0.0 <2.0.0"

[target.app]
type = "executable"
sources = ["src/main.cc"]
deps = ["spdlog"]
"#;
    let app_main = "#include \"spdlog.h\"\nint main() { log_hello(); return 0; }\n";
    dir.child("app/cabin.toml").write_str(app_manifest).unwrap();
    dir.child("app/src/main.cc").write_str(app_main).unwrap();

    // fmt archive (library).
    let fmt_archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let fmt_hex = make_archive(&fmt_archive, &fmt_archive_entries());

    // spdlog archive: library that depends on fmt.
    let spdlog_manifest = r#"[package]
name = "spdlog"
version = "1.13.0"

[dependencies]
fmt = ">=10.0.0 <11.0.0"

[target.spdlog]
type = "library"
sources = ["src/spdlog.cc"]
include_dirs = ["include"]
deps = ["fmt"]
"#;
    let spdlog_header = "#pragma once\nvoid log_hello();\n";
    let spdlog_src =
        "#include \"spdlog.h\"\n#include \"fmt.h\"\nvoid log_hello() { say_hello(); }\n";
    let spdlog_archive = dir.path().join("artifacts/spdlog-1.13.0.tar.gz");
    let spdlog_hex = make_archive(
        &spdlog_archive,
        &[
            ("cabin.toml", spdlog_manifest),
            ("include/spdlog.h", spdlog_header),
            ("src/spdlog.cc", spdlog_src),
        ],
    );

    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &fmt_hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );
    write_index_entry(
        &dir.path().join("index"),
        "spdlog",
        "1.13.0",
        r#"{ "fmt": ">=10.0.0 <11.0.0" }"#,
        &spdlog_hex,
        "../artifacts/spdlog-1.13.0.tar.gz",
    );

    let build_dir = dir.path().join("build");
    let cache = dir.path().join("cache");
    cabin()
        .args(["build", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .arg("--build-dir")
        .arg(&build_dir)
        .assert()
        .success();

    // Both packages should have been fetched and built.
    assert!(
        cache
            .join("sources/sha256")
            .join(&fmt_hex)
            .join("cabin.toml")
            .is_file()
    );
    assert!(
        cache
            .join("sources/sha256")
            .join(&spdlog_hex)
            .join("cabin.toml")
            .is_file()
    );
    assert!(
        build_dir
            .join("dev/packages/fmt")
            .join(host_static_lib("fmt"))
            .is_file()
    );
    assert!(
        build_dir
            .join("dev/packages/spdlog")
            .join(host_static_lib("spdlog"))
            .is_file()
    );
    assert!(
        build_dir
            .join("dev/packages/app")
            .join(host_exe("app"))
            .is_file()
    );
}

#[test]
fn fetch_fails_on_checksum_mismatch() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    make_archive(&archive, &fmt_archive_entries());
    // Index advertises a checksum that doesn't match the archive's
    // actual bytes.
    let bogus_hex = "0".repeat(64);
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &bogus_hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );

    let cache = dir.path().join("cache");
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .failure()
        .stderr(predicate::str::contains("checksum mismatch"));
}

#[test]
fn fetch_rejects_unsafe_archive() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex =
        make_archive_with_raw_name(&archive, "../escape.txt", tar::EntryType::Regular, b"evil");
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );
    let cache = dir.path().join("cache");
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .failure()
        .stderr(predicate::str::contains("unsafe archive entry"));
    // Nothing escaped the cache.
    assert!(!dir.path().join("escape.txt").exists());
}

#[test]
fn fetch_fails_when_index_has_no_source() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry_no_source(&dir.path().join("index"), "fmt", "10.2.1", &hex);

    let cache = dir.path().join("cache");
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .failure()
        .stderr(predicate::str::contains("no source artifact"));
}

#[test]
fn frozen_uses_cache_after_initial_fetch() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );

    let cache = dir.path().join("cache");
    // Populate cache normally.
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .success();
    // Now move the source archive away and re-run with --frozen;
    // cache hit should let it succeed.
    fs::remove_file(&archive).unwrap();
    cabin()
        .args(["fetch", "--frozen", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .success();
}

#[test]
fn frozen_fails_on_cache_miss() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );
    // Pre-populate a lockfile so --frozen can run resolution.
    cabin()
        .args(["resolve", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .assert()
        .success();

    let empty_cache = dir.path().join("empty-cache");
    cabin()
        .args(["fetch", "--frozen", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&empty_cache)
        .assert()
        .failure()
        .stderr(predicate::str::contains("--frozen"))
        .stderr(predicate::str::contains("not cached"));
}

#[test]
fn frozen_does_not_write_lockfile_or_cache() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );

    // No lockfile, no cache pre-populated. --frozen must refuse.
    let cache = dir.path().join("cache");
    cabin()
        .args(["fetch", "--frozen", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .failure();
    // Lockfile must not have been created by the failed run.
    assert!(!dir.path().join("app/cabin.lock").exists());
    // Cache must not have been populated by the failed run.
    let archive_in_cache = cache.join("archives/sha256").join(format!("{hex}.tar.gz"));
    assert!(!archive_in_cache.exists());
}

#[test]
fn fetch_fails_when_archive_manifest_disagrees() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    // Archive declares fmt 10.1.0 but the index promises 10.2.1.
    let mut entries = fmt_archive_entries();
    entries[0].1 = r#"[package]
name = "fmt"
version = "10.1.0"
"#;
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &entries);
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );
    let cache = dir.path().join("cache");
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .failure()
        .stderr(predicate::str::contains("contains package"));
}

#[test]
fn fetch_with_no_versioned_deps_succeeds() {
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_for("solo", "0.1.0", &[]))
        .unwrap();
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("cabin.toml"))
        .assert()
        .success()
        .stdout(predicate::str::contains("(no registry dependencies"));
}

#[test]
fn build_uses_separate_cache_dir_when_specified() {
    let dir = TempDir::new().unwrap();
    write_app_using_fmt(dir.path());
    let archive = dir.path().join("artifacts/fmt-10.2.1.tar.gz");
    let hex = make_archive(&archive, &fmt_archive_entries());
    write_index_entry(
        &dir.path().join("index"),
        "fmt",
        "10.2.1",
        "{}",
        &hex,
        "../artifacts/fmt-10.2.1.tar.gz",
    );

    let cache = dir.path().join("alt-cache");
    cabin()
        .args(["fetch", "--manifest-path"])
        .arg(dir.path().join("app/cabin.toml"))
        .arg("--index-path")
        .arg(dir.path().join("index"))
        .arg("--cache-dir")
        .arg(&cache)
        .assert()
        .success();
    assert!(
        cache
            .join("archives/sha256")
            .join(format!("{hex}.tar.gz"))
            .is_file()
    );
    // Default cache must NOT have been populated.
    assert!(!dir.path().join("app/.cabin/cache").exists());
}