mbx 1.20.0

A build cache for Rust projects
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
//! Real Cargo is the oracle for alias expansion. A wrapper can fail metadata
//! without changing Cargo's configuration loading, listing, or execution.
#![cfg(unix)]

use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

struct Fixture {
    _temp: tempfile::TempDir,
    root: PathBuf,
    outside: PathBuf,
    cargo: PathBuf,
}

impl Fixture {
    fn new() -> Self {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().canonicalize().unwrap();
        let outside = root.join("outside");
        std::fs::create_dir_all(outside.join(".cargo")).unwrap();
        std::fs::create_dir_all(root.join("bin")).unwrap();
        let cargo = root.join("bin/cargo");
        executable(
            &cargo,
            r#"#!/bin/sh
for arg do
  if [ "$arg" = metadata ] && [ "$REJECT_METADATA" = 1 ]; then exit 1; fi
done
exec "$REAL_CARGO" "$@"
"#,
        );
        executable(
            &root.join("bin/cargo-probe"),
            r#"#!/bin/sh
printf '%s\n' "$@"
touch "$EXTERNAL_MARKER"
"#,
        );
        Self {
            _temp: temp,
            root,
            outside,
            cargo,
        }
    }

    fn config(&self, text: &str) {
        std::fs::write(self.outside.join(".cargo/config.toml"), text).unwrap();
    }

    fn project(&self, name: &str) -> PathBuf {
        let project = self.root.join(name);
        std::fs::create_dir_all(project.join("src")).unwrap();
        std::fs::write(
            project.join("Cargo.toml"),
            "[package]\nname='alias-fixture'\nversion='0.0.0'\nedition='2021'\n",
        )
        .unwrap();
        std::fs::write(project.join("src/main.rs"), "fn main() {}\n").unwrap();
        // Successful recovery must actually manage the build.
        std::fs::write(
            project.join("build.rs"),
            r#"fn main() {
    assert!(std::env::var_os("MBX_SOCKET").is_some(), "unmanaged build");
}
"#,
        )
        .unwrap();
        project
    }

    fn command(&self, shim: bool) -> Command {
        let mut command = Command::new(env!("CARGO_BIN_EXE_mbx"));
        let real = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
        let real = which::which(real).unwrap();
        let path = std::env::join_paths(
            std::iter::once(self.root.join("bin"))
                .chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())),
        )
        .unwrap();
        for (key, _) in std::env::vars_os() {
            let name = key.to_string_lossy();
            if name.starts_with("MBX_") || name.starts_with("CARGO_") || name.starts_with("RUSTC_")
            {
                command.env_remove(key);
            }
        }
        command
            .current_dir(&self.outside)
            .env("PATH", path)
            .env("REAL_CARGO", real)
            .env("CARGO", &self.cargo)
            .env("CARGO_HOME", self.root.join("cargo-home"))
            .env("MBX_CACHE_DIR", self.root.join("cache"))
            .env("MBX_TARGET_ROOT", self.root.join("targets"))
            .env("MBX_GC_AUTO", "0")
            .env("MBX_INCREMENTAL", "0")
            .env("MBX_LINKER", "system")
            .env("MBX_SUMMARY", "off")
            .env("EXTERNAL_MARKER", self.root.join("external-ran"));
        if shim {
            command.env("MBX_CARGO_SHIM_MODE", "1");
        }
        command
    }
}

fn executable(path: &Path, text: &str) {
    std::fs::write(path, text).unwrap();
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}

fn rejected(output: Output) {
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("could not verify Cargo build storage"),
        "{stderr}"
    );
    assert!(!stderr.contains("Compiling"), "{stderr}");
}

fn succeeded(output: Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "{stderr}");
    String::from_utf8(output.stdout).unwrap()
}

fn array(words: &[&str]) -> String {
    toml::Value::Array(
        words
            .iter()
            .map(|word| toml::Value::String((*word).into()))
            .collect(),
    )
    .to_string()
}

#[test]
fn path_aliases_preserve_boundaries_and_fail_closed() {
    let f = Fixture::new();
    for name in [
        "ordinary",
        "space suffix",
        "space -suffix",
        "space --help",
        "tab\tsuffix",
    ] {
        let project = f.project(name);
        let path = project.to_str().unwrap();
        for attached in [false, true] {
            let attached_path = format!("--path={path}");
            let words = if attached {
                vec!["install", &attached_path]
            } else {
                vec!["install", "--path", path]
            };
            f.config(&format!("[alias]\ni={}\nchain='i'\n", array(&words)));
            for shim in [false, true] {
                rejected(
                    f.command(shim)
                        .args(["chain", "--offline"])
                        .env("REJECT_METADATA", "1")
                        .output()
                        .unwrap(),
                );
            }
        }
        assert!(!project.join("target").exists());
    }
}

#[test]
fn real_path_installs_are_managed_even_with_spaces_and_dashes() {
    let f = Fixture::new();
    let project = f.project("package -suffix");
    f.config(&format!(
        "[alias]\ni={}\n",
        array(&["install", "--path", project.to_str().unwrap()])
    ));
    for shim in [false, true] {
        succeeded(
            f.command(shim)
                .args(["i", "--offline", "--root"])
                .arg(f.root.join(format!("installed-{shim}")))
                .output()
                .unwrap(),
        );
        assert!(
            f.root
                .join(format!("installed-{shim}/bin/alias-fixture"))
                .is_file()
        );
    }
}

#[test]
fn outside_commands_and_external_aliases_reach_real_cargo() {
    let f = Fixture::new();
    let template = f.project("template -suffix");
    f.config(&format!(
        "[alias]\nexternal={}\nchain='external'\n",
        array(&["probe", "--path", template.to_str().unwrap(), "ripgrep"])
    ));
    for shim in [false, true] {
        succeeded(
            f.command(shim)
                .args(["probe", "--manifest-path"])
                .arg(template.join("Cargo.toml"))
                .output()
                .unwrap(),
        );
        for command in ["probe", "chain"] {
            let stdout = succeeded(f.command(shim).arg(command).output().unwrap());
            assert!(stdout.starts_with("probe\n"));
            if command == "chain" {
                assert!(stdout.contains(template.to_str().unwrap()));
                assert!(stdout.ends_with("ripgrep\n"));
            }
        }
        let output = f.command(shim).arg("build").output().unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("could not find `Cargo.toml`"), "{stderr}");
        assert!(!stderr.contains("could not verify"), "{stderr}");
    }
}

#[test]
fn environment_and_hierarchical_aliases_keep_cargo_precedence() {
    let f = Fixture::new();
    let project = f.project("package -suffix");
    let install = array(&["install", "--path", project.to_str().unwrap()]);
    // The lower-priority array contributes its command, the local one its path.
    std::fs::create_dir_all(f.root.join(".cargo")).unwrap();
    std::fs::write(
        f.root.join(".cargo/config.toml"),
        "[alias]\ni=['install']\n",
    )
    .unwrap();
    f.config(&format!(
        "[alias]\ni={}\n",
        array(&["--path", project.to_str().unwrap()])
    ));
    for shim in [false, true] {
        rejected(
            f.command(shim)
                .arg("i")
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
        rejected(
            f.command(shim)
                .env("REJECT_METADATA", "1")
                .arg("i")
                .env("CARGO_ALIAS_I", "probe")
                .output()
                .unwrap(),
        );
        rejected(
            f.command(shim)
                .args(["env-install", "--path"])
                .arg(&project)
                .env("CARGO_ALIAS_ENV_INSTALL", "install")
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
    }
    // Legacy config wins over config.toml, including for built-in shorthand.
    std::fs::write(
        f.outside.join(".cargo/config"),
        format!("[alias]\nb={install}\n"),
    )
    .unwrap();
    for shim in [false, true] {
        rejected(
            f.command(shim)
                .arg("b")
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
    }
}

#[test]
fn unsupported_configuration_and_recursive_aliases_are_not_guessed() {
    let f = Fixture::new();
    for config in [
        "[alias]\nx='y'\ny='x'\n",
        "[alias]\nx=['-Zscript','example.rs']\n",
        "[alias]\nx=['build','-C','somewhere']\n",
        "[alias]\nx=['--config','alias.y=\"probe\"','y']\n",
    ] {
        f.config(config);
        for shim in [false, true] {
            rejected(
                f.command(shim)
                    .arg("x")
                    .env("REJECT_METADATA", "1")
                    .output()
                    .unwrap(),
            );
        }
    }
    f.config("[alias]\nx='probe'\n");
    rejected(
        f.command(true)
            .args(["--config", "term.quiet=true", "x"])
            .env("REJECT_METADATA", "1")
            .output()
            .unwrap(),
    );
    assert!(!f.root.join("external-ran").exists());
}

/// An `include` is configuration this cannot read, but only aliases can come
/// out of one, and Cargo's own listing reports the aliases it honours. So a
/// command Cargo knows as an alias is refused rather than guessed, while a
/// command that is no alias at all is untouched: an include cannot turn
/// `cargo probe` into something else, and refusing it would put back the very
/// failure outside a project that this change exists to remove.
#[test]
fn configuration_includes_refuse_aliases_without_refusing_everything() {
    let f = Fixture::new();
    let include = |text: &str| {
        std::fs::write(f.outside.join(".cargo/extra.toml"), text).unwrap();
        f.config("include=['extra.toml']\n");
    };
    for shim in [false, true] {
        // Cargo honours the alias and says so in its listing, so it is refused
        // rather than read from configuration this cannot follow.
        include("[alias]\nx='probe'\n");
        rejected(
            f.command(shim)
                .arg("x")
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
        assert!(!f.root.join("external-ran").exists());
        // The same configuration must not cost an ordinary external command
        // its passthrough.
        let stdout = succeeded(
            f.command(shim)
                .arg("probe")
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
        assert!(stdout.starts_with("probe\n"), "{stdout}");
        std::fs::remove_file(f.root.join("external-ran")).unwrap();
    }
    // An include Cargo cannot load leaves it honouring no alias at all, and
    // its own diagnostic is the one worth showing. Nothing is built either way.
    f.config("include=['missing.toml']\n[alias]\nx='probe'\n");
    for shim in [false, true] {
        let output = f
            .command(shim)
            .arg("x")
            .env("REJECT_METADATA", "1")
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(!stderr.contains("could not verify"), "{stderr}");
        assert!(!stderr.contains("Compiling"), "{stderr}");
        assert!(!f.root.join("external-ran").exists(), "{stderr}");
    }
}

#[test]
fn manifest_aliases_global_flags_and_builtin_shadowing_are_checked() {
    let f = Fixture::new();
    let project = f.project("manifest --help");
    let manifest = project.join("Cargo.toml");
    for expansion in [
        array(&["build", "--manifest-path", manifest.to_str().unwrap()]),
        array(&[
            "--offline",
            "build",
            "--manifest-path",
            manifest.to_str().unwrap(),
        ]),
        array(&["build", &format!("--manifest-path={}", manifest.display())]),
    ] {
        f.config(&format!("[alias]\nx={expansion}\nbuild='probe'\n"));
        for shim in [false, true] {
            rejected(
                f.command(shim)
                    .arg("x")
                    .env("REJECT_METADATA", "1")
                    .output()
                    .unwrap(),
            );
        }
    }
    assert!(!f.root.join("external-ran").exists());
    assert!(!project.join("target").exists());
}

#[test]
fn cargo_home_and_environment_string_aliases_are_resolved() {
    let f = Fixture::new();
    std::fs::create_dir_all(f.root.join("cargo-home")).unwrap();
    std::fs::write(
        f.root.join("cargo-home/config.toml"),
        "[alias]\nx='build'\n",
    )
    .unwrap();
    for shim in [false, true] {
        // An environment string replaces a file string (but appends to an
        // array, covered separately). Whitespace splitting matches Cargo.
        succeeded(
            f.command(shim)
                .arg("x")
                .env("CARGO_ALIAS_X", "probe\t--example")
                .output()
                .unwrap(),
        );
    }
    let project = f.project("project");
    std::fs::write(
        f.root.join("cargo-home/config.toml"),
        format!(
            "[alias]\nx={}\n",
            array(&["install", "--path", project.to_str().unwrap()])
        ),
    )
    .unwrap();
    for shim in [false, true] {
        rejected(
            f.command(shim)
                .arg("x")
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
    }
}

#[test]
fn external_flags_cannot_hide_a_project_after_failed_metadata() {
    let f = Fixture::new();
    let project = f.project("project");
    for shim in [false, true] {
        rejected(
            f.command(shim)
                .current_dir(&project)
                .args(["probe", "--manifest-path", "missing/Cargo.toml"])
                .env("REJECT_METADATA", "1")
                .output()
                .unwrap(),
        );
    }
    assert!(!f.root.join("external-ran").exists());
}