diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index 25071b6..a94e765 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -38,6 +38,7 @@ A repository adopts the standard in four steps: - `doc-length`: The prose of each item's or module's docs, in a file that isn't generated, spans at most `standard.toml`'s `[comments] doc-lines` lines (10 by default). Code blocks and a crate root's `//!` docs don't count. - `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 --`. Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and diff --git a/crates/sourceorigin-standard/src/rules/fix.rs b/crates/sourceorigin-standard/src/rules/fix.rs index a1e973d..d442674 100644 --- a/crates/sourceorigin-standard/src/rules/fix.rs +++ b/crates/sourceorigin-standard/src/rules/fix.rs @@ -56,7 +56,8 @@ impl Fix { } /// Makes `fixes` under `root`: each file's once, in order, and drops a - /// fix that repeats another. + /// fix that repeats another. A missing file is written, from an empty + /// document. pub(super) fn apply_all(root: &Path, fixes: &mut Vec) -> Result<(), Error> { let mut seen = BTreeSet::new(); fixes.retain(|fix| seen.insert((fix.path.clone(), fix.what.clone()))); @@ -66,10 +67,22 @@ impl Fix { } for (path, fixes) in by_path { let file = root.join(path); - let text = std::fs::read_to_string(&file).map_err(|source| Error::Read { - path: file.clone(), - source, - })?; + let text = match std::fs::read_to_string(&file) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(source) => { + return Err(Error::Read { + path: file.clone(), + source, + }); + } + }; + if let Some(dir) = file.parent() { + std::fs::create_dir_all(dir).map_err(|source| Error::Write { + path: dir.to_owned(), + source, + })?; + } let mut document: DocumentMut = text.parse() .map_err(|error: toml_edit::TomlError| Error::Toml { diff --git a/crates/sourceorigin-standard/src/rules/layout.rs b/crates/sourceorigin-standard/src/rules/layout.rs new file mode 100644 index 0000000..e61d339 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/layout.rs @@ -0,0 +1,113 @@ +//! `layout`: where a workspace's crates live, and how `cargo xtask` runs. + +use std::collections::BTreeMap; +use std::path::Path; + +use serde::Deserialize; +use toml::Spanned; + +use super::fix::{Checked, Fix}; +use super::{Finding, Repository}; + +/// Cargo's configuration, from the repository's root. +pub(super) const CARGO_CONFIG: &str = ".cargo/config.toml"; + +/// The directories crates live in: libraries, binaries and development +/// tasks. +const DIRS: [&str; 3] = ["crates", "apps", "tools"]; + +/// The crate `cargo xtask` runs, and its directory. +const XTASK: &str = "xtask"; +const XTASK_DIR: &str = "tools/xtask"; + +/// What `cargo xtask` stands for. +const ALIAS: &str = "run --locked --package xtask --"; + +/// `.cargo/config.toml`, reduced to its aliases. +#[derive(Deserialize)] +pub(super) struct CargoConfig { + #[serde(default)] + alias: BTreeMap>, +} + +impl Repository { + /// Each crate outside the crate directories, an `xtask` crate missing + /// from `tools/xtask`, and an `xtask` alias that isn't the standard's. + /// A wrong or missing alias is fixed. + pub(super) fn layout(&self) -> Checked { + let root = &self.metadata.workspace_root; + let mut findings: Vec = self + .manifests + .iter() + .filter(|manifest| { + !DIRS + .iter() + .any(|dir| manifest.path.starts_with(dir) && manifest.path != Path::new(dir)) + }) + .map(|manifest| Finding { + path: manifest.path.clone(), + line: 1, + message: "the crate is outside `crates/`, `apps/` and `tools/`: move it to \ + `crates/` for a library, `apps/` for a binary, or `tools/` for a \ + development task" + .to_owned(), + }) + .collect(); + let xtask = self + .metadata + .packages + .iter() + .find(|package| package.name == XTASK); + if xtask.is_none_or(|xtask| xtask.manifest_path.parent() != Some(&root.join(XTASK_DIR))) { + findings.push(Finding { + path: XTASK_DIR.into(), + line: 1, + message: format!( + "no `{XTASK}` crate in `{XTASK_DIR}`: put the repository's development \ + tasks there, run as `cargo xtask`" + ), + }); + } + let alias = self + .cargo_config + .as_ref() + .and_then(|config| Some((config, config.value.alias.get(XTASK)?))); + let wanted = format!("{XTASK} = \"{ALIAS}\""); + match alias { + Some((_, value)) if Self::alias_of(value.get_ref()) == ALIAS => { + return findings.into(); + } + Some((config, value)) => findings.push(Finding { + path: CARGO_CONFIG.into(), + line: config.line(value), + message: format!( + "the `{XTASK}` alias is `{}`: make it `{ALIAS}`", + Self::alias_of(value.get_ref()) + ), + }), + None => findings.push(Finding { + path: CARGO_CONFIG.into(), + line: 1, + message: format!("no `{XTASK}` alias: add `{wanted}` under `[alias]`"), + }), + } + let fixes = vec![Fix::new( + CARGO_CONFIG, + format!("alias `{XTASK}` to `{ALIAS}`"), + |document| document["alias"][XTASK] = toml_edit::value(ALIAS), + )]; + Checked { findings, fixes } + } + + /// An alias's command, from its string or its list of arguments. + fn alias_of(value: &toml::Value) -> String { + match value { + toml::Value::Array(arguments) => arguments + .iter() + .filter_map(toml::Value::as_str) + .collect::>() + .join(" "), + other => other.as_str().unwrap_or_default().to_owned(), + } + } +} diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index 6a74503..b02eccd 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -9,6 +9,7 @@ mod comments; mod config_comments; mod fix; mod generated_lints; +mod layout; mod level; mod manifest; mod modules; @@ -31,6 +32,7 @@ use budget::Budget; use config_comments::Commented; use fix::Checked; pub use fix::Fix; +use layout::CargoConfig; use manifest::{Manifest, RootManifest}; use modules::Modules; pub use report::{Report, RuleReport}; @@ -123,6 +125,10 @@ rules! { /// `[workspace.package]` sets `edition = "2024"`, and every workspace /// crate inherits it with `edition.workspace = true`. WorkspaceManifest = "workspace-manifest" => workspace_manifest, + /// 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 --`. + Layout = "layout" => layout, } /// Why the rules couldn't be checked. @@ -267,6 +273,8 @@ struct Repository { metadata: Metadata, /// The root manifest. root_manifest: TomlFile, + /// `.cargo/config.toml`. + cargo_config: Option>, /// The manifests of the workspace's crates. manifests: Vec>, /// The lints `[workspace.lints]` sets. @@ -295,6 +303,7 @@ impl Repository { manifests: TomlFile::load_all(&metadata)?, lint_levels: LintLevel::all(&root_manifest), root_manifest, + cargo_config: TomlFile::load(root, layout::CARGO_CONFIG)?, modules: Modules::of(&metadata, &sources), budget: Budget::load(root)?, commented: Commented::load_all(root)?, diff --git a/crates/sourceorigin-standard/src/rules/tests/layout.rs b/crates/sourceorigin-standard/src/rules/tests/layout.rs new file mode 100644 index 0000000..989ac96 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/layout.rs @@ -0,0 +1,90 @@ +use super::Fixture; +use crate::rules::Rule; + +/// A root manifest whose members are `members`. +fn root(members: &str) -> String { + format!("[workspace]\nmembers = [{members}]\n") +} + +impl Fixture { + /// Adds the crate at `dir`. + fn add_crate_at(&self, dir: &str) -> &Self { + let name = dir.rsplit('/').next().unwrap_or(dir); + self.write( + &format!("{dir}/Cargo.toml"), + &format!("[package]\nname = \"{name}\"\nedition = \"2024\"\n"), + ) + .write(&format!("{dir}/src/lib.rs"), "") + } +} + +#[test] +fn crates_live_in_their_directories_and_cargo_xtask_runs_locked() { + let fixture = Fixture::new(); + fixture + .write( + "Cargo.toml", + &root("\"crates/core\", \"apps/daemon\", \"tools/xtask\", \"lib\""), + ) + .add_crate_at("crates/core") + .add_crate_at("apps/daemon") + .add_crate_at("tools/xtask") + .add_crate_at("lib") + .write( + ".cargo/config.toml", + "[alias]\nxtask = \"run --package xtask --\"\n", + ); + assert_eq!( + fixture.violations(Rule::Layout), + [ + ".cargo/config.toml:2: the `xtask` alias is `run --package xtask --`: make it \ + `run --locked --package xtask --` (layout)", + "lib/Cargo.toml:1: the crate is outside `crates/`, `apps/` and `tools/`: move it to \ + `crates/` for a library, `apps/` for a binary, or `tools/` for a development task \ + (layout)", + ] + ); +} + +#[test] +fn the_xtask_crate_lives_in_tools() { + let fixture = Fixture::new(); + fixture + .write("Cargo.toml", &root("\"crates/xtask\"")) + .add_crate_at("crates/xtask") + .write( + ".cargo/config.toml", + "[alias]\nxtask = [\"run\", \"--locked\", \"--package\", \"xtask\", \"--\"]\n", + ); + assert_eq!( + fixture.violations(Rule::Layout), + [ + "tools/xtask:1: no `xtask` crate in `tools/xtask`: put the repository's development \ + tasks there, run as `cargo xtask` (layout)" + ] + ); +} + +#[test] +fn fix_aliases_cargo_xtask() { + for config in [ + None, + Some("[env]\nA = \"1\"\n"), + Some("[alias]\nxtask = \"run\"\n"), + ] { + let fixture = Fixture::new(); + fixture + .write("Cargo.toml", &root("\"tools/xtask\"")) + .add_crate_at("tools/xtask"); + match config { + Some(config) => fixture.write(".cargo/config.toml", config), + None => fixture.remove(".cargo/config.toml"), + }; + fixture.fix_rule(Rule::Layout); + assert_eq!( + fixture.violations(Rule::Layout), + Vec::::new(), + "{config:?}" + ); + } +} diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index a4e0aed..cefa328 100644 --- a/crates/sourceorigin-standard/src/rules/tests/mod.rs +++ b/crates/sourceorigin-standard/src/rules/tests/mod.rs @@ -6,6 +6,7 @@ mod config_comments; mod fix; mod framework; mod generated_lints; +mod layout; mod report; mod unsafe_modules; mod workspace_lints; @@ -25,6 +26,9 @@ impl Fixture { "Cargo.toml", &format!("[workspace]\nresolver = \"3\"\nmembers = [\"crates/*\"]\n\n{LINTS}"), ); + for (path, text) in CONFIG { + repository.write(path, text); + } Self(repository) } @@ -43,6 +47,12 @@ impl Fixture { self } + /// Removes the file at `path`, such as one of [`CONFIG`]. + fn remove(&self, path: &str) -> &Self { + std::fs::remove_file(self.0.root().join(path)).expect("the file is removed"); + self + } + /// Makes the fixes of `rule` alone. fn fix_rule(&self, rule: Rule) -> &Self { let repository = super::Repository::load(self.0.root()).expect("the repository loads"); @@ -90,5 +100,12 @@ undocumented_unsafe_blocks = \"warn\" self_named_module_files = \"warn\" "; +/// The configuration files every fixture holds, as the standard has them, +/// so a rule's fixes touch only what a test writes. +const CONFIG: [(&str, &str); 1] = [( + ".cargo/config.toml", + "[alias]\nxtask = \"run --locked --package xtask --\"\n", +)]; + /// A manifest tail inheriting the workspace's lints. const INHERITS: &str = "[lints]\nworkspace = true\n";