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
622
623
use super::*;
use std::path::PathBuf;

/// Locate the bundled fake `pkg-config` binary the same way
/// `cabin-fmt` and `cabin-tidy` locate their fakes: walk up
/// from the test executable to the target dir and look for
/// the named bin. Build with the `test-fake-pkg-config`
/// feature on `cabin-system-deps`.
fn fake_pkg_config_path() -> PathBuf {
    let test_exe = std::env::current_exe().expect("current_exe");
    let mut dir = test_exe
        .parent()
        .expect("test exe should live in a directory")
        .to_path_buf();
    if dir.file_name().and_then(|n| n.to_str()) == Some("deps") {
        dir.pop();
    }
    let candidate = dir.join(format!(
        "cabin-system-deps-fake-pkg-config{}",
        std::env::consts::EXE_SUFFIX
    ));
    assert!(
        candidate.is_file(),
        "expected fake pkg-config at {}; build cabin-system-deps with `--features test-fake-pkg-config`",
        candidate.display()
    );
    candidate
}

/// Pre-built TempDir holding fixture JSON files for the fake
/// pkg-config. Tests call `.write` to publish a module's
/// metadata, then point `CABIN_FAKE_PKG_CONFIG_FIXTURES` at
/// the directory path through the command env.
pub(super) struct Fixtures {
    dir: TempDir,
}

impl Fixtures {
    pub(super) fn new() -> Self {
        Self {
            dir: TempDir::new().expect("tempdir"),
        }
    }

    pub(super) fn write(&self, name: &str, body: &str) {
        assert_fs::fixture::ChildPath::new(self.dir.path().join(format!("{name}.json")))
            .write_str(body)
            .unwrap();
    }

    pub(super) fn path(&self) -> &Path {
        self.dir.path()
    }
}

/// Build a `cabin` command pre-loaded with the fake
/// pkg-config and a freshly-created fixture directory. The
/// caller publishes fixtures via the returned `Fixtures`
/// handle.
pub(super) fn cabin_with_fake_pkg_config(fixtures: &Fixtures) -> Command {
    let mut cmd = cabin();
    cmd.env("CABIN_PKG_CONFIG", fake_pkg_config_path());
    cmd.env("CABIN_FAKE_PKG_CONFIG_FIXTURES", fixtures.path());
    cmd
}

/// Manifest declaring exactly one system dependency. Tests
/// override the requirement / required field by formatting
/// it as needed.
fn manifest_with_system_dep(version: &str, required_clause: &str) -> String {
    format!(
        "[package]\nname = \"hello\"\nversion = \"0.1.0\"\n\n[target.hello]\ntype = \"executable\"\nsources = [\"src/main.cc\"]\n\n[dependencies]\nzlib = {{ version = \"{version}\", system = true{required_clause} }}\n",
    )
}

fn write_hello_main(root: &Path) {
    assert_fs::fixture::ChildPath::new(root.join("src/main.cc"))
        .write_str(HELLO_MAIN_CC)
        .unwrap();
}

#[test]
fn build_succeeds_with_no_system_deps_even_when_pkg_config_missing() {
    let dir = TempDir::new().unwrap();
    dir.child("cabin.toml").write_str(VALID_MANIFEST).unwrap();
    write_hello_main(dir.path());

    let mut cmd = cabin();
    // Point CABIN_PKG_CONFIG at a path that does not exist;
    // because the manifest has no `system = true` deps,
    // Cabin must not try to spawn pkg-config.
    cmd.env("CABIN_PKG_CONFIG", dir.path().join("missing-pkg-config"));
    // metadata exercises the same code path without
    // requiring a real toolchain.
    cmd.current_dir(dir.path())
        .arg("metadata")
        .assert()
        .success();
}

#[test]
fn metadata_reflects_pkg_config_cflags_in_build_flags_per_package() {
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "-I/opt/zlib/include -DZLIB_CONST",
                "libs": "-L/opt/zlib/lib -lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assertion.get_output().stdout).to_string();
    let view: serde_json::Value =
        serde_json::from_str(&stdout).expect("metadata output should be JSON");
    let pkg = package_build_flags(&view);
    let includes: Vec<String> = pkg["include_dirs"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_owned())
        .collect();
    assert!(
        includes.iter().any(|p| p == "/opt/zlib/include"),
        "include dirs must reflect pkg-config -I path: {includes:?}",
    );
    let extra_compile: Vec<String> = pkg["extra_compile_args"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_owned())
        .collect();
    assert!(
        extra_compile.contains(&"-DZLIB_CONST".to_owned()),
        "extra compile args must carry non-include cflags: {extra_compile:?}",
    );
    let extra_link: Vec<String> = pkg["ldflags"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_owned())
        .collect();
    assert_eq!(
        extra_link,
        vec!["-L/opt/zlib/lib".to_owned(), "-lz".to_owned()],
        "pkg-config --libs must reach the planner verbatim and in order",
    );
}

/// Lookup helper: `cabin metadata`'s build flags live under
/// `toolchain.build_flags_per_package.<name>`. Returns the
/// first package's block; only one package is declared in
/// these fixtures.
fn package_build_flags(view: &serde_json::Value) -> &serde_json::Value {
    let per_package = view["toolchain"]["build_flags_per_package"]
        .as_object()
        .expect("toolchain.build_flags_per_package object");
    per_package
        .values()
        .next()
        .expect("at least one package with build flags")
}

#[test]
fn metadata_fails_when_system_dep_is_missing() {
    let fixtures = Fixtures::new();
    // No fixture published; fake pkg-config will report
    // "not found".
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assertion.get_output().stderr).to_string();
    assert!(
        stderr.contains("zlib"),
        "diagnostic should name the missing dep: {stderr}",
    );
    assert!(
        stderr.contains("not found"),
        "diagnostic should describe the failure mode: {stderr}",
    );
}

#[test]
fn metadata_fails_when_system_dep_version_unsatisfied() {
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.1.0",
                "cflags": "",
                "libs": "-lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep(">=2", ""))
        .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assertion.get_output().stderr).to_string();
    assert!(
        stderr.contains("zlib"),
        "diagnostic should name the dep: {stderr}",
    );
    assert!(
        stderr.contains(">=2"),
        "diagnostic should quote the requirement: {stderr}",
    );
    assert!(
        stderr.contains("1.1.0"),
        "diagnostic should report the installed version: {stderr}",
    );
}

#[test]
fn metadata_fails_when_pkg_config_missing_and_system_dep_declared() {
    let fixtures = Fixtures::new();
    let dir = TempDir::new().unwrap();
    let missing_pkg_config = dir.path().join("nope-pkg-config");
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    let mut cmd = cabin();
    cmd.env("CABIN_PKG_CONFIG", &missing_pkg_config);
    cmd.env("CABIN_FAKE_PKG_CONFIG_FIXTURES", fixtures.path());
    let assertion = cmd
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assertion.get_output().stderr).to_string();
    assert!(
        stderr.contains("not found"),
        "diagnostic should mention `not found`: {stderr}",
    );
    assert!(
        stderr.contains("CABIN_PKG_CONFIG"),
        "diagnostic should mention the override env var: {stderr}",
    );
}

#[test]
fn cabin_pkg_config_env_var_overrides_executable() {
    // A fixture-publishing test that depends on the env var
    // being honored. If the env var were ignored, the test
    // would fail to spawn pkg-config and metadata would error.
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "-I/opt/zlib/include",
                "libs": "-lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .success();
}

#[test]
fn manifest_rejects_required_field_on_system_dep() {
    // System dependencies are unconditionally required. The
    // CLI must reject any attempt to declare `required = …`
    // with a diagnostic that explicitly names the offending
    // field — the snippet alone is too weak because the source
    // line happens to contain the field name regardless.
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep(">=1", ", required = false"))
        .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin()
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assertion.get_output().stderr).to_string();
    assert!(
        stderr.contains("unknown field `required`"),
        "diagnostic should call out the unknown field by name: {stderr}",
    );
}

#[test]
fn build_compile_commands_carry_include_paths_from_pkg_config() {
    require_cxx_build_tools();
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "-I/opt/zlib/include -DZLIB_CONST",
                "libs": "-L/opt/zlib/lib -lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    // The default Windows toolchain is MSVC, and Cabin rejects
    // `system = true` dependencies under MSVC: pkg-config emits
    // GNU-style flags (`-I`, `-L`, `-lz`) that `cl` / `link` cannot
    // consume, and on Windows the `.pc` files reference the MinGW
    // ABI. There is nothing to propagate, so the build is refused
    // before any probe runs — assert the actionable diagnostic
    // instead. A GNU/Clang toolchain (the non-Windows default) flows
    // the discovered flags through to the compile and link commands.
    if cfg!(windows) {
        let assertion = cabin_with_fake_pkg_config(&fixtures)
            .current_dir(dir.path())
            .arg("build")
            .assert()
            .failure();
        let stderr = String::from_utf8_lossy(&assertion.get_output().stderr).to_string();
        assert!(
            stderr.contains("not supported with an MSVC toolchain"),
            "MSVC build must reject system dependencies with a clear diagnostic: {stderr}",
        );
        return;
    }

    cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("build")
        .assert()
        .success();

    let ccdb_path = dir.path().join("build/dev/compile_commands.json");
    let ccdb = std::fs::read_to_string(&ccdb_path).expect("compile_commands.json");
    // The planner emits include directories as two argv tokens (`-I`
    // followed by the path), so assert the flag and the path
    // separately rather than requiring a fixed adjacency.
    assert!(
        ccdb.contains("-I ") && ccdb.contains("opt/zlib/include"),
        "compile_commands.json must carry the pkg-config include: {ccdb}",
    );
    assert!(
        ccdb.contains("-DZLIB_CONST"),
        "compile_commands.json must carry pkg-config -D: {ccdb}",
    );

    let ninja_path = dir.path().join("build/dev/build.ninja");
    let ninja = std::fs::read_to_string(&ninja_path).expect("build.ninja");
    assert!(
        ninja.contains("-lz"),
        "build.ninja link command must carry pkg-config -l: {ninja}",
    );
    assert!(
        ninja.contains("-L/opt/zlib/lib"),
        "build.ninja link command must carry pkg-config -L: {ninja}",
    );
}

#[test]
fn fingerprint_moves_when_pkg_config_flags_change() {
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "-I/opt/zlib/include",
                "libs": "-lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    // The metadata view only emits `configuration` (and
    // hence the fingerprint) when the package declares at
    // least one feature. Declare a trivial feature so the
    // fingerprint surface is populated.
    dir.child("cabin.toml")

            .write_str("[package]\nname = \"hello\"\nversion = \"0.1.0\"\n\n[target.hello]\ntype = \"executable\"\nsources = [\"src/main.cc\"]\n\n[features]\ndefault = []\nflag-a = []\n\n[dependencies]\nzlib = { version = \"\", system = true }\n")

            .unwrap();
    write_hello_main(dir.path());

    let stdout1 = String::from_utf8_lossy(
        &cabin_with_fake_pkg_config(&fixtures)
            .current_dir(dir.path())
            .arg("metadata")
            .assert()
            .success()
            .get_output()
            .stdout,
    )
    .to_string();
    let view1: serde_json::Value = serde_json::from_str(&stdout1).unwrap();
    let fp1 = find_fingerprint(&view1);

    // Republish with different libs — the discovered link
    // args change, so the fingerprint must move.
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "-I/opt/zlib/include",
                "libs": "-lz -lother"
            }"#,
    );
    let stdout2 = String::from_utf8_lossy(
        &cabin_with_fake_pkg_config(&fixtures)
            .current_dir(dir.path())
            .arg("metadata")
            .assert()
            .success()
            .get_output()
            .stdout,
    )
    .to_string();
    let view2: serde_json::Value = serde_json::from_str(&stdout2).unwrap();
    let fp2 = find_fingerprint(&view2);

    assert_ne!(
        fp1, fp2,
        "fingerprint must move when discovered pkg-config flags change",
    );
}

/// Walk the metadata view looking for the first build-config
/// fingerprint. Build-configurations live under
/// `configurations.<package>.fingerprint`; the value is a
/// hex string. Robust against schema reshuffles.
fn find_fingerprint(value: &serde_json::Value) -> String {
    fn walk(v: &serde_json::Value) -> Option<String> {
        if let Some(map) = v.as_object() {
            if let Some(fp) = map.get("fingerprint").and_then(|f| f.as_str()) {
                return Some(fp.to_owned());
            }
            for child in map.values() {
                if let Some(found) = walk(child) {
                    return Some(found);
                }
            }
        }
        if let Some(arr) = v.as_array() {
            for item in arr {
                if let Some(found) = walk(item) {
                    return Some(found);
                }
            }
        }
        None
    }
    walk(value).expect("metadata view should expose a fingerprint")
}

#[test]
fn non_matching_target_conditional_system_dep_does_not_require_pkg_config() {
    // Declare a system dep gated on a condition that the
    // host platform cannot match. Cabin must not spawn
    // pkg-config — and the integration test exercises that
    // by pointing `CABIN_PKG_CONFIG` at a non-existent path.
    let dir = TempDir::new().unwrap();
    let unreachable = dir.path().join("never-reached-pkg-config");
    dir.child("cabin.toml")

            .write_str("[package]\nname = \"hello\"\nversion = \"0.1.0\"\n\n[target.hello]\ntype = \"executable\"\nsources = [\"src/main.cc\"]\n\n[target.'cfg(os = \"none-such\")'.dependencies]\nzlib = { version = \"\", system = true }\n")

            .unwrap();
    write_hello_main(dir.path());

    let mut cmd = cabin();
    cmd.env("CABIN_PKG_CONFIG", &unreachable);
    cmd.current_dir(dir.path())
        .arg("metadata")
        .assert()
        .success();
}

#[test]
fn matching_target_conditional_system_dep_is_probed() {
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "-I/opt/zlib/include",
                "libs": "-lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    let host_os = if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(target_os = "linux") {
        "linux"
    } else if cfg!(target_os = "windows") {
        "windows"
    } else {
        "linux"
    };
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))

            .write_str(&format!(
                "[package]\nname = \"hello\"\nversion = \"0.1.0\"\n\n[target.hello]\ntype = \"executable\"\nsources = [\"src/main.cc\"]\n\n[target.'cfg(os = \"{host_os}\")'.dependencies]\nzlib = {{ version = \"\", system = true }}\n",
            ))

            .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("metadata")
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assertion.get_output().stdout).to_string();
    let view: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let pkg = package_build_flags(&view);
    let includes: Vec<String> = pkg["include_dirs"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_owned())
        .collect();
    assert!(
        includes.iter().any(|p| p == "/opt/zlib/include"),
        "matching conditional system dep must contribute flags: {includes:?}",
    );
}

#[test]
fn verbose_mode_prints_probe_progress() {
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "",
                "libs": "-lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("-v")
        .arg("metadata")
        .assert()
        .success();
    let stderr = String::from_utf8_lossy(&assertion.get_output().stderr).to_string();
    assert!(
        stderr.contains("probing"),
        "verbose stderr should mention probing: {stderr}",
    );
    assert!(
        stderr.contains("zlib"),
        "verbose stderr should mention the dep name: {stderr}",
    );
    assert!(
        stderr.contains("1.2.13"),
        "verbose stderr should mention the resolved version: {stderr}",
    );
}

#[test]
fn metadata_stdout_stays_clean_under_verbose_with_system_deps() {
    let fixtures = Fixtures::new();
    fixtures.write(
        "zlib",
        r#"{
                "version": "1.2.13",
                "cflags": "",
                "libs": "-lz"
            }"#,
    );
    let dir = TempDir::new().unwrap();
    assert_fs::fixture::ChildPath::new(dir.path().join("cabin.toml"))
        .write_str(&manifest_with_system_dep("", ""))
        .unwrap();
    write_hello_main(dir.path());

    let assertion = cabin_with_fake_pkg_config(&fixtures)
        .current_dir(dir.path())
        .arg("-v")
        .arg("metadata")
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assertion.get_output().stdout).to_string();
    // Stdout must still be parseable JSON — probe chatter
    // belongs on stderr only.
    let _view: serde_json::Value =
        serde_json::from_str(&stdout).expect("metadata stdout must remain valid JSON under -v");
}