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
15 changes: 10 additions & 5 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ A repository adopts the standard in four steps:
- `nextest-config`: `.config/nextest.toml`'s default profile sets a `slow-timeout`, every `slow-timeout` in it has a `terminate-after`, and no profile or override sets `retries`.
- `workspace-dependencies`: Every dependency of a workspace crate, of every kind and target, is inherited with `workspace = true` from the root's `[workspace.dependencies]`, where each `path` dependency also has a `version`.
- `deny-config`: `deny.toml` sets `unknown-registry` and `unknown-git` under `[sources]`, and `wildcards` under `[bans]`, to `"deny"`, allows at least one license, and gives every ignored advisory a `reason`: `{ id = "…", reason = "…" }`.
- `anyhow-edges`: No library depends on `anyhow` (dev-dependencies aside), unless `standard.toml`'s `anyhow-crates` lists it as a binary's edge, such as a crate holding a CLI's commands. Each listed name is a workspace crate.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand All @@ -60,18 +61,22 @@ is optional, and a missing file means the defaults. An unknown key, or a
rule name that doesn't exist, fails with the parser's message naming it.

```toml
# The modules that may expect `unsafe_code`, on the smallest item inside
# them that needs it. A target's root module is its crate's name, such as
# `build_script_build` for a build script.
unsafe-modules = ["my_crate::ffi"]

# The libraries that may depend on `anyhow`, each a binary's edge, such as
# a crate holding a CLI's commands. A crate with no library may anyway.
anyhow-crates = ["my-cli"]

# Rules the repository departs from, each with its reason: everywhere, or
# only in the files `paths` matches and the crates `crates` names. A
# deviation, or an entry of its scope, that excuses no violation is one.
[deviations]
rule-name = "why the repository departs from it everywhere"
other-rule = { reason = "why", paths = ["crates/generated/**"], crates = ["vendored"] }

# The modules that may expect `unsafe_code`, on the smallest item inside
# them that needs it. A target's root module is its crate's name, such as
# `build_script_build` for a build script.
unsafe-modules = ["my_crate::ffi"]

[comments]
# The most lines of prose an item's or module's docs may span, code blocks
# and a crate root's `//!` docs aside.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ fn package(dir: &str, dependencies: &[&str], library: bool) -> Package {
.iter()
.map(|name| Dependency {
name: (*name).to_owned(),
kind: None,
})
.collect(),
targets: vec![Target {
Expand Down
4 changes: 4 additions & 0 deletions crates/sourceorigin-standard/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ pub(crate) struct Config {
pub(crate) unsafe_modules: Vec<Listed>,
/// The `[comments]` table.
pub(crate) comments: Comments,
/// The libraries that may depend on `anyhow`, as the edge of a binary.
pub(crate) anyhow_crates: Vec<Listed>,
}

/// The `[comments]` table: what comments the rules allow.
Expand Down Expand Up @@ -224,6 +226,7 @@ struct File {
check_changed: CheckChanged,
unsafe_modules: Vec<Spanned<String>>,
comments: Comments,
anyhow_crates: Vec<Spanned<String>>,
}

/// A deviation as written: its reason alone, for everywhere, or a table
Expand Down Expand Up @@ -352,6 +355,7 @@ impl Config {
check_changed: file.check_changed,
unsafe_modules: listed(file.unsafe_modules),
comments: file.comments,
anyhow_crates: listed(file.anyhow_crates),
})
}

Expand Down
17 changes: 17 additions & 0 deletions crates/sourceorigin-standard/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ pub(crate) struct Package {
#[derive(Debug, Deserialize)]
pub(crate) struct Dependency {
pub(crate) name: String,
/// Its kind; `None` for a normal dependency.
pub(crate) kind: Option<DependencyKind>,
}

/// A dependency other than a normal one, as `cargo metadata` names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum DependencyKind {
Dev,
Build,
}

/// A package's library, binary, test, example, benchmark or build script.
Expand Down Expand Up @@ -151,6 +161,13 @@ impl Package {
})
}

/// Whether the crate has a normal dependency on `name`.
pub(crate) fn depends_on(&self, name: &str) -> bool {
self.dependencies
.iter()
.any(|dependency| dependency.name == name && dependency.kind.is_none())
}

/// Whether the crate has a library, which doc tests need.
pub(crate) fn has_library(&self) -> bool {
self.targets.iter().any(Target::is_library)
Expand Down
54 changes: 54 additions & 0 deletions crates/sourceorigin-standard/src/rules/anyhow_edges.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//! `anyhow-edges`: libraries return typed errors; `anyhow` stays at a
//! binary's edge.

use super::{Finding, Repository};
use crate::config;

/// The crate that erases error types.
const ANYHOW: &str = "anyhow";

impl Repository {
/// Each library depending on `anyhow` that `anyhow-crates` doesn't
/// list, and each listed name that is no workspace crate.
pub(super) fn anyhow_edges(&self) -> Vec<Finding> {
let listed = &self.config.anyhow_crates;
let mut findings: Vec<Finding> = self
.metadata
.packages
.iter()
.filter(|package| {
package.has_library()
&& package.depends_on(ANYHOW)
&& !listed.iter().any(|listed| listed.value == package.name)
})
.map(|package| Finding {
path: package
.manifest_path
.strip_prefix(&self.metadata.workspace_root)
.unwrap_or(&package.manifest_path)
.to_owned(),
line: 1,
message: format!(
"the library `{}` depends on `{ANYHOW}`: return a `thiserror` enum instead, \
or list the crate in {}'s `anyhow-crates` if it is a binary's edge",
package.name,
config::PATH
),
})
.collect();
findings.extend(
listed
.iter()
.filter(|listed| !self.metadata.has(&listed.value))
.map(|listed| Finding {
path: config::PATH.into(),
line: listed.line,
message: format!(
"`anyhow-crates` lists `{}`, no workspace crate: remove it",
listed.value
),
}),
);
findings
}
}
6 changes: 6 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

mod agent_files;
mod agents_md;
mod anyhow_edges;
mod budget;
mod cargo_locked;
mod clippy_config;
Expand Down Expand Up @@ -181,6 +182,11 @@ rules! {
/// least one license, and gives every ignored advisory a `reason`:
/// `{ id = "…", reason = "…" }`.
DenyConfig = "deny-config" => deny_config,
/// No library depends on `anyhow` (dev-dependencies aside), unless
/// `standard.toml`'s `anyhow-crates` lists it as a binary's edge, such
/// as a crate holding a CLI's commands. Each listed name is a workspace
/// crate.
AnyhowEdges = "anyhow-edges" => anyhow_edges,
}

/// Why the rules couldn't be checked.
Expand Down
36 changes: 36 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/anyhow_edges.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use super::{Fixture, INHERITS};
use crate::rules::Rule;

/// A manifest tail depending on `anyhow`, and on `thiserror` for tests.
const ANYHOW: &str = "\n[dependencies]\nanyhow = \"1\"\n\n[dev-dependencies]\nthiserror = \"2\"\n";

#[test]
fn only_listed_edges_and_binaries_depend_on_anyhow() {
let fixture = Fixture::new();
fixture
.add_crate("core", &format!("{ANYHOW}{INHERITS}"))
.add_crate("cli", &format!("{ANYHOW}{INHERITS}"))
.add_crate(
"tests",
&format!("\n[dev-dependencies]\nanyhow = \"1\"\n{INHERITS}"),
)
.write(
"crates/tool/Cargo.toml",
&format!("[package]\nname = \"tool\"\nedition = \"2024\"\n{ANYHOW}{INHERITS}"),
)
.write("crates/tool/src/main.rs", "fn main() {}\n")
.write(
"standard.toml",
"anyhow-crates = [\n \"cli\",\n \"gone\",\n]\n",
);
assert_eq!(
fixture.violations(Rule::AnyhowEdges),
[
"crates/core/Cargo.toml:1: the library `core` depends on `anyhow`: return a \
`thiserror` enum instead, or list the crate in standard.toml's `anyhow-crates` if \
it is a binary's edge (anyhow-edges)",
"standard.toml:3: `anyhow-crates` lists `gone`, no workspace crate: remove it \
(anyhow-edges)",
]
);
}
1 change: 1 addition & 0 deletions crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

mod agent_files;
mod agents_md;
mod anyhow_edges;
mod budget;
mod cargo_locked;
mod clippy_config;
Expand Down