cargo-ark 0.2.0

Cargo release utilities
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::cell::RefCell;

use toml_edit::Item;

use super::*;

fn unlaunched(_: &mut Command) -> io::Result<ExitStatus> {
    unreachable!("this test fails or finishes before launching Cargo")
}

const SIMULATED_FAILURE: &str = "SIMULATED_CARGO_FAILURE";

thread_local! {
    static SIMULATED_TEST_RUNS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

/// Stands in for Cargo: `package` writes one archive per selected package, and `test` checks the
/// extracted manifest and its crates-io patch, then records `<stem> <feature mode>`.
///
/// The `SIMULATED_CARGO_FAILURE` child variable names the operation that exits unsuccessfully:
/// `package`, a test's feature flag, or `default` for the test without one.
#[cfg(any(unix, windows))]
fn simulated_cargo(command: &mut Command) -> io::Result<ExitStatus> {
    let args: Vec<&str> = command
        .get_args()
        .map(|arg| arg.to_str().expect("the simulated commands use only UTF-8 scratch paths"))
        .collect();
    let failure = command
        .get_envs()
        .find(|(key, _)| *key == SIMULATED_FAILURE)
        .and_then(|(_, value)| value?.to_str());
    let operation = if args[0] == "package" {
        let archives = Path::new(args[3]).join("package");
        fs::create_dir_all(&archives)?;
        for selected in args[4..].iter().filter(|arg| **arg != "--package") {
            let stem = selected.replace('@', "-");
            write_crate_archive(&archives.join(format!("{stem}.crate")), &stem)?;
        }
        String::from("package")
    } else {
        let manifest = Path::new(args[args.len() - 1]);
        assert_eq!(manifest.file_name(), Some(OsStr::new("Cargo.toml")), "{args:?}");
        assert!(manifest.is_file(), "{args:?}");
        let source = manifest.parent().expect("the manifest was checked to be a file in a directory");
        let patch: DocumentMut = fs::read_to_string(args[1])?.parse().expect("the check writes its patch as TOML");
        let patched = patch
            .get("patch")
            .and_then(|patch| patch.get("crates-io"))
            .and_then(Item::as_table_like)
            .is_some_and(|crates| {
                crates
                    .iter()
                    .any(|(_, entry)| entry.get("path").and_then(Item::as_str) == source.to_str())
            });
        assert!(patched, "{patch}");
        let mode = if args[3] == "--manifest-path" { "default" } else { args[3] };
        let stem = source.file_name().and_then(OsStr::to_str).expect("archive stems are UTF-8");
        SIMULATED_TEST_RUNS.with_borrow_mut(|runs| runs.push(format!("{stem} {mode}")));
        mode.to_owned()
    };
    Ok(exit_status(failure == Some(operation.as_str())))
}

#[cfg(any(unix, windows))]
fn write_crate_archive(path: &Path, stem: &str) -> io::Result<()> {
    const MANIFEST: &[u8] = b"[package]\n";
    let mut header = tar::Header::new_gnu();
    header.set_size(MANIFEST.len().try_into().expect("a ten-byte manifest fits in u64"));
    header.set_mode(0o644);
    let mut archive = tar::Builder::new(flate2::write::GzEncoder::new(File::create(path)?, flate2::Compression::fast()));
    archive.append_data(&mut header, format!("{stem}/Cargo.toml"), MANIFEST)?;
    archive.into_inner()?.finish()?;
    Ok(())
}

#[cfg(unix)]
fn exit_status(failed: bool) -> ExitStatus {
    use std::os::unix::process::ExitStatusExt;
    ExitStatus::from_raw(i32::from(failed) << 8)
}

#[cfg(windows)]
fn exit_status(failed: bool) -> ExitStatus {
    use std::os::windows::process::ExitStatusExt;
    ExitStatus::from_raw(u32::from(failed))
}

#[cfg(any(unix, windows))]
fn simulated_check(failure: Option<&str>) -> Result<()> {
    let report = r#"[{"name":"peer","new_version":"1.2.0"},{"name":"consumer","new_version":"0.3.0"}]"#;
    let cargo = CargoInvoker {
        root: PathBuf::from("workspace"),
        child_env: failure
            .map(|failure| (SIMULATED_FAILURE.into(), failure.into()))
            .into_iter()
            .collect(),
        scratch: tempfile::tempdir()?,
        run_status: simulated_cargo,
    };
    check(Candidates::from_report(report)?, cargo)
}

#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn check_tests_every_packaged_candidate_in_each_feature_mode() -> Result<()> {
    simulated_check(None)?;
    assert_eq!(
        SIMULATED_TEST_RUNS.take(),
        [
            "consumer-0.3.0 --all-features",
            "consumer-0.3.0 --no-default-features",
            "consumer-0.3.0 default",
            "peer-1.2.0 --all-features",
            "peer-1.2.0 --no-default-features",
            "peer-1.2.0 default",
        ]
    );
    Ok(())
}

#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn check_stops_when_packaging_fails() {
    let error = simulated_check(Some("package")).unwrap_err().to_string();
    assert!(error.starts_with("cargo package for release candidates failed ("), "{error}");
    assert_eq!(SIMULATED_TEST_RUNS.take(), Vec::<String>::new());
}

#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn check_names_the_candidate_and_feature_mode_of_a_failing_test() {
    let error = simulated_check(Some("default")).unwrap_err().to_string();
    assert!(
        error.starts_with("consumer: cargo test (default features) from package archive failed ("),
        "{error}"
    );
    assert_eq!(
        SIMULATED_TEST_RUNS.take(),
        [
            "consumer-0.3.0 --all-features",
            "consumer-0.3.0 --no-default-features",
            "consumer-0.3.0 default"
        ]
    );
}

#[test]
fn preserves_the_selected_cargo_home_for_shipped_tests() -> Result<()> {
    #[cfg(windows)]
    let workspace = Path::new(r"\\?\C:\workspace");
    #[cfg(not(windows))]
    let workspace = Path::new("/workspace");
    let key = OsStr::new("CARGO_HOME");
    for (override_home, inherited, expected) in [
        (None, None, None),
        (None, Some("cache"), Some(workspace.join("cache").into_os_string())),
        (Some("override"), Some("cache"), Some(workspace.join("override").into_os_string())),
        (Some(""), Some("cache"), Some(OsString::new())),
    ] {
        let mut child_env = override_home.into_iter().map(|home| (key.to_owned(), home.into())).collect();
        resolve_cargo_home(workspace, &mut child_env, inherited.map(Into::into))?;
        assert_eq!(child_env.get(key), expected.as_ref());
    }
    Ok(())
}

#[cfg(windows)]
#[test]
fn preserves_an_absolute_cargo_home_without_normalizing_it() -> Result<()> {
    let root = Path::new(r"\\?\C:\workspace");
    let home = OsString::from(r"C:\cache\..\shared");
    let mut child_env = BTreeMap::new();
    resolve_cargo_home(root, &mut child_env, Some(home.clone()))?;
    assert_eq!(child_env.get(OsStr::new(CARGO_HOME)), Some(&home));
    Ok(())
}

#[cfg(windows)]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_a_cargo_home_that_windows_cannot_resolve() -> Result<()> {
    let parent = tempfile::tempdir()?;
    let workspace = tempfile::tempdir_in(parent.path())?;
    let child_env = BTreeMap::from([(CARGO_HOME.into(), "C:cache\0".into())]);
    let error = CargoInvoker::new(workspace.path(), child_env, Some(parent.path())).unwrap_err();
    assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::InvalidInput);
    Ok(())
}

#[test]
fn reads_candidate_versions_and_ignores_discovery_metadata() -> Result<()> {
    let report = r#"[{"name":"peer","new_version":"1.2.0","old_version":"1.1.0","classification":"compatible"}]"#;
    assert_eq!(
        Candidates::from_report(report)?.packages,
        BTreeMap::from([("peer".into(), "1.2.0".into())])
    );
    assert!(Candidates::from_report("[]")?.is_empty());
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn an_empty_report_needs_no_workspace_and_releases_scratch() -> Result<()> {
    let scratch = tempfile::tempdir()?;
    let path = scratch.path().to_path_buf();
    let cargo = CargoInvoker {
        root: path.join("missing-workspace"),
        child_env: BTreeMap::new(),
        scratch,
        run_status: unlaunched,
    };
    check(Candidates::from_report("[]")?, cargo)?;
    assert!(!path.try_exists()?);
    Ok(())
}

#[test]
fn deduplicates_candidates_with_the_same_name_and_version() -> Result<()> {
    let report = r#"[
        {"name":"peer","new_version":"1.2.0"},
        {"name":"other","new_version":"1.2.0"},
        {"name":"peer","new_version":"1.2.0"}
    ]"#;
    assert_eq!(
        Candidates::from_report(report)?.packages,
        BTreeMap::from([("other".into(), "1.2.0".into()), ("peer".into(), "1.2.0".into())])
    );
    Ok(())
}

#[test]
fn rejects_invalid_candidate_reports() {
    for report in ["", "{}"] {
        assert!(Candidates::from_report(report).is_err(), "{report}");
    }
    for (report, diagnostic) in [
        (r#"[{"new_version":"1.2.0"}]"#, "candidate is missing its name"),
        (r#"[{"name":"peer","old_version":"1.1.0"}]"#, "candidate is missing its version"),
        (
            r#"[{"name":"peer","new_version":"1.1.0"},{"name":"peer","new_version":"1.2.0"}]"#,
            "report lists two versions for `peer`: `1.1.0` and `1.2.0`; keep one",
        ),
    ] {
        assert_eq!(Candidates::from_report(report).unwrap_err().to_string(), diagnostic);
    }
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn validate_packages_reports_the_missing_candidate_archive() -> Result<()> {
    let scratch = tempfile::tempdir()?;
    let archives = tempfile::tempdir_in(scratch.path())?;
    let candidates = BTreeMap::from([("peer".into(), "1.2.0".into())]);
    let cargo = CargoInvoker {
        root: PathBuf::from("workspace"),
        child_env: BTreeMap::new(),
        scratch,
        run_status: unlaunched,
    };
    let error =
        validate_packages(&cargo, archives.path(), candidates).expect_err("peer was reported as packaged, but its archive is missing");
    let missing = archives.path().join("peer-1.2.0.crate");
    assert!(
        error.to_string().starts_with(&format!("extracting {}:", missing.display())),
        "{error}"
    );
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_a_missing_workspace_when_preparing_scratch() -> Result<()> {
    let parent = tempfile::tempdir()?;
    let error = CargoInvoker::new(&parent.path().join("missing-workspace"), BTreeMap::new(), Some(parent.path())).unwrap_err();
    assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn rejects_scratch_at_or_inside_the_workspace() -> Result<()> {
    let workspace = tempfile::tempdir()?;
    let member = tempfile::tempdir_in(workspace.path())?;
    for parent in [workspace.path(), member.path()] {
        let error = CargoInvoker::new(workspace.path(), BTreeMap::new(), Some(parent)).unwrap_err();
        assert_eq!(error.to_string(), "select a temporary directory outside the source workspace");
    }
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_scratch_creation_failure_when_the_parent_is_a_file() -> Result<()> {
    let workspace = tempfile::tempdir()?;
    let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
    let error = CargoInvoker::new(workspace.path(), BTreeMap::new(), Some(&manifest)).unwrap_err();
    assert!(
        error
            .to_string()
            .starts_with(&format!("preparing release scratch directory in {}: ", manifest.display())),
        "{error}"
    );
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn rejects_a_missing_scratch_parent() -> Result<()> {
    let temp = tempfile::tempdir()?;
    let workspace = tempfile::tempdir_in(temp.path())?;
    let scratch_parent = temp.path().join("nonexistent");
    let error =
        CargoInvoker::new(workspace.path(), BTreeMap::new(), Some(&scratch_parent)).expect_err("the scratch parent must already exist");
    assert!(error.to_string().starts_with("preparing release scratch directory in"), "{error}");
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_when_the_candidate_patch_cannot_be_written() -> Result<()> {
    let temp = tempfile::tempdir()?;
    let scratch = tempfile::tempdir_in(temp.path())?;
    fs::remove_dir(scratch.path())?;
    let cargo = CargoInvoker {
        root: temp.path().to_path_buf(),
        child_env: BTreeMap::new(),
        scratch,
        run_status: unlaunched,
    };
    let error = test_archives(&cargo, &BTreeMap::new()).unwrap_err();
    assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
    Ok(())
}

#[cfg(any(unix, windows))]
#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn reports_paths_cargo_cannot_represent_in_patch_toml() {
    #[cfg(unix)]
    let directory = {
        use std::os::unix::ffi::OsStringExt;
        std::ffi::OsString::from_vec(vec![0xff])
    };
    #[cfg(windows)]
    let directory = {
        use std::os::windows::ffi::OsStringExt;
        std::ffi::OsString::from_wide(&[0xd800])
    };
    let sources = BTreeMap::from([("candidate".into(), directory.into())]);
    let temp = tempfile::tempdir();
    let cargo = CargoInvoker {
        root: PathBuf::from("workspace"),
        child_env: BTreeMap::new(),
        scratch: temp.unwrap(),
        run_status: unlaunched,
    };
    assert_eq!(
        test_archives(&cargo, &sources).unwrap_err().to_string(),
        "candidate archive path must be UTF-8"
    );
}

#[test]
fn reports_when_the_required_cargo_process_cannot_start() {
    let mut command = Command::new("cargo");
    let error = run(&mut command, "testing a candidate", |_| Err(io::ErrorKind::NotFound.into())).unwrap_err();
    assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn commands_use_workspace_config_and_keep_builds_in_scratch() -> Result<()> {
    let root = tempfile::tempdir()?;
    let scratch = tempfile::tempdir()?;
    let patch = scratch.path().join("patch.toml");
    let manifest = scratch.path().join("Cargo.toml");
    let cargo = CargoInvoker {
        root: root.path().to_path_buf(),
        child_env: BTreeMap::from([
            ("RUSTUP_TOOLCHAIN".into(), "workspace-toolchain".into()),
            ("CARGO_BUILD_BUILD_DIR".into(), "caller-build".into()),
        ]),
        scratch,
        run_status: unlaunched,
    };
    let command = archive_test_command(&cargo, &patch, &manifest, Some("--no-default-features"));
    assert_eq!(command.get_program(), "cargo");
    assert_eq!(command.get_current_dir(), Some(root.path()));
    assert_eq!(
        command.get_args().collect::<Vec<_>>(),
        [
            "--config".as_ref(),
            patch.as_os_str(),
            "test".as_ref(),
            "--no-default-features".as_ref(),
            "--manifest-path".as_ref(),
            manifest.as_os_str(),
        ]
    );
    let env: BTreeMap<_, _> = command.get_envs().collect();
    assert_eq!(
        env.get(OsStr::new("RUSTUP_TOOLCHAIN")),
        Some(&Some(OsStr::new("workspace-toolchain")))
    );
    for key in ["CARGO_TARGET_DIR", "CARGO_BUILD_BUILD_DIR"] {
        let directory = env.get(OsStr::new(key)).copied().flatten().map(Path::new).unwrap();
        assert!(directory.starts_with(cargo.scratch.path()) && directory != cargo.scratch.path());
    }
    assert!(!env.contains_key(OsStr::new("CARGO_HOME")));
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn package_command_selects_only_the_candidates() -> Result<()> {
    let root = tempfile::tempdir()?;
    let scratch = tempfile::tempdir()?;
    let cargo = CargoInvoker::new(root.path(), BTreeMap::new(), Some(scratch.path()))?;
    assert_eq!(cargo.scratch.path().parent(), Some(scratch.path().canonicalize()?.as_path()));
    let candidates = BTreeMap::from([("consumer".to_owned(), "1.2.0".to_owned()), ("peer".to_owned(), "3.4.0".to_owned())]);
    let command = cargo.package_command(&candidates);
    let artifacts = cargo.scratch.path().join("artifacts");
    assert_eq!(
        command.get_args().collect::<Vec<_>>(),
        [
            "package".as_ref(),
            "--allow-dirty".as_ref(),
            "--target-dir".as_ref(),
            artifacts.as_os_str(),
            "--package".as_ref(),
            "consumer@1.2.0".as_ref(),
            "--package".as_ref(),
            "peer@3.4.0".as_ref(),
        ]
    );
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore = "uses the host filesystem")]
fn archive_commands_cover_all_three_feature_modes() -> Result<()> {
    let cargo = CargoInvoker {
        root: PathBuf::from("workspace"),
        child_env: BTreeMap::new(),
        scratch: tempfile::tempdir()?,
        run_status: unlaunched,
    };
    let patch = cargo.scratch.path().join("candidates.toml");
    let manifest = cargo.scratch.path().join("candidate/Cargo.toml");
    let args = ARCHIVE_FEATURE_MODES.map(|feature| {
        archive_test_command(&cargo, &patch, &manifest, feature)
            .get_args()
            .map(OsStr::to_os_string)
            .collect::<Vec<_>>()
    });
    assert!(args[0].iter().any(|arg| arg == "--all-features"));
    assert!(args[1].iter().any(|arg| arg == "--no-default-features"));
    assert!(args[2].iter().all(|arg| arg != "--all-features" && arg != "--no-default-features"));
    Ok(())
}