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 @@ -49,6 +49,7 @@ A repository adopts the standard in four steps:
- `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.
- `recipes`: The justfile has the recipes `validate`, `fmt`, `fmt-check`, `lint`, `standard`, `test`, `doc`, `doc-test`, `audit`, `unused` and `check-changed`. `just` alone runs `validate` or `check-changed`; `validate` runs `fmt` first, then at least `lint`, `standard`, `test`, `doc`, `doc-test`, `audit` and `unused`, and never `fmt-check`; `test` takes `*ARGS`, defaulting to `--workspace`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
81 changes: 81 additions & 0 deletions crates/sourceorigin-standard/src/rules/justfile.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//! The repository's justfile, as `just --dump --dump-format json` describes
//! it.

use std::collections::BTreeMap;
use std::path::Path;

use serde::Deserialize;

use super::Error;
use crate::workspace::Workspace;

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

/// The justfile's recipes.
#[derive(Debug, Deserialize)]
pub(super) struct Justfile {
/// The recipe `just` alone runs.
pub(super) first: Option<String>,
pub(super) recipes: BTreeMap<String, Recipe>,
}

/// A recipe.
#[derive(Debug, Deserialize)]
pub(super) struct Recipe {
/// Each line, as fragments: text, or an interpolation.
body: Vec<Vec<serde_json::Value>>,
pub(super) dependencies: Vec<Dependency>,
pub(super) parameters: Vec<Parameter>,
}

/// A recipe another runs first.
#[derive(Debug, Deserialize)]
pub(super) struct Dependency {
pub(super) recipe: String,
}

/// A recipe's parameter.
#[derive(Debug, Deserialize)]
pub(super) struct Parameter {
/// `singular`, `plus` or `star`.
pub(super) kind: String,
/// Its default, a string unless it is an expression.
pub(super) default: Option<serde_json::Value>,
}

impl Justfile {
/// The justfile under `root`, or `None` when there is none.
pub(super) fn load(root: &Path) -> Result<Option<Self>, Error> {
if !root.join(PATH).is_file() {
return Ok(None);
}
let json = Workspace::new(root).output("just", &["--dump", "--dump-format", "json"])?;
serde_json::from_str(&json)
.map(Some)
.map_err(Error::Justfile)
}

/// The names of the recipes `name` depends on, in order.
pub(super) fn dependencies(&self, name: &str) -> Vec<&str> {
self.recipes.get(name).map_or_else(Vec::new, |recipe| {
recipe
.dependencies
.iter()
.map(|dependency| dependency.recipe.as_str())
.collect()
})
}
}

impl Recipe {
/// Its body's lines, each interpolation written `{{…}}`.
pub(super) fn lines(&self) -> impl Iterator<Item = String> {
self.body.iter().map(|fragments| {
fragments
.iter()
.map(|fragment| fragment.as_str().unwrap_or("{{…}}"))
.collect()
})
}
}
16 changes: 16 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ mod config_comments;
mod deny_config;
mod fix;
mod generated_lints;
mod justfile;
mod layout;
mod level;
mod manifest;
mod modules;
mod nextest_config;
mod recipes;
mod report;
mod rustfmt_config;
mod settings;
Expand All @@ -46,6 +48,7 @@ use config_comments::Commented;
use deny_config::DenyConfig;
use fix::Checked;
pub use fix::Fix;
use justfile::Justfile;
use layout::CargoConfig;
use manifest::{Manifest, RootManifest};
use modules::Modules;
Expand Down Expand Up @@ -187,6 +190,13 @@ rules! {
/// as a crate holding a CLI's commands. Each listed name is a workspace
/// crate.
AnyhowEdges = "anyhow-edges" => anyhow_edges,
/// The justfile has the recipes `validate`, `fmt`, `fmt-check`, `lint`,
/// `standard`, `test`, `doc`, `doc-test`, `audit`, `unused` and
/// `check-changed`. `just` alone runs `validate` or `check-changed`;
/// `validate` runs `fmt` first, then at least `lint`, `standard`, `test`,
/// `doc`, `doc-test`, `audit` and `unused`, and never `fmt-check`; `test`
/// takes `*ARGS`, defaulting to `--workspace`.
Recipes = "recipes" => recipes,
}

/// Why the rules couldn't be checked.
Expand Down Expand Up @@ -219,6 +229,9 @@ pub enum Error {
#[source]
source: std::io::Error,
},
/// `just --dump` printed what isn't a justfile's description.
#[error("parse `just --dump --dump-format json`")]
Justfile(#[source] serde_json::Error),
/// A manifest isn't valid TOML.
#[error("{}: {message}", path.display())]
Toml {
Expand Down Expand Up @@ -362,6 +375,8 @@ struct Repository {
nextest: TomlFile<NextestConfig>,
/// `deny.toml`.
deny: Option<TomlFile<DenyConfig>>,
/// The justfile, as `just` describes it.
justfile: Option<Justfile>,
}

impl Repository {
Expand All @@ -387,6 +402,7 @@ impl Repository {
agent_files: AgentFiles::load(root)?,
nextest: TomlFile::load_or_empty(root, nextest_config::PATH)?,
deny: TomlFile::load(root, deny_config::PATH)?,
justfile: Justfile::load(root)?,
metadata,
sources,
unparsed,
Expand Down
111 changes: 111 additions & 0 deletions crates/sourceorigin-standard/src/rules/recipes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
//! `recipes`: every repository's justfile runs the same checks under the
//! same names.

use super::justfile::{self, Justfile};
use super::{Finding, Repository};

/// The recipes every justfile has.
const REQUIRED: [&str; 11] = [
"validate",
"fmt",
"fmt-check",
"lint",
"standard",
"test",
"doc",
"doc-test",
"audit",
"unused",
"check-changed",
];

/// The recipes `validate` runs, after `fmt`.
const VALIDATED: [&str; 7] = [
"lint", "standard", "test", "doc", "doc-test", "audit", "unused",
];

/// What `just` alone may run.
const DEFAULTS: [&str; 2] = ["validate", "check-changed"];

/// The default `test` passes on.
const TEST_DEFAULT: &str = "--workspace";

impl Justfile {
/// Where the justfile breaks the standard, each with what fixes it.
fn violations(&self) -> Vec<String> {
let mut violations: Vec<String> = REQUIRED
.iter()
.filter(|&&name| !self.recipes.contains_key(name))
.map(|name| format!("no `{name}` recipe: add it"))
.collect();
let first = self.first.as_deref().unwrap_or_default();
let bodiless = self
.recipes
.get(first)
.is_some_and(|recipe| recipe.lines().next().is_none());
let runs = match self.dependencies(first).as_slice() {
[only] if bodiless => *only,
_ => first,
};
if !DEFAULTS.contains(&runs) {
violations.push(format!(
"`just` alone runs `{first}`: make the first recipe `default: validate` or \
`default: check-changed`"
));
}
if self.recipes.contains_key("validate") {
let validated = self.dependencies("validate");
if validated.first() != Some(&"fmt") {
violations.push(
"`validate` doesn't format first: make `fmt` its first dependency".to_owned(),
);
}
violations.extend(
VALIDATED
.iter()
.filter(|name| !validated.contains(name))
.map(|name| {
format!("`validate` doesn't run `{name}`: add it to its dependencies")
}),
);
if validated.contains(&"fmt-check") {
violations
.push("`validate` runs `fmt-check` after formatting: remove it".to_owned());
}
}
if let Some(test) = self.recipes.get("test") {
let passes_on = test.parameters.iter().any(|parameter| {
parameter.kind == "star"
&& parameter
.default
.as_ref()
.and_then(serde_json::Value::as_str)
== Some(TEST_DEFAULT)
});
if !passes_on {
violations.push(format!(
"`test` doesn't pass arguments on: give it `*ARGS='{TEST_DEFAULT}'`"
));
}
}
violations
}
}

impl Repository {
/// Each way the justfile breaks the standard, or a missing justfile.
pub(super) fn recipes(&self) -> Vec<Finding> {
let violations = match &self.justfile {
Some(justfile) => justfile.violations(),
None => vec!["no justfile: add one with the standard's recipes".to_owned()],
};
violations
.into_iter()
.map(|message| Finding {
path: justfile::PATH.into(),
line: 1,
message,
})
.collect()
}
}
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 @@ -14,6 +14,7 @@ mod framework;
mod generated_lints;
mod layout;
mod nextest_config;
mod recipes;
mod report;
mod rustfmt_config;
mod toolchain;
Expand Down
59 changes: 59 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/recipes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use super::{Fixture, INHERITS};
use crate::rules::Rule;

/// A justfile with every required recipe, `default` and `validate` as the
/// standard has them.
const JUSTFILE: &str = "\
default: check-changed

validate: fmt lint standard test doc doc-test audit unused

fmt:
fmt-check:
lint:
standard:
[positional-arguments]
test *ARGS='--workspace':
cargo nextest run --locked \"$@\"
doc:
doc-test:
audit:
unused:
check-changed:
";

#[test]
fn the_justfile_has_the_standard_recipes() {
let fixture = Fixture::new();
fixture
.add_crate("core", INHERITS)
.write("justfile", JUSTFILE);
assert_eq!(fixture.violations(Rule::Recipes), Vec::<String>::new());

fixture.write(
"justfile",
"build:\n\nvalidate: lint fmt-check test\n\nfmt:\nfmt-check:\nlint:\ntest:\n",
);
let violations: Vec<String> = [
"no `standard` recipe: add it",
"no `doc` recipe: add it",
"no `doc-test` recipe: add it",
"no `audit` recipe: add it",
"no `unused` recipe: add it",
"no `check-changed` recipe: add it",
"`just` alone runs `build`: make the first recipe `default: validate` or \
`default: check-changed`",
"`validate` doesn't format first: make `fmt` its first dependency",
"`validate` doesn't run `standard`: add it to its dependencies",
"`validate` doesn't run `doc`: add it to its dependencies",
"`validate` doesn't run `doc-test`: add it to its dependencies",
"`validate` doesn't run `audit`: add it to its dependencies",
"`validate` doesn't run `unused`: add it to its dependencies",
"`validate` runs `fmt-check` after formatting: remove it",
"`test` doesn't pass arguments on: give it `*ARGS='--workspace'`",
]
.iter()
.map(|message| format!("justfile:1: {message} (recipes)"))
.collect();
assert_eq!(fixture.violations(Rule::Recipes), violations);
}