From f1232f21a2b2392ceeb5f7b167109ddc39604eb7 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 21:21:34 +0100 Subject: [PATCH] feat: cargo-locked makes every Cargo command in recipes, workflows and t3.json pass --locked --- crates/sourceorigin-standard/README.md | 1 + .../src/rules/cargo_locked.rs | 170 ++++++++++++++++++ crates/sourceorigin-standard/src/rules/fix.rs | 66 +++++-- crates/sourceorigin-standard/src/rules/mod.rs | 16 +- .../src/rules/tests/cargo_locked.rs | 74 ++++++++ .../src/rules/tests/mod.rs | 1 + .../src/rules/text_file.rs | 36 ++++ 7 files changed, 349 insertions(+), 15 deletions(-) create mode 100644 crates/sourceorigin-standard/src/rules/cargo_locked.rs create mode 100644 crates/sourceorigin-standard/src/rules/tests/cargo_locked.rs create mode 100644 crates/sourceorigin-standard/src/rules/text_file.rs diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index a94e765..c8053f2 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -39,6 +39,7 @@ A repository adopts the standard in four steps: - `config-comments`: In every `Cargo.toml`, justfile (and `*.just`) and `.github` YAML file, each block of `#` comment lines spans at most `standard.toml`'s `[comments] block-lines` (6 by default), and the file holds at most `[comments] file-lines` comment lines (40 by default). - `workspace-manifest`: The root manifest's `[workspace]` sets `resolver = "3"`, its `[workspace.package]` sets `edition = "2024"`, and every workspace crate inherits it with `edition.workspace = true`. - `layout`: Every workspace crate lives under `crates/`, `apps/` or `tools/`, the `xtask` crate in `tools/xtask`, and `.cargo/config.toml` aliases `cargo xtask` to `run --locked --package xtask --`. +- `cargo-locked`: Every `cargo build`, `check`, `clippy`, `doc`, `llvm-cov`, `nextest`, `publish`, `run` and `test` in a justfile (and `*.just`), `.github` YAML file or `t3.json` passes `--locked` (or `--frozen`). Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and diff --git a/crates/sourceorigin-standard/src/rules/cargo_locked.rs b/crates/sourceorigin-standard/src/rules/cargo_locked.rs new file mode 100644 index 0000000..a9ae0fc --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/cargo_locked.rs @@ -0,0 +1,170 @@ +//! `cargo-locked`: recipes, workflows and `t3.json` never let Cargo update +//! `Cargo.lock`. + +use std::collections::BTreeMap; + +use super::fix::{Checked, Fix}; +use super::text_file::TextFile; +use super::{Finding, Repository}; + +/// The files whose commands the rule reads, as git pathspecs. +pub(super) const FILES: [&str; 5] = [ + ":(glob)**/justfile", + ":(glob)**/*.just", + ":(glob).github/**/*.yml", + ":(glob).github/**/*.yaml", + "t3.json", +]; + +/// The Cargo subcommands that resolve dependencies, so take `--locked`. +/// `cargo xtask` takes it through its alias, which `layout` checks. +const SUBCOMMANDS: [&str; 9] = [ + "build", "check", "clippy", "doc", "llvm-cov", "nextest", "publish", "run", "test", +]; + +/// The flags that keep `Cargo.lock` as it is. +const LOCKED: [&str; 2] = ["--locked", "--frozen"]; + +/// A Cargo command without `--locked`: the line its subcommand is on, and +/// where `--locked` goes in it. +struct Unlocked<'a> { + subcommand: &'a str, + /// The line, from 1. + line: usize, + /// The byte of that line after which `--locked` goes. + insert_at: usize, +} + +impl TextFile { + /// Each Cargo command of the file that resolves dependencies without + /// `--locked`. A command runs from `cargo` to the next `&&`, `||`, `;` + /// or `|`, across lines ending in `\`; `#` lines are comments. + fn unlocked(&self) -> Vec> { + let mut tokens: Vec<(usize, usize, &str)> = Vec::new(); + let mut found = Vec::new(); + for (index, line) in self.text.lines().enumerate() { + if line.trim_start().starts_with('#') { + continue; + } + let continued = line.trim_end().ends_with('\\'); + for (start, token) in Self::tokens(line) { + tokens.push((index + 1, start + token.len(), token)); + } + if !continued { + found.extend(Self::commands(&tokens)); + tokens.clear(); + } + } + found.extend(Self::commands(&tokens)); + found + } + + /// The words of `line`, each with the byte it starts at, trimmed of + /// quotes and of just's `@` and `-`. A `;`, `|` or `&` ends a word and + /// is a `;` word of its own. + fn tokens(line: &str) -> Vec<(usize, &str)> { + let mut words = Vec::new(); + let mut start = None; + for (at, c) in line.char_indices().chain([(line.len(), ' ')]) { + let separator = matches!(c, ';' | '|' | '&'); + if c.is_whitespace() || separator { + if let Some(from) = start.take() { + words.push((from, &line[from..at])); + } + if separator { + words.push((at, ";")); + } + } else if start.is_none() { + start = Some(at); + } + } + words + .into_iter() + .map(|(at, word)| { + let quoted = word.trim_start_matches(['"', '\'', '(']); + let trimmed = quoted + .strip_prefix(['@', '-']) + .filter(|rest| !rest.starts_with('-')) + .unwrap_or(quoted); + let at = at + word.len() - trimmed.len(); + (at, trimmed.trim_end_matches(['"', '\'', ')', ','])) + }) + .filter(|(_, word)| !word.is_empty()) + .collect() + } + + /// The commands of `tokens` that run a subcommand without `--locked`. + fn commands<'a>(tokens: &[(usize, usize, &'a str)]) -> Vec> { + tokens + .split(|&(_, _, token)| token == ";") + .filter_map(|command| { + let cargo = command + .iter() + .position(|&(_, _, token)| token == "cargo" || token.ends_with("/cargo"))?; + let mut rest = command[cargo + 1..] + .iter() + .skip_while(|(_, _, token)| token.starts_with('+')); + let &(line, end, subcommand) = rest.next()?; + if !SUBCOMMANDS.contains(&subcommand) + || command.iter().any(|(_, _, token)| LOCKED.contains(token)) + { + return None; + } + let (line, insert_at) = match rest.next() { + Some(&(run_line, run_end, "run")) if subcommand == "nextest" => { + (run_line, run_end) + } + _ => (line, end), + }; + Some(Unlocked { + subcommand, + line, + insert_at, + }) + }) + .collect() + } +} + +impl Repository { + /// Each Cargo command in a justfile, workflow or `t3.json` that + /// resolves dependencies without `--locked`, fixed by adding it after + /// the subcommand. + pub(super) fn cargo_locked(&self) -> Checked { + let mut checked = Checked::default(); + for file in &self.scripts { + let mut by_line: BTreeMap>> = BTreeMap::new(); + for unlocked in file.unlocked() { + checked.findings.push(Finding { + path: file.path.clone(), + line: unlocked.line, + message: format!( + "`cargo {}` without `--locked`: add it, so the command never updates \ + Cargo.lock", + unlocked.subcommand + ), + }); + by_line.entry(unlocked.line).or_default().push(unlocked); + } + for (line, mut unlocked) in by_line { + let mut text = file + .text + .lines() + .nth(line - 1) + .unwrap_or_default() + .to_owned(); + unlocked.sort_by_key(|unlocked| std::cmp::Reverse(unlocked.insert_at)); + for unlocked in &unlocked { + text.insert_str(unlocked.insert_at.min(text.len()), " --locked"); + } + checked.fixes.push(Fix::line( + file.path.clone(), + format!("add `--locked` to line {line}'s Cargo commands"), + line, + text, + )); + } + } + checked + } +} diff --git a/crates/sourceorigin-standard/src/rules/fix.rs b/crates/sourceorigin-standard/src/rules/fix.rs index d442674..3a45948 100644 --- a/crates/sourceorigin-standard/src/rules/fix.rs +++ b/crates/sourceorigin-standard/src/rules/fix.rs @@ -1,5 +1,6 @@ //! `--fix`: the edits that resolve a rule's mechanical violations, each made -//! to a TOML document so the file keeps its layout and comments. +//! to a TOML document so the file keeps its layout and comments, or to the +//! lines of a file that isn't TOML, such as a justfile. use std::collections::{BTreeMap, BTreeSet}; use std::fmt; @@ -10,14 +11,23 @@ use toml_edit::{DocumentMut, Item, Value}; use super::{Error, Finding, Rule}; use crate::config::{self, Deviation, Stale}; -/// A mechanical edit to one TOML file, which `cargo xtask standard --fix` +/// A mechanical edit to one file, which `cargo xtask standard --fix` /// makes. pub struct Fix { /// The file, from the repository's root. pub path: PathBuf, /// What it changes, such as "add `[lints] workspace = true`". pub what: String, - edit: Box, + edit: Edit, +} + +/// How a fix changes its file. +enum Edit { + /// An edit to a TOML file's document. + Toml(Box), + /// The replacement of a line, from 1, of a file that isn't TOML, with + /// text that may span lines. + Line(usize, String), } impl Fix { @@ -30,7 +40,17 @@ impl Fix { Self { path: path.into(), what, - edit: Box::new(edit), + edit: Edit::Toml(Box::new(edit)), + } + } + + /// A fix replacing `line`, from 1, of `path`, a file that isn't TOML, + /// with `text`, which may span lines. A line past the end is added. + pub(super) fn line(path: impl Into, what: String, line: usize, text: String) -> Self { + Self { + path: path.into(), + what, + edit: Edit::Line(line, text), } } @@ -83,16 +103,36 @@ impl Fix { source, })?; } - let mut document: DocumentMut = - text.parse() - .map_err(|error: toml_edit::TomlError| Error::Toml { - path: path.to_owned(), - message: error.to_string(), - })?; - for fix in fixes { - (fix.edit)(&mut document); + let mut written = text.clone(); + if fixes.iter().any(|fix| matches!(fix.edit, Edit::Toml(_))) { + let mut document: DocumentMut = + text.parse() + .map_err(|error: toml_edit::TomlError| Error::Toml { + path: path.to_owned(), + message: error.to_string(), + })?; + for fix in &fixes { + if let Edit::Toml(edit) = &fix.edit { + edit(&mut document); + } + } + written = document.to_string(); + } + let mut lines: Vec = written.lines().map(str::to_owned).collect(); + let mut replaced = false; + for fix in &fixes { + if let Edit::Line(line, new) = &fix.edit { + let index = line.saturating_sub(1); + match lines.get_mut(index) { + Some(old) => new.clone_into(old), + None => lines.push(new.clone()), + } + replaced = true; + } + } + if replaced { + written = lines.into_iter().map(|line| line + "\n").collect(); } - let mut written = document.to_string(); if text.contains("\r\n") { written = written.replace("\r\n", "\n").replace('\n', "\r\n"); } diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index b02eccd..3670991 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -5,6 +5,7 @@ //! their docs. mod budget; +mod cargo_locked; mod comments; mod config_comments; mod fix; @@ -17,6 +18,7 @@ mod report; mod source; #[cfg(test)] mod tests; +mod text_file; mod toml_file; mod unsafe_modules; mod workspace_lints; @@ -37,6 +39,7 @@ use manifest::{Manifest, RootManifest}; use modules::Modules; pub use report::{Report, RuleReport}; use source::{Source, Unparsed}; +use text_file::TextFile; use toml_file::TomlFile; use workspace_lints::LintLevel; @@ -129,6 +132,10 @@ rules! { /// `xtask` crate in `tools/xtask`, and `.cargo/config.toml` aliases /// `cargo xtask` to `run --locked --package xtask --`. Layout = "layout" => layout, + /// Every `cargo build`, `check`, `clippy`, `doc`, `llvm-cov`, + /// `nextest`, `publish`, `run` and `test` in a justfile (and `*.just`), + /// `.github` YAML file or `t3.json` passes `--locked` (or `--frozen`). + CargoLocked = "cargo-locked" => cargo_locked, } /// Why the rules couldn't be checked. @@ -287,6 +294,9 @@ struct Repository { modules: Modules, /// Each crate's ceilings of exceptions. budget: Budget, + /// The justfiles, workflows and `t3.json`, whose commands the rules + /// read. + scripts: Vec, /// The manifests, justfiles and workflows, with their comments. commented: Vec, } @@ -307,6 +317,7 @@ impl Repository { modules: Modules::of(&metadata, &sources), budget: Budget::load(root)?, commented: Commented::load_all(root)?, + scripts: TextFile::load_all(root, &cargo_locked::FILES)?, metadata, sources, unparsed, @@ -391,8 +402,9 @@ pub fn check(root: &Path) -> Result, Error> { /// Makes every mechanical fix the rules know in the repository at `root`, /// such as adding `[lints] workspace = true` or lowering a ceiling of /// `budget.toml` to what the crate holds, and returns them. Each is an edit -/// to a TOML document, which keeps the file's layout and comments. What -/// needs judgement stays a violation for [`check`] to report. +/// to a TOML document, which keeps the file's layout and comments, or to a +/// line of another file, such as a justfile. What needs judgement stays a +/// violation for [`check`] to report. /// /// # Errors /// diff --git a/crates/sourceorigin-standard/src/rules/tests/cargo_locked.rs b/crates/sourceorigin-standard/src/rules/tests/cargo_locked.rs new file mode 100644 index 0000000..96057fc --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/cargo_locked.rs @@ -0,0 +1,74 @@ +use super::{Fixture, INHERITS}; +use crate::rules::Rule; + +/// A justfile with locked, unlocked and other Cargo commands. +const JUSTFILE: &str = "\ +build: + @cargo build --workspace && cargo test +# cargo test in a comment +test *ARGS: + cargo nextest run --locked \"$@\" + cargo fmt --all && cargo +nightly doc --no-deps +lint: + cargo clippy \\ + --locked -- -D warnings + cargo xtask standard; cargo nextest run --workspace +"; + +#[test] +fn cargo_commands_that_resolve_dependencies_pass_locked() { + let fixture = Fixture::new(); + fixture + .add_crate("core", INHERITS) + .write("justfile", JUSTFILE) + .write( + ".github/workflows/ci.yml", + "jobs:\n rust:\n steps:\n - run: |\n cargo test --frozen\n \ + cargo run --package tool\n", + ) + .write("t3.json", "{ \"command\": \"cargo check --workspace\" }\n") + .write("scripts/build.sh", "cargo build\n"); + let unlocked = |path: &str, line: usize, subcommand: &str| { + format!( + "{path}:{line}: `cargo {subcommand}` without `--locked`: add it, so the command \ + never updates Cargo.lock (cargo-locked)" + ) + }; + assert_eq!( + fixture.violations(Rule::CargoLocked), + [ + unlocked(".github/workflows/ci.yml", 6, "run"), + unlocked("justfile", 2, "build"), + unlocked("justfile", 2, "test"), + unlocked("justfile", 6, "doc"), + unlocked("justfile", 10, "nextest"), + unlocked("t3.json", 1, "check"), + ] + ); +} + +#[test] +fn fix_adds_locked_after_the_subcommand() { + let fixture = Fixture::new(); + fixture + .add_crate("core", INHERITS) + .write("justfile", JUSTFILE) + .fix_rule(Rule::CargoLocked); + let justfile = + std::fs::read_to_string(fixture.0.root().join("justfile")).expect("the justfile is read"); + assert_eq!( + justfile.lines().collect::>(), + [ + "build:", + " @cargo build --locked --workspace && cargo test --locked", + "# cargo test in a comment", + "test *ARGS:", + " cargo nextest run --locked \"$@\"", + " cargo fmt --all && cargo +nightly doc --locked --no-deps", + "lint:", + " cargo clippy \\", + " --locked -- -D warnings", + " cargo xtask standard; cargo nextest run --locked --workspace", + ] + ); +} diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index cefa328..3bd0508 100644 --- a/crates/sourceorigin-standard/src/rules/tests/mod.rs +++ b/crates/sourceorigin-standard/src/rules/tests/mod.rs @@ -1,6 +1,7 @@ //! A fixture workspace the rules check, shared by the tests of each rule. mod budget; +mod cargo_locked; mod comments; mod config_comments; mod fix; diff --git a/crates/sourceorigin-standard/src/rules/text_file.rs b/crates/sourceorigin-standard/src/rules/text_file.rs new file mode 100644 index 0000000..05f67b3 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/text_file.rs @@ -0,0 +1,36 @@ +//! The text files the rules read line by line, such as justfiles and +//! workflows. + +use std::path::{Path, PathBuf}; + +use super::Error; +use crate::workspace::Workspace; + +/// A file's text. +pub(super) struct TextFile { + /// From the repository's root. + pub(super) path: PathBuf, + pub(super) text: String, +} + +impl TextFile { + /// Every file git tracks or would track under `root` matching any of + /// `pathspecs`. + pub(super) fn load_all(root: &Path, pathspecs: &[&str]) -> Result, Error> { + Workspace::new(root) + .files(pathspecs)? + .into_iter() + .filter_map(|path| match std::fs::read_to_string(root.join(&path)) { + Ok(text) => Some(Ok(Self { + path: PathBuf::from(path), + text, + })), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(source) => Some(Err(Error::Read { + path: PathBuf::from(path), + source, + })), + }) + .collect() + } +}