diff --git a/crates/sourceorigin-standard/src/rules/budget.rs b/crates/sourceorigin-standard/src/rules/budget.rs index 6a57a88..e51a89a 100644 --- a/crates/sourceorigin-standard/src/rules/budget.rs +++ b/crates/sourceorigin-standard/src/rules/budget.rs @@ -9,8 +9,8 @@ use toml::Spanned; use super::comments::Comment; use super::fix::{Checked, Fix}; use super::level::Level; +use super::toml_file::TomlFile; use super::{Error, Finding, Repository}; -use crate::config::line_of; /// Where the budget lives, from the repository's root. pub(super) const PATH: &str = "budget.toml"; @@ -53,33 +53,24 @@ struct File { impl Budget { /// Loads the budget under `root`. pub(super) fn load(root: &Path) -> Result { - let path = root.join(PATH); - let text = match std::fs::read_to_string(&path) { - Ok(text) => text, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return Ok(Self::default()); - } - Err(source) => return Err(Error::Read { path, source }), + let Some(file) = TomlFile::::load(root, PATH)? else { + return Ok(Self::default()); }; - let file: File = toml::from_str(&text).map_err(|error| Error::Toml { - path: PATH.into(), - message: error.to_string(), - })?; Ok(Self { - expect: Ceilings::of(&text, file.expect), - invariant: Ceilings::of(&text, file.invariant), + expect: Ceilings::of(&file, &file.value.expect), + invariant: Ceilings::of(&file, &file.value.invariant), }) } } impl Ceilings { - fn of(text: &str, table: BTreeMap, usize>) -> Self { + fn of(file: &TomlFile, table: &BTreeMap, usize>) -> Self { Self( table - .into_iter() - .map(|(name, count)| { - let line = line_of(text, name.span().start); - (name.into_inner(), Ceiling { count, line }) + .iter() + .map(|(name, &count)| { + let line = file.line(name); + (name.get_ref().clone(), Ceiling { count, line }) }) .collect(), ) diff --git a/crates/sourceorigin-standard/src/rules/manifest.rs b/crates/sourceorigin-standard/src/rules/manifest.rs new file mode 100644 index 0000000..f2c4c8c --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/manifest.rs @@ -0,0 +1,70 @@ +//! The workspace's manifests: the root's `[workspace]`, and each crate's, +//! reduced to what the rules read. + +use std::collections::BTreeMap; +use std::path::Path; + +use serde::Deserialize; +use toml::Spanned; + +use super::Error; +use super::level::Level; +use super::toml_file::TomlFile; +use crate::metadata::Metadata; + +/// The root manifest, from the repository's root. +pub(super) const ROOT: &str = "Cargo.toml"; + +/// The root manifest. +#[derive(Deserialize)] +pub(super) struct RootManifest { + #[serde(default)] + pub(super) workspace: Workspace, +} + +/// The root manifest's `[workspace]`. +#[derive(Default, Deserialize)] +pub(super) struct Workspace { + /// Each tool's lints, such as `clippy`'s, each with its setting. + #[serde(default)] + pub(super) lints: BTreeMap, Setting>>, +} + +/// A lint's setting in a manifest: its level, alone or in a table beside +/// its priority. +#[derive(Deserialize)] +#[serde(untagged)] +pub(super) enum Setting { + Level(Level), + Table { level: Level }, +} + +/// A workspace crate's manifest. +#[derive(Deserialize)] +pub(super) struct Manifest { + pub(super) lints: Option>, +} + +impl TomlFile { + /// The root manifest under `root`. + pub(super) fn load_root(root: &Path) -> Result { + Self::require(root, ROOT) + } +} + +impl TomlFile { + /// The manifest of every crate `metadata` lists. + pub(super) fn load_all(metadata: &Metadata) -> Result, Error> { + metadata + .packages + .iter() + .map(|package| { + let path = &package.manifest_path; + Self::require( + &metadata.workspace_root, + path.strip_prefix(&metadata.workspace_root).unwrap_or(path), + ) + }) + .collect() + } +} diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index 3997b02..eeb5dda 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -10,11 +10,13 @@ mod config_comments; mod fix; mod generated_lints; mod level; +mod manifest; mod modules; mod report; mod source; #[cfg(test)] mod tests; +mod toml_file; mod unsafe_modules; mod workspace_lints; @@ -28,10 +30,12 @@ use budget::Budget; use config_comments::Commented; use fix::Checked; pub use fix::Fix; +use manifest::{Manifest, RootManifest}; use modules::Modules; pub use report::{Report, RuleReport}; use source::{Source, Unparsed}; -use workspace_lints::{LintLevel, Manifest}; +use toml_file::TomlFile; +use workspace_lints::LintLevel; /// Declares the rules: each variant's doc comment is the doc [`Rule::doc`] /// returns, its string its stable name, and its method the check it runs on @@ -257,7 +261,7 @@ struct Repository { /// The workspace's crates. metadata: Metadata, /// The manifests of the workspace's crates. - manifests: Vec, + manifests: Vec>, /// The lints `[workspace.lints]` sets. lint_levels: Vec, /// Every Rust file git tracks or would track that parses, by path. @@ -278,10 +282,11 @@ impl Repository { fn load(root: &Path) -> Result { let metadata = Metadata::load(Workspace::new(root))?; let (sources, unparsed) = Source::load_all(root)?; + let root_manifest = TomlFile::::load_root(root)?; Ok(Self { config: Config::load(root)?, - manifests: Manifest::load_all(&metadata)?, - lint_levels: LintLevel::load_all(&metadata.workspace_root)?, + manifests: TomlFile::load_all(&metadata)?, + lint_levels: LintLevel::all(&root_manifest), modules: Modules::of(&metadata, &sources), budget: Budget::load(root)?, commented: Commented::load_all(root)?, diff --git a/crates/sourceorigin-standard/src/rules/toml_file.rs b/crates/sourceorigin-standard/src/rules/toml_file.rs new file mode 100644 index 0000000..5f2af8f --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/toml_file.rs @@ -0,0 +1,55 @@ +//! The TOML files the rules read, each deserialized into the shape its rule +//! needs, keeping its text for the lines of what the rule finds. + +use std::path::{Path, PathBuf}; + +use serde::de::DeserializeOwned; +use toml::Spanned; + +use super::Error; +use crate::config::line_of; + +/// A TOML file, as `T` reads it. +pub(super) struct TomlFile { + /// From the repository's root. + pub(super) path: PathBuf, + text: String, + pub(super) value: T, +} + +impl TomlFile { + /// The file at `path`, from `root`, or `None` when there is none. + pub(super) fn load(root: &Path, path: impl Into) -> Result, Error> { + let path = path.into(); + match std::fs::read_to_string(root.join(&path)) { + Ok(text) => Self::parse(path, text).map(Some), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(source) => Err(Error::Read { path, source }), + } + } + + /// The file at `path`, from `root`, which must exist. + pub(super) fn require(root: &Path, path: impl Into) -> Result { + let path = path.into(); + let text = std::fs::read_to_string(root.join(&path)).map_err(|source| Error::Read { + path: path.clone(), + source, + })?; + Self::parse(path, text) + } + + fn parse(path: PathBuf, text: String) -> Result { + let value = toml::from_str(&text).map_err(|error| Error::Toml { + path: path.clone(), + message: error.to_string(), + })?; + Ok(Self { path, text, value }) + } +} + +impl TomlFile { + /// The line, from 1, where `spanned` starts. + pub(super) fn line(&self, spanned: &Spanned) -> usize { + line_of(&self.text, spanned.span().start) + } +} diff --git a/crates/sourceorigin-standard/src/rules/workspace_lints.rs b/crates/sourceorigin-standard/src/rules/workspace_lints.rs index a73d21e..b09ac66 100644 --- a/crates/sourceorigin-standard/src/rules/workspace_lints.rs +++ b/crates/sourceorigin-standard/src/rules/workspace_lints.rs @@ -1,31 +1,11 @@ //! `workspace-lints`: every crate inherits the workspace's lints, which all //! warn. -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; - -use serde::Deserialize; -use toml::Spanned; - use super::fix::{Checked, Fix}; use super::level::Level; -use super::{Error, Finding, Repository}; -use crate::config::line_of; -use crate::metadata::Metadata; - -/// A workspace crate's manifest, reduced to its `[lints]` table. -pub(super) struct Manifest { - /// From the repository's root. - path: PathBuf, - /// Its `[lints]` table's line, and whether it says `workspace = true`. - lints: Option<(usize, bool)>, -} - -/// A manifest's `[lints]` table, with where it is. -#[derive(Deserialize)] -struct Lints { - lints: Option>, -} +use super::manifest::{ROOT, RootManifest, Setting}; +use super::toml_file::TomlFile; +use super::{Finding, Repository}; /// The lints the standard requires the workspace to set to `warn`, as /// `[workspace.lints.] `. @@ -57,57 +37,24 @@ pub(super) struct LintLevel { line: usize, } -/// A lint's setting in a manifest: its level, alone or in a table beside -/// its priority. -#[derive(Deserialize)] -#[serde(untagged)] -enum Setting { - Level(Level), - Table { level: Level }, -} - -/// The root manifest's `[workspace.lints]`, each lint with where it is. -#[derive(Deserialize)] -struct Root { - workspace: Option, -} - -#[derive(Deserialize)] -struct RootWorkspace { - #[serde(default)] - lints: BTreeMap, Setting>>, -} - impl LintLevel { - /// The root manifest. - pub(super) const PATH: &str = "Cargo.toml"; - - /// The lints `[workspace.lints]` sets, from the root manifest under - /// `root`. - pub(super) fn load_all(root: &Path) -> Result, Error> { - let path = root.join(Self::PATH); - let text = std::fs::read_to_string(&path).map_err(|source| Error::Read { path, source })?; - let manifest: Root = toml::from_str(&text).map_err(|error| Error::Toml { - path: Self::PATH.into(), - message: error.to_string(), - })?; - let tools = manifest + /// The lints the root manifest's `[workspace.lints]` sets. + pub(super) fn all(root: &TomlFile) -> Vec { + root.value .workspace - .map_or_else(BTreeMap::new, |workspace| workspace.lints); - Ok(tools - .into_iter() + .lints + .iter() .flat_map(|(tool, lints)| { - let text = &text; - lints.into_iter().map(move |(name, setting)| Self { + lints.iter().map(move |(name, setting)| Self { tool: tool.clone(), - line: line_of(text, name.span().start), - name: name.into_inner(), + line: root.line(name), + name: name.get_ref().clone(), level: match setting { - Setting::Level(level) | Setting::Table { level } => level, + Setting::Level(level) | Setting::Table { level } => *level, }, }) }) - .collect()) + .collect() } /// Its name as attributes write it, such as `clippy::panic`. @@ -125,37 +72,6 @@ impl LintLevel { } } -impl Manifest { - /// The manifest of every crate `metadata` lists. - pub(super) fn load_all(metadata: &Metadata) -> Result, Error> { - metadata - .packages - .iter() - .map(|package| Self::load(&package.manifest_path, &metadata.workspace_root)) - .collect() - } - - fn load(path: &Path, root: &Path) -> Result { - let text = std::fs::read_to_string(path).map_err(|source| Error::Read { - path: path.to_owned(), - source, - })?; - let path = path.strip_prefix(root).unwrap_or(path).to_owned(); - let manifest: Lints = toml::from_str(&text).map_err(|error| Error::Toml { - path: path.clone(), - message: error.to_string(), - })?; - let lints = manifest.lints.map(|lints| { - let inherits = lints - .get_ref() - .get("workspace") - .and_then(toml::Value::as_bool); - (line_of(&text, lints.span().start), inherits == Some(true)) - }); - Ok(Self { path, lints }) - } -} - impl Repository { /// Each crate whose manifest lacks `[lints] workspace = true`, which /// Cargo allows only without lint tables of the crate's own; each lint @@ -166,20 +82,28 @@ impl Repository { let crates = self .manifests .iter() - .filter_map(|manifest| match manifest.lints { + .filter_map(|manifest| match &manifest.value.lints { None => Some(Finding { path: manifest.path.clone(), line: 1, message: "no `[lints]`: add `[lints] workspace = true`".to_owned(), }), - Some((line, false)) => Some(Finding { - path: manifest.path.clone(), - line, - message: "`[lints]` declares the crate's own lints: move them to \ - `[workspace.lints]`, and inherit those with `workspace = true`" - .to_owned(), - }), - Some((_, true)) => None, + Some(lints) + if lints + .get_ref() + .get("workspace") + .and_then(toml::Value::as_bool) + != Some(true) => + { + Some(Finding { + path: manifest.path.clone(), + line: manifest.line(lints), + message: "`[lints]` declares the crate's own lints: move them to \ + `[workspace.lints]`, and inherit those with `workspace = true`" + .to_owned(), + }) + } + Some(_) => None, }); let levels = self.lint_levels.iter().filter_map(|lint| { let message = match lint.level { @@ -195,7 +119,7 @@ impl Repository { ), }; Some(Finding { - path: LintLevel::PATH.into(), + path: ROOT.into(), line: lint.line, message, }) @@ -209,7 +133,7 @@ impl Repository { .any(|lint| lint.tool == *tool && lint.name == *name) }) .map(|(tool, name)| Finding { - path: LintLevel::PATH.into(), + path: ROOT.into(), line: 1, message: format!( "the standard requires `{name} = \"warn\"` in `[workspace.lints.{tool}]`" @@ -218,7 +142,7 @@ impl Repository { let inherit = self .manifests .iter() - .filter(|manifest| manifest.lints.is_none()) + .filter(|manifest| manifest.value.lints.is_none()) .map(|manifest| { Fix::new( manifest.path.clone(), @@ -233,7 +157,7 @@ impl Repository { .map(|lint| { let (tool, name) = (lint.tool.clone(), lint.name.clone()); Fix::new( - LintLevel::PATH, + ROOT, format!("make `{}` `warn`", lint.lint()), move |document| { let item = &mut document["workspace"]["lints"][&tool][&name];