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
10 changes: 6 additions & 4 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ A repository adopts the standard in four steps:
- `rust-comments`: Rust files that aren't generated hold only doc comments (`///`, `//!`), `// SAFETY:` comments and `// INVARIANT:` comments; any other `//` or `/* */` comment fails.
- `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`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down Expand Up @@ -98,10 +99,11 @@ piqueld = 2
fix, then how to challenge the rule, suggesting a deviation scoped to its
file.
- `cargo xtask standard --fix` first runs [`rules::fix`], which makes the
fixes that need no judgement and prints each: it adds
`[lints] workspace = true`, makes a workspace lint at `deny` or `forbid`
`warn` (never an `allow`), lowers a ceiling of `budget.toml` to what the
crate holds, and removes a stale deviation or entry of one. It edits each
fixes that need no judgement and prints each, such as adding
`[lints] workspace = true`, making a workspace lint at `deny` or `forbid`
`warn` (never an `allow`), making a crate inherit the workspace's edition,
lowering a ceiling of `budget.toml` to what the crate holds, or removing a
stale deviation or entry of one. It edits each
TOML file as a document, so its layout and comments stay.
- `cargo xtask standard report` prints [`rules::report`] as JSON: each
rule's violations and deviation, deviated or not, with the repository's
Expand Down
16 changes: 16 additions & 0 deletions crates/sourceorigin-standard/src/rules/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pub(super) struct RootManifest {
/// The root manifest's `[workspace]`.
#[derive(Default, Deserialize)]
pub(super) struct Workspace {
pub(super) resolver: Option<Spanned<String>>,
pub(super) package: Option<Spanned<WorkspacePackage>>,
/// Each tool's lints, such as `clippy`'s, each with its setting.
#[serde(default)]
pub(super) lints: BTreeMap<String, BTreeMap<Spanned<String>, Setting>>,
Expand All @@ -39,12 +41,26 @@ pub(super) enum Setting {
Table { level: Level },
}

/// The root manifest's `[workspace.package]`, which crates inherit from.
#[derive(Deserialize)]
pub(super) struct WorkspacePackage {
pub(super) edition: Option<Spanned<String>>,
}

/// A workspace crate's manifest.
#[derive(Deserialize)]
pub(super) struct Manifest {
pub(super) package: Option<Spanned<Package>>,
pub(super) lints: Option<Spanned<toml::Table>>,
}

/// A crate's `[package]`.
#[derive(Deserialize)]
pub(super) struct Package {
/// A string, or `{ workspace = true }`.
pub(super) edition: Option<Spanned<toml::Value>>,
}

impl TomlFile<RootManifest> {
/// The root manifest under `root`.
pub(super) fn load_root(root: &Path) -> Result<Self, Error> {
Expand Down
8 changes: 8 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod tests;
mod toml_file;
mod unsafe_modules;
mod workspace_lints;
mod workspace_manifest;

use std::fmt;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -118,6 +119,10 @@ rules! {
/// `[comments] block-lines` (6 by default), and the file holds at most
/// `[comments] file-lines` comment lines (40 by default).
ConfigComments = "config-comments" => config_comments,
/// The root manifest's `[workspace]` sets `resolver = "3"`, its
/// `[workspace.package]` sets `edition = "2024"`, and every workspace
/// crate inherits it with `edition.workspace = true`.
WorkspaceManifest = "workspace-manifest" => workspace_manifest,
}

/// Why the rules couldn't be checked.
Expand Down Expand Up @@ -260,6 +265,8 @@ struct Repository {
config: Config,
/// The workspace's crates.
metadata: Metadata,
/// The root manifest.
root_manifest: TomlFile<RootManifest>,
/// The manifests of the workspace's crates.
manifests: Vec<TomlFile<Manifest>>,
/// The lints `[workspace.lints]` sets.
Expand Down Expand Up @@ -287,6 +294,7 @@ impl Repository {
config: Config::load(root)?,
manifests: TomlFile::load_all(&metadata)?,
lint_levels: LintLevel::all(&root_manifest),
root_manifest,
modules: Modules::of(&metadata, &sources),
budget: Budget::load(root)?,
commented: Commented::load_all(root)?,
Expand Down
9 changes: 9 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod generated_lints;
mod report;
mod unsafe_modules;
mod workspace_lints;
mod workspace_manifest;

use super::Rule;
use crate::testing::Repository;
Expand Down Expand Up @@ -42,6 +43,14 @@ impl Fixture {
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");
super::Fix::apply_all(self.0.root(), &mut rule.check(&repository).fixes)
.expect("the fixes are made");
self
}

/// The violations of `rule`, each as `path:line: message (rule)`.
fn violations(&self, rule: Rule) -> Vec<String> {
super::check(self.0.root())
Expand Down
53 changes: 53 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/workspace_manifest.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use super::Fixture;
use crate::rules::Rule;

#[test]
fn the_root_sets_the_resolver_and_edition_every_crate_inherits() {
let fixture = Fixture::new();
fixture
.write(
"Cargo.toml",
"[workspace]\nmembers = [\"crates/*\"]\n\n[workspace.package]\nedition = \"2021\"\n",
)
.add_crate("own", "")
.write(
"crates/inherits/Cargo.toml",
"[package]\nname = \"inherits\"\nedition.workspace = true\n",
)
.write("crates/inherits/src/lib.rs", "")
.write(
"crates/missing/Cargo.toml",
"[package]\nname = \"missing\"\n",
)
.write("crates/missing/src/lib.rs", "");
assert_eq!(
fixture.violations(Rule::WorkspaceManifest),
[
"Cargo.toml:1: `[workspace]` sets no `resolver`: add `resolver = \"3\"` \
(workspace-manifest)",
"Cargo.toml:5: `[workspace.package]` sets `edition = \"2021\"`: make it \"2024\", \
migrating with `cargo fix --edition` (workspace-manifest)",
"crates/missing/Cargo.toml:1: the crate sets its own edition: inherit the \
workspace's with `edition.workspace = true` (workspace-manifest)",
"crates/own/Cargo.toml:3: the crate sets its own edition: inherit the workspace's \
with `edition.workspace = true` (workspace-manifest)",
]
);
}

#[test]
fn fix_makes_a_crate_inherit_the_edition_it_repeats() {
let fixture = Fixture::new();
fixture
.write(
"Cargo.toml",
"[workspace]\nresolver = \"3\"\nmembers = [\"crates/*\"]\n\n\
[workspace.package]\nedition = \"2024\"\n",
)
.add_crate("core", "");
fixture.fix_rule(Rule::WorkspaceManifest);
assert_eq!(
fixture.violations(Rule::WorkspaceManifest),
Vec::<String>::new()
);
}
101 changes: 101 additions & 0 deletions crates/sourceorigin-standard/src/rules/workspace_manifest.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//! `workspace-manifest`: one resolver and one edition, set by the root
//! manifest.

use super::fix::{Checked, Fix};
use super::manifest::ROOT;
use super::{Finding, Repository};

/// The resolver the root manifest sets.
const RESOLVER: &str = "3";

/// The edition `[workspace.package]` sets.
const EDITION: &str = "2024";

impl Repository {
/// The root manifest's resolver and edition when they aren't the
/// standard's, and each crate that doesn't inherit the edition. A crate
/// setting the workspace's edition itself is fixed to inherit it.
pub(super) fn workspace_manifest(&self) -> Checked {
let root = &self.root_manifest;
let workspace = &root.value.workspace;
let finding = |line, message: String| Finding {
path: ROOT.into(),
line,
message,
};
let edition = workspace
.package
.as_ref()
.and_then(|package| package.get_ref().edition.as_ref());
let mut findings = Vec::new();
match &workspace.resolver {
Some(resolver) if resolver.get_ref() == RESOLVER => {}
Some(resolver) => findings.push(finding(
root.line(resolver),
format!(
"`resolver` is \"{}\": make it \"{RESOLVER}\"",
resolver.get_ref()
),
)),
None => findings.push(finding(
1,
format!("`[workspace]` sets no `resolver`: add `resolver = \"{RESOLVER}\"`"),
)),
}
match edition {
Some(edition) if edition.get_ref() == EDITION => {}
Some(edition) => findings.push(finding(
root.line(edition),
format!(
"`[workspace.package]` sets `edition = \"{}\"`: make it \"{EDITION}\", \
migrating with `cargo fix --edition`",
edition.get_ref()
),
)),
None => findings.push(finding(
1,
format!("no `[workspace.package]` `edition`: add `edition = \"{EDITION}\"` to it"),
)),
}
let inheritable = edition.is_some_and(|edition| edition.get_ref() == EDITION);
let mut fixes = Vec::new();
for manifest in &self.manifests {
let Some(package) = &manifest.value.package else {
continue;
};
let edition = package.get_ref().edition.as_ref();
let inherits = edition
.and_then(|edition| edition.get_ref().get("workspace"))
.and_then(toml::Value::as_bool)
== Some(true);
if inherits {
continue;
}
let line =
edition.map_or_else(|| manifest.line(package), |edition| manifest.line(edition));
findings.push(Finding {
path: manifest.path.clone(),
line,
message: "the crate sets its own edition: inherit the workspace's with \
`edition.workspace = true`"
.to_owned(),
});
let repeats = edition
.and_then(|edition| edition.get_ref().as_str())
.is_some_and(|edition| edition == EDITION);
if repeats && inheritable {
fixes.push(Fix::new(
manifest.path.clone(),
"inherit the workspace's edition".to_owned(),
|document| {
let mut inherited = toml_edit::Table::new();
inherited.set_dotted(true);
inherited["workspace"] = toml_edit::value(true);
document["package"]["edition"] = toml_edit::Item::Table(inherited);
},
));
}
}
Checked { findings, fixes }
}
}