Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
170 changes: 170 additions & 0 deletions crates/sourceorigin-standard/src/rules/cargo_locked.rs
Original file line number Diff line number Diff line change
@@ -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<Unlocked<'_>> {
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<Unlocked<'a>> {
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<usize, Vec<Unlocked<'_>>> = 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
}
}
66 changes: 53 additions & 13 deletions crates/sourceorigin-standard/src/rules/fix.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<dyn Fn(&mut DocumentMut)>,
edit: Edit,
}

/// How a fix changes its file.
enum Edit {
/// An edit to a TOML file's document.
Toml(Box<dyn Fn(&mut DocumentMut)>),
/// 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 {
Expand All @@ -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<PathBuf>, what: String, line: usize, text: String) -> Self {
Self {
path: path.into(),
what,
edit: Edit::Line(line, text),
}
}

Expand Down Expand Up @@ -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<String> = 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");
}
Expand Down
16 changes: 14 additions & 2 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! their docs.

mod budget;
mod cargo_locked;
mod comments;
mod config_comments;
mod fix;
Expand All @@ -17,6 +18,7 @@ mod report;
mod source;
#[cfg(test)]
mod tests;
mod text_file;
mod toml_file;
mod unsafe_modules;
mod workspace_lints;
Expand All @@ -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;

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<TextFile>,
/// The manifests, justfiles and workflows, with their comments.
commented: Vec<Commented>,
}
Expand All @@ -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,
Expand Down Expand Up @@ -391,8 +402,9 @@ pub fn check(root: &Path) -> Result<Vec<Violation>, 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
///
Expand Down
Loading