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 @@ -43,6 +43,7 @@ A repository adopts the standard in four steps:
- `agent-files`: `AGENTS.md` sits at the root, and no `CLAUDE.md` exists. Each skill is `.agents/skills/<name>/SKILL.md`, its frontmatter's `name` is `<name>`, and `.claude/skills` is a symlink to `../.agents/skills`.
- `agents-md`: AGENTS.md names every workspace crate, by its name in backticks or its directory, and holds at most 150 lines.
- `toolchain`: `rust-toolchain.toml` pins `channel = "stable"` and installs at least the `rustfmt` and `clippy` components.
- `rustfmt-config`: `rustfmt.toml` sets `edition = "2024"`, `newline_style = "Unix"` and `use_field_init_shorthand = true`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
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 @@ -17,6 +17,8 @@ mod level;
mod manifest;
mod modules;
mod report;
mod rustfmt_config;
mod settings;
mod source;
#[cfg(test)]
mod tests;
Expand All @@ -42,6 +44,7 @@ use layout::CargoConfig;
use manifest::{Manifest, RootManifest};
use modules::Modules;
pub use report::{Report, RuleReport};
use settings::Settings;
use source::{Source, Unparsed};
use text_file::TextFile;
use toml_file::TomlFile;
Expand Down Expand Up @@ -151,6 +154,9 @@ rules! {
/// `rust-toolchain.toml` pins `channel = "stable"` and installs at
/// least the `rustfmt` and `clippy` components.
Toolchain = "toolchain" => toolchain,
/// `rustfmt.toml` sets `edition = "2024"`, `newline_style = "Unix"` and
/// `use_field_init_shorthand = true`.
RustfmtConfig = "rustfmt-config" => rustfmt_config,
}

/// Why the rules couldn't be checked.
Expand Down Expand Up @@ -297,6 +303,8 @@ struct Repository {
root_manifest: TomlFile<RootManifest>,
/// `rust-toolchain.toml`.
toolchain: Option<TomlFile<ToolchainFile>>,
/// `rustfmt.toml`, empty when missing.
rustfmt: TomlFile<Settings>,
/// `.cargo/config.toml`.
cargo_config: Option<TomlFile<CargoConfig>>,
/// The manifests of the workspace's crates.
Expand Down Expand Up @@ -334,6 +342,7 @@ impl Repository {
root_manifest,
cargo_config: TomlFile::load(root, layout::CARGO_CONFIG)?,
toolchain: TomlFile::load(root, toolchain::PATH)?,
rustfmt: TomlFile::load_or_empty(root, rustfmt_config::PATH)?,
modules: Modules::of(&metadata, &sources),
budget: Budget::load(root)?,
commented: Commented::load_all(root)?,
Expand Down
22 changes: 22 additions & 0 deletions crates/sourceorigin-standard/src/rules/rustfmt_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! `rustfmt-config`: rustfmt formats every repository alike.

use super::Repository;
use super::fix::Checked;
use super::settings::Value;

/// rustfmt's configuration, from the repository's root.
pub(super) const PATH: &str = "rustfmt.toml";

/// The settings it requires.
const REQUIRED: [(&str, Value); 3] = [
("edition", Value::Str("2024")),
("newline_style", Value::Str("Unix")),
("use_field_init_shorthand", Value::Bool(true)),
];

impl Repository {
/// Each required setting `rustfmt.toml` lacks or sets otherwise.
pub(super) fn rustfmt_config(&self) -> Checked {
self.rustfmt.settings_are(&REQUIRED)
}
}
87 changes: 87 additions & 0 deletions crates/sourceorigin-standard/src/rules/settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! Flat TOML files of `key = value` settings, such as `rustfmt.toml`, and
//! the values the rules require of them.

use std::collections::BTreeMap;

use toml::Spanned;

use super::Finding;
use super::fix::{Checked, Fix};
use super::toml_file::TomlFile;

/// A flat TOML file's settings.
pub(super) type Settings = BTreeMap<Spanned<String>, toml::Value>;

/// A value a setting must have.
#[derive(Clone, Copy)]
pub(super) enum Value {
Str(&'static str),
Bool(bool),
}

impl Value {
fn is(self, value: &toml::Value) -> bool {
match self {
Self::Str(wanted) => value.as_str() == Some(wanted),
Self::Bool(wanted) => value.as_bool() == Some(wanted),
}
}

/// The value, for a TOML document.
fn toml(self) -> toml_edit::Value {
match self {
Self::Str(wanted) => wanted.into(),
Self::Bool(wanted) => wanted.into(),
}
}

/// The value as TOML writes it.
fn literal(self) -> String {
match self {
Self::Str(wanted) => format!("\"{wanted}\""),
Self::Bool(wanted) => wanted.to_string(),
}
}
}

impl TomlFile<Settings> {
/// The setting `key`, with its line.
fn setting(&self, key: &str) -> Option<(usize, &toml::Value)> {
self.value
.iter()
.find(|(name, _)| name.get_ref() == key)
.map(|(name, value)| (self.line(name), value))
}

/// Each of `required` the file doesn't set to its value, fixed by
/// setting it.
pub(super) fn settings_are(&self, required: &[(&'static str, Value)]) -> Checked {
let mut checked = Checked::default();
for &(key, wanted) in required {
let setting = format!("{key} = {}", wanted.literal());
let (line, message) = match self.setting(key) {
Some((_, value)) if wanted.is(value) => continue,
Some((line, _)) => (line, format!("`{key}` has another value: set `{setting}`")),
None => (1, format!("`{key}` is unset: add `{setting}`")),
};
checked.findings.push(Finding {
path: self.path.clone(),
line,
message,
});
checked.fixes.push(Fix::new(
self.path.clone(),
format!("set `{setting}`"),
move |document| {
let new = wanted.toml();
if document.contains_key(key) {
Fix::set(&mut document[key], new);
} else {
document[key] = toml_edit::Item::Value(new);
}
},
));
}
checked
}
}
7 changes: 6 additions & 1 deletion crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod framework;
mod generated_lints;
mod layout;
mod report;
mod rustfmt_config;
mod toolchain;
mod unsafe_modules;
mod workspace_lints;
Expand Down Expand Up @@ -106,7 +107,7 @@ 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); 2] = [
const CONFIG: [(&str, &str); 3] = [
(
".cargo/config.toml",
"[alias]\nxtask = \"run --locked --package xtask --\"\n",
Expand All @@ -115,6 +116,10 @@ const CONFIG: [(&str, &str); 2] = [
"rust-toolchain.toml",
"[toolchain]\nchannel = \"stable\"\ncomponents = [\"rustfmt\", \"clippy\"]\n",
),
(
"rustfmt.toml",
"edition = \"2024\"\nnewline_style = \"Unix\"\nuse_field_init_shorthand = true\n",
),
];

/// A manifest tail inheriting the workspace's lints.
Expand Down
38 changes: 38 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/rustfmt_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use super::{Fixture, INHERITS};
use crate::rules::Rule;

#[test]
fn rustfmt_sets_the_standard_settings() {
let fixture = Fixture::new();
fixture.add_crate("core", INHERITS).write(
"rustfmt.toml",
"edition = \"2021\"\nnewline_style = \"Unix\"\nmax_width = 120\n",
);
assert_eq!(
fixture.violations(Rule::RustfmtConfig),
[
"rustfmt.toml:1: `edition` has another value: set `edition = \"2024\"` \
(rustfmt-config)",
"rustfmt.toml:1: `use_field_init_shorthand` is unset: add \
`use_field_init_shorthand = true` (rustfmt-config)",
]
);
fixture.fix_rule(Rule::RustfmtConfig);
assert_eq!(
fixture.violations(Rule::RustfmtConfig),
Vec::<String>::new()
);
}

#[test]
fn fix_writes_a_missing_rustfmt_toml() {
let fixture = Fixture::new();
fixture
.add_crate("core", INHERITS)
.remove("rustfmt.toml")
.fix_rule(Rule::RustfmtConfig);
assert_eq!(
fixture.violations(Rule::RustfmtConfig),
Vec::<String>::new()
);
}
14 changes: 14 additions & 0 deletions crates/sourceorigin-standard/src/rules/toml_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ impl<T: DeserializeOwned> TomlFile<T> {
}
}

/// The file at `path`, from `root`, or an empty one when there is
/// none, which a fix writes.
pub(super) fn load_or_empty(root: &Path, path: impl Into<PathBuf>) -> Result<Self, Error>
where
T: Default,
{
let path = path.into();
Ok(Self::load(root, &path)?.unwrap_or_else(|| Self {
path,
text: String::new(),
value: T::default(),
}))
}

/// The file at `path`, from `root`, which must exist.
pub(super) fn require(root: &Path, path: impl Into<PathBuf>) -> Result<Self, Error> {
let path = path.into();
Expand Down