cargo-each 0.3.0

A cargo subcommand that runs a command over a cargo-style selection of workspace members
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Placeholder substitution for the command template.
//!
//! A fixed, small set of `{token}` replacements — deliberately not an
//! expression language:
//!
//! - Package tokens (valid in per-package and per-target modes): `{name}`,
//!   `{spec}`, `{version}`, `{manifest}`. Replaced textually inside each
//!   argument.
//! - The per-target token `{target}`.
//! - The once token (valid only in `--once` mode): `{packages}`. Must stand
//!   alone as a whole argument; it expands to the resolved selection flags,
//!   which is several tokens.
//! - The workspace token `{workspace-rust-version}`, valid in every mode.
//!
//! Using a token in the wrong mode is a usage error ([`PlaceholderMisuseError`]).
//!
//! Only the tokens above are interpreted. Any other `{…}` sequence — a typo
//! like `{manfiest}`, a wrong-case `{Name}`, or a literal brace an argument
//! genuinely needs — is passed through **verbatim** to the spawned command.
//! There is no brace-escape mechanism, so this passthrough is a deliberate part
//! of the contract (`cargo-each` never interprets the command beyond these
//! fixed substitutions), not an oversight.

use crate::error::{EachError, PlaceholderMisuseError, WorkspaceRustVersionError};
use crate::plan::Mode;

/// Per-package placeholder tokens.
const PER_PACKAGE_TOKENS: [&str; 4] = ["{name}", "{spec}", "{version}", "{manifest}"];
/// The per-target placeholder token.
const TARGET_TOKEN: &str = "{target}";
/// The once-mode placeholder token.
const PACKAGES_TOKEN: &str = "{packages}";
/// The workspace-wide Rust compatibility floor token.
const WORKSPACE_RUST_VERSION_TOKEN: &str = "{workspace-rust-version}";

/// The substitution context for one command invocation.
#[derive(Debug, Clone)]
pub(crate) enum Placeholders {
    /// Per-package mode: substitute the member's facts into each argument.
    Package {
        /// `{name}` — bare package name.
        name: String,
        /// `{spec}` — `name@version`.
        spec: String,
        /// `{version}` — package version.
        version: String,
        /// `{manifest}` — absolute path to the member's `Cargo.toml`.
        manifest: String,
        /// The root workspace Rust-version declaration, when requested.
        workspace_rust_version: Option<String>,
    },
    /// Per-target mode: package facts plus the selected target name.
    Target {
        name: String,
        spec: String,
        version: String,
        manifest: String,
        target: String,
        workspace_rust_version: Option<String>,
    },
    /// Once mode: `{packages}` expands to these pre-computed selection flags.
    Once {
        /// The cargo selection flags for the resolved set (e.g.
        /// `["--workspace"]` or `["--package", "a@1", "--package", "b@2"]`).
        packages: Vec<String>,
        /// The root workspace Rust-version declaration, when requested.
        workspace_rust_version: Option<String>,
    },
}

impl Placeholders {
    fn workspace_rust_version(&self) -> Option<&str> {
        match self {
            Self::Package {
                workspace_rust_version, ..
            }
            | Self::Target {
                workspace_rust_version, ..
            }
            | Self::Once {
                workspace_rust_version, ..
            } => workspace_rust_version.as_deref(),
        }
    }
}

fn replace_arg<'a>(arg: &str, placeholders: &'a Placeholders, mut replacements: Vec<(&'static str, &'a str)>) -> Result<String, EachError> {
    if arg.contains(WORKSPACE_RUST_VERSION_TOKEN) {
        let version = placeholders.workspace_rust_version().ok_or_else(|| {
            WorkspaceRustVersionError::new("the command uses the placeholder but its root value was not resolved".to_owned())
        })?;
        replacements.push((WORKSPACE_RUST_VERSION_TOKEN, version));
    }

    let mut rest = arg;
    let mut replaced = String::with_capacity(arg.len());
    while let Some((offset, token, value)) = replacements
        .iter()
        .filter_map(|&(token, value)| rest.find(token).map(|offset| (offset, token, value)))
        .min_by_key(|&(offset, _, _)| offset)
    {
        let (literal, token_and_rest) = rest.split_at(offset);
        let (_token, remaining) = token_and_rest.split_at(token.len());
        replaced.push_str(literal);
        replaced.push_str(value);
        rest = remaining;
    }
    replaced.push_str(rest);

    Ok(replaced)
}

/// Whether a command template uses the lazy workspace Rust-version token.
#[must_use]
pub(crate) fn uses_workspace_rust_version(args: &[String]) -> bool {
    args.iter().any(|arg| arg.contains(WORKSPACE_RUST_VERSION_TOKEN))
}

/// Validate that `args` only reference placeholders valid for the mode.
///
/// Checks mode-consistency without expanding the tokens — the check factored
/// out of [`substitute`] so the contract can be enforced even when the
/// selection resolves to no members (where `substitute` is never called) — a
/// misused placeholder is then a usage error rather than a silent no-op.
///
/// # Errors
///
/// Returns [`EachError`] if a per-package token appears under [`Mode::Once`],
/// if `{packages}` appears outside [`Mode::Once`], or if `{packages}` is
/// embedded in a larger argument rather than standing alone.
pub(crate) fn validate_placeholders(args: &[String], mode: Mode) -> Result<(), EachError> {
    for arg in args {
        if mode == Mode::Once {
            if let Some(token) = PER_PACKAGE_TOKENS.iter().find(|t| arg.contains(**t)) {
                return Err(
                    PlaceholderMisuseError::new((*token).to_owned(), "per-package token is not valid in --once mode".to_owned()).into(),
                );
            }
            if arg.contains(TARGET_TOKEN) {
                return Err(PlaceholderMisuseError::new(
                    TARGET_TOKEN.to_owned(),
                    "per-target token is not valid in --once mode".to_owned(),
                )
                .into());
            }
            if arg != PACKAGES_TOKEN && arg.contains(PACKAGES_TOKEN) {
                return Err(PlaceholderMisuseError::new(
                    PACKAGES_TOKEN.to_owned(),
                    "must stand alone as a whole argument (it expands to multiple tokens)".to_owned(),
                )
                .into());
            }
        } else {
            if arg.contains(PACKAGES_TOKEN) {
                return Err(PlaceholderMisuseError::new(PACKAGES_TOKEN.to_owned(), "only valid in --once mode".to_owned()).into());
            }
            if mode == Mode::PerPackage && arg.contains(TARGET_TOKEN) {
                return Err(PlaceholderMisuseError::new(TARGET_TOKEN.to_owned(), "only valid in per-target mode".to_owned()).into());
            }
        }
    }
    Ok(())
}

/// Substitute placeholders in `args` for one invocation.
///
/// Returns the fully-expanded argument vector.
///
/// # Errors
///
/// Returns [`EachError`] if a token is used in the wrong mode (a per-package
/// token under `--once`, or `{packages}` outside `--once`), or if `{packages}`
/// is embedded in a larger argument rather than standing alone.
pub(crate) fn substitute(args: &[String], placeholders: &Placeholders) -> Result<Vec<String>, EachError> {
    let mode = match placeholders {
        Placeholders::Package { .. } => Mode::PerPackage,
        Placeholders::Target { .. } => Mode::PerTarget,
        Placeholders::Once { .. } => Mode::Once,
    };
    validate_placeholders(args, mode)?;
    let mut out = Vec::with_capacity(args.len());
    for arg in args {
        match placeholders {
            Placeholders::Package {
                name,
                spec,
                version,
                manifest,
                ..
            } => {
                // The `{name}` / `{spec}` / … literals are cargo-each
                // placeholder tokens, not Rust format-string arguments.
                #[expect(
                    clippy::literal_string_with_formatting_args,
                    reason = "cargo-each placeholder tokens, not format args"
                )]
                let replaced = replace_arg(
                    arg,
                    placeholders,
                    vec![("{name}", name), ("{spec}", spec), ("{version}", version), ("{manifest}", manifest)],
                )?;
                out.push(replaced);
            }
            Placeholders::Target {
                name,
                spec,
                version,
                manifest,
                target,
                ..
            } => {
                #[expect(
                    clippy::literal_string_with_formatting_args,
                    reason = "cargo-each placeholder tokens, not format args"
                )]
                let replaced = replace_arg(
                    arg,
                    placeholders,
                    vec![
                        ("{name}", name),
                        ("{spec}", spec),
                        ("{version}", version),
                        ("{manifest}", manifest),
                        (TARGET_TOKEN, target),
                    ],
                )?;
                out.push(replaced);
            }
            Placeholders::Once { packages, .. } => {
                // Validation above guarantees each arg is either exactly
                // `{packages}` or contains no placeholder token at all.
                if arg == PACKAGES_TOKEN {
                    out.extend(packages.iter().cloned());
                } else {
                    out.push(replace_arg(arg, placeholders, Vec::new())?);
                }
            }
        }
    }

    Ok(out)
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    fn pkg() -> Placeholders {
        Placeholders::Package {
            name: "cargo-anvil".to_owned(),
            spec: "cargo-anvil@0.4.0".to_owned(),
            version: "0.4.0".to_owned(),
            manifest: "/ws/cargo-anvil/Cargo.toml".to_owned(),
            workspace_rust_version: None,
        }
    }

    fn args(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| (*s).to_owned()).collect()
    }

    #[test]
    fn per_package_tokens_expand() {
        let out = substitute(
            &args(&["{name}", "{spec}", "{version}", "{manifest}", "{name}:{version}:{name}"]),
            &pkg(),
        )
        .expect("substitute");
        assert_eq!(
            out,
            [
                "cargo-anvil",
                "cargo-anvil@0.4.0",
                "0.4.0",
                "/ws/cargo-anvil/Cargo.toml",
                "cargo-anvil:0.4.0:cargo-anvil",
            ]
        );
    }

    #[test]
    fn spec_and_name_distinct() {
        let out = substitute(&args(&["--package", "{name}", "note={spec}"]), &pkg()).expect("substitute");
        assert_eq!(out, ["--package", "cargo-anvil", "note=cargo-anvil@0.4.0"]);
    }

    #[test]
    fn packages_token_rejected_in_per_package_mode() {
        let err = substitute(&args(&["clippy", "{packages}"]), &pkg()).expect_err("misuse");
        assert_eq!(
            err.to_string(),
            "placeholder `{packages}` cannot be used here: only valid in --once mode"
        );
    }

    #[test]
    fn once_expands_packages_token() {
        let ph = Placeholders::Once {
            packages: args(&["--package", "a@1", "--package", "b@2"]),
            workspace_rust_version: None,
        };
        let out = substitute(&args(&["clippy", "{packages}", "--all-targets"]), &ph).expect("substitute");
        assert_eq!(out, ["clippy", "--package", "a@1", "--package", "b@2", "--all-targets"]);
    }

    #[test]
    fn once_rejects_per_package_token() {
        let ph = Placeholders::Once {
            packages: args(&["--workspace"]),
            workspace_rust_version: None,
        };
        let err = substitute(&args(&["test", "--package", "{name}"]), &ph).expect_err("misuse");
        assert_eq!(
            err.to_string(),
            "placeholder `{name}` cannot be used here: per-package token is not valid in --once mode"
        );
    }

    #[test]
    fn once_rejects_target_token() {
        let ph = Placeholders::Once {
            packages: args(&["--workspace"]),
            workspace_rust_version: None,
        };
        let err = substitute(&args(&["test", "--test", "{target}"]), &ph).expect_err("misuse");
        assert_eq!(
            err.to_string(),
            "placeholder `{target}` cannot be used here: per-target token is not valid in --once mode"
        );
    }

    #[test]
    fn once_rejects_embedded_packages_token() {
        let ph = Placeholders::Once {
            packages: args(&["--workspace"]),
            workspace_rust_version: None,
        };
        let err = substitute(&args(&["x={packages}"]), &ph).expect_err("misuse");
        assert_eq!(
            err.to_string(),
            "placeholder `{packages}` cannot be used here: must stand alone as a whole argument (it expands to multiple tokens)"
        );
    }

    #[test]
    fn target_mode_expands_package_and_target_tokens() {
        let ph = Placeholders::Target {
            name: "cargo-anvil".to_owned(),
            spec: "cargo-anvil@0.4.0".to_owned(),
            version: "0.4.0".to_owned(),
            manifest: "/ws/cargo-anvil/Cargo.toml".to_owned(),
            target: "loom".to_owned(),
            workspace_rust_version: None,
        };
        let out = substitute(
            &args(&["{name}", "{spec}", "{version}", "{manifest}", "{target}", "{target}:{name}"]),
            &ph,
        )
        .expect("substitute");
        assert_eq!(
            out,
            [
                "cargo-anvil",
                "cargo-anvil@0.4.0",
                "0.4.0",
                "/ws/cargo-anvil/Cargo.toml",
                "loom",
                "loom:cargo-anvil",
            ]
        );
    }

    #[test]
    fn target_token_is_rejected_in_per_package_mode() {
        let err = substitute(&args(&["echo", "{target}"]), &pkg()).expect_err("misuse");
        assert_eq!(
            err.to_string(),
            "placeholder `{target}` cannot be used here: only valid in per-target mode"
        );
    }

    #[test]
    fn unknown_and_brace_like_tokens_pass_through_verbatim() {
        let input = args(&["{manfiest}", "x={Name}", "{", "}"]);
        assert_eq!(substitute(&input, &pkg()).expect("substitute"), input);
    }

    #[test]
    fn workspace_rust_version_expands_in_every_mode() {
        let command = args(&["rustup", "toolchain", "install", "{workspace-rust-version}"]);
        let mut package = pkg();
        let Placeholders::Package {
            workspace_rust_version, ..
        } = &mut package
        else {
            unreachable!("pkg returns package placeholders");
        };
        *workspace_rust_version = Some("1.80".to_owned());
        assert_eq!(
            substitute(&command, &package).expect("package substitution"),
            ["rustup", "toolchain", "install", "1.80"]
        );

        let once = Placeholders::Once {
            packages: args(&["--workspace"]),
            workspace_rust_version: Some("1.80".to_owned()),
        };
        assert_eq!(
            substitute(&command, &once).expect("once substitution"),
            ["rustup", "toolchain", "install", "1.80"]
        );
    }

    #[test]
    fn unresolved_workspace_rust_version_is_reported_in_package_and_target_modes() {
        let command = args(&["echo", "{workspace-rust-version}"]);
        let package_error = substitute(&command, &pkg()).expect_err("package value is unresolved");
        assert!(package_error.to_string().contains("root value was not resolved"), "{package_error}");

        let target = Placeholders::Target {
            name: "crate".to_owned(),
            spec: "crate@1.0.0".to_owned(),
            version: "1.0.0".to_owned(),
            manifest: "/ws/crate/Cargo.toml".to_owned(),
            target: "example".to_owned(),
            workspace_rust_version: None,
        };
        let target_error = substitute(&command, &target).expect_err("target value is unresolved");
        assert!(target_error.to_string().contains("root value was not resolved"), "{target_error}");
    }

    #[test]
    fn package_values_are_not_rescanned_for_workspace_tokens() {
        let placeholders = Placeholders::Package {
            name: "crate".to_owned(),
            spec: "crate@1.0.0".to_owned(),
            version: "1.0.0".to_owned(),
            manifest: "/ws/{workspace-rust-version}/crate/Cargo.toml".to_owned(),
            workspace_rust_version: Some("1.80".to_owned()),
        };
        assert_eq!(
            substitute(&args(&["{workspace-rust-version}", "{manifest}"]), &placeholders).expect("substitute package placeholders"),
            ["1.80", "/ws/{workspace-rust-version}/crate/Cargo.toml"]
        );
    }

    #[test]
    fn target_values_are_not_rescanned_for_workspace_tokens() {
        let placeholders = Placeholders::Target {
            name: "crate".to_owned(),
            spec: "crate@1.0.0".to_owned(),
            version: "1.0.0".to_owned(),
            manifest: "/ws/{workspace-rust-version}/crate/Cargo.toml".to_owned(),
            target: "example".to_owned(),
            workspace_rust_version: Some("1.80".to_owned()),
        };
        assert_eq!(
            substitute(&args(&["{workspace-rust-version}", "{manifest}:{target}"]), &placeholders,)
                .expect("substitute target placeholders"),
            ["1.80", "/ws/{workspace-rust-version}/crate/Cargo.toml:example"]
        );
    }

    #[test]
    fn manifest_values_are_not_rescanned_for_target_tokens() {
        let placeholders = Placeholders::Target {
            name: "crate".to_owned(),
            spec: "crate@1.0.0".to_owned(),
            version: "1.0.0".to_owned(),
            manifest: "/ws/{target}/crate/Cargo.toml".to_owned(),
            target: "example".to_owned(),
            workspace_rust_version: None,
        };
        assert_eq!(
            substitute(&args(&["{manifest}:{target}"]), &placeholders).expect("substitute target placeholders"),
            ["/ws/{target}/crate/Cargo.toml:example"]
        );
    }

    #[test]
    fn detects_workspace_rust_version_usage() {
        assert!(uses_workspace_rust_version(&args(&["tool", "v={workspace-rust-version}"])));
        assert!(!uses_workspace_rust_version(&args(&["tool", "{name}"])));
    }
}