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
6 changes: 4 additions & 2 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).
- `childless-mod-rs`: A module is `foo/mod.rs` only when its directory holds another Rust file; otherwise it is `foo.rs`. A `mod.rs` beside an integration test's, benchmark's or example's root, such as `tests/common/mod.rs`, passes.
- `inline-tests`: An inline `#[cfg(test)] mod … { }` at the top level of a file a target reaches outside test code spans at most 30% of the file's lines; a larger one is a file of its own, `mod tests;`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down Expand Up @@ -102,10 +103,11 @@ piqueld = 2
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, moves a childless `foo/mod.rs` to `foo.rs`, and removes a
crate holds, moves a childless `foo/mod.rs` to `foo.rs`, moves inline
tests over their share of a file to a file of their own, and removes a
stale deviation or entry of one. It edits each TOML file as a document,
so its layout and comments stay, and leaves alone a file a deviation
excuses.
excuses. `cargo fmt` then reflows the lines a move made shorter.
- `cargo xtask standard report` prints [`rules::report`] as JSON: each
rule's violations and deviation, deviated or not, with the repository's
`#[expect]` attributes by lint, its `// INVARIANT:` lines and the lints
Expand Down
8 changes: 6 additions & 2 deletions crates/sourceorigin-standard/src/rules/childless_mod_rs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use super::{Finding, Repository};

impl Repository {
/// Each `mod.rs` whose directory holds no other Rust file, and the fix
/// moving it to `foo.rs`. A `mod.rs` beside an integration test's,
/// moving it to `foo.rs`. A `mod.rs` whose inline tests `inline-tests`
/// moves out keeps them as its child, and one beside an integration test's,
/// benchmark's or example's root passes, since cargo would take `foo.rs`
/// there for a target of its own.
pub(super) fn childless_mod_rs(&self) -> Checked {
Expand All @@ -20,7 +21,10 @@ impl Repository {
};
let has_child = self
.rust_files()
.any(|other| other != path && other.starts_with(dir));
.any(|other| other != path && other.starts_with(dir))
|| self
.oversized_tests()
.any(|tests| tests.source.path == path);
if has_child
|| dir
.parent()
Expand Down
106 changes: 93 additions & 13 deletions crates/sourceorigin-standard/src/rules/fix.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! `--fix`: the edits that resolve a rule's mechanical violations. A TOML
//! file is edited as a document, so it keeps its layout and comments; a
//! Rust file moves.
//! Rust file has lines replaced, is created or moves.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};

use toml_edit::{DocumentMut, Item, Value};
Expand Down Expand Up @@ -31,6 +32,10 @@ type TomlEdit = Box<dyn Fn(&mut DocumentMut)>;
enum Edit {
/// Edits it as a TOML document.
Toml(TomlEdit),
/// Replaces these lines of it, from 1, with this text.
Lines(RangeInclusive<usize>, String),
/// Creates it with this text.
Create(String),
/// Moves it here, from the repository's root, removing the directory
/// it leaves empty.
Move(PathBuf),
Expand All @@ -43,22 +48,41 @@ impl Fix {
what: String,
edit: impl Fn(&mut DocumentMut) + 'static,
) -> Self {
let path = path.into();
Self {
resolves: path.clone(),
path,
what,
edit: Edit::Toml(Box::new(edit)),
}
Self::of(path.into(), what, Edit::Toml(Box::new(edit)))
}

/// Moves `path` to `to`.
pub(super) fn move_to(path: PathBuf, what: String, to: PathBuf) -> Self {
Self::of(path, what, Edit::Move(to))
}

/// Replaces `lines` of `path` with `text`.
pub(super) fn replace_lines(
path: PathBuf,
what: String,
lines: RangeInclusive<usize>,
text: String,
) -> Self {
Self::of(path, what, Edit::Lines(lines, text))
}

/// Creates `path` with `text`.
pub(super) fn create(path: PathBuf, what: String, text: String) -> Self {
Self::of(path, what, Edit::Create(text))
}

/// The fix, resolving a violation in `resolves` rather than its own
/// file.
pub(super) fn resolving(self, resolves: PathBuf) -> Self {
Self { resolves, ..self }
}

fn of(path: PathBuf, what: String, edit: Edit) -> Self {
Self {
resolves: path.clone(),
path,
what,
edit: Edit::Move(to),
edit,
}
}

Expand Down Expand Up @@ -98,12 +122,20 @@ impl Fix {
.iter()
.filter_map(|fix| match &fix.edit {
Edit::Toml(edit) => Some(edit),
Edit::Move(_) => None,
Edit::Lines(..) | Edit::Create(_) | Edit::Move(_) => None,
})
.collect();
if !toml.is_empty() {
Self::edit_toml(path, &file, &toml)?;
}
let text: Vec<_> = fixes
.iter()
.map(|fix| &fix.edit)
.filter(|edit| matches!(edit, Edit::Lines(..) | Edit::Create(_)))
.collect();
if !text.is_empty() {
Self::edit_text(&file, &text)?;
}
for fix in fixes {
if let Edit::Move(to) = &fix.edit {
Self::move_file(&file, &root.join(to))?;
Expand Down Expand Up @@ -139,16 +171,64 @@ impl Fix {
})
}

/// Makes `edits`, each a [`Edit::Lines`] or [`Edit::Create`], to the
/// text of `file`, each against its lines as they were.
fn edit_text(file: &Path, edits: &[&Edit]) -> Result<(), Error> {
let created = edits.iter().find_map(|edit| match edit {
Edit::Create(text) => Some(text.clone()),
Edit::Toml(_) | Edit::Lines(..) | Edit::Move(_) => None,
});
let written = if let Some(text) = created {
text
} else {
let text = std::fs::read_to_string(file).map_err(|source| Error::Read {
path: file.to_owned(),
source,
})?;
let mut lines: Vec<Option<String>> =
text.lines().map(|line| Some(line.to_owned())).collect();
for edit in edits {
let Edit::Lines(range, new) = edit else {
continue;
};
for line in range.clone() {
if let Some(slot) = line.checked_sub(1).and_then(|at| lines.get_mut(at)) {
*slot = (line == *range.start()).then(|| new.clone());
}
}
}
lines
.into_iter()
.flatten()
.map(|line| line + "\n")
.collect()
};
Self::create_parent(file)?;
std::fs::write(file, written).map_err(|source| Error::Write {
path: file.to_owned(),
source,
})
}

/// Creates the directory `file` goes in.
fn create_parent(file: &Path) -> Result<(), Error> {
let Some(dir) = file.parent() else {
return Ok(());
};
std::fs::create_dir_all(dir).map_err(|source| Error::Write {
path: dir.to_owned(),
source,
})
}

/// Moves `from` to `to`, creating `to`'s directory and removing
/// `from`'s once it is empty.
fn move_file(from: &Path, to: &Path) -> Result<(), Error> {
let write = |path: &Path, source| Error::Write {
path: path.to_owned(),
source,
};
if let Some(dir) = to.parent() {
std::fs::create_dir_all(dir).map_err(|source| write(dir, source))?;
}
Self::create_parent(to)?;
std::fs::rename(from, to).map_err(|source| write(to, source))?;
let Some(dir) = from.parent() else {
return Ok(());
Expand Down
Loading