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 @@ -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 --`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
23 changes: 18 additions & 5 deletions crates/sourceorigin-standard/src/rules/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self>) -> Result<(), Error> {
let mut seen = BTreeSet::new();
fixes.retain(|fix| seen.insert((fix.path.clone(), fix.what.clone())));
Expand All @@ -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 {
Expand Down
113 changes: 113 additions & 0 deletions crates/sourceorigin-standard/src/rules/layout.rs
Original file line number Diff line number Diff line change
@@ -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<String, Spanned<toml::Value>>,
}

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<Finding> = 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::<Vec<_>>()
.join(" "),
other => other.as_str().unwrap_or_default().to_owned(),
}
}
}
9 changes: 9 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod comments;
mod config_comments;
mod fix;
mod generated_lints;
mod layout;
mod level;
mod manifest;
mod modules;
Expand All @@ -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};
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -267,6 +273,8 @@ struct Repository {
metadata: Metadata,
/// The root manifest.
root_manifest: TomlFile<RootManifest>,
/// `.cargo/config.toml`.
cargo_config: Option<TomlFile<CargoConfig>>,
/// The manifests of the workspace's crates.
manifests: Vec<TomlFile<Manifest>>,
/// The lints `[workspace.lints]` sets.
Expand Down Expand Up @@ -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)?,
Expand Down
90 changes: 90 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/layout.rs
Original file line number Diff line number Diff line change
@@ -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::<String>::new(),
"{config:?}"
);
}
}
17 changes: 17 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod config_comments;
mod fix;
mod framework;
mod generated_lints;
mod layout;
mod report;
mod unsafe_modules;
mod workspace_lints;
Expand All @@ -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)
}

Expand All @@ -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");
Expand Down Expand Up @@ -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";