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
5 changes: 5 additions & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ A repository adopts the standard in four steps:
- `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`.
- `recipes-only`: Every command of `t3.json` runs `just`, and no line of a workflow's or composite action's `run:` starts with `cargo` unless `standard.toml`'s `cargo-in-ci` lists it; each listed line is one a `run:` holds.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand All @@ -71,6 +72,10 @@ unsafe-modules = ["my_crate::ffi"]
# a crate holding a CLI's commands. A crate with no library may anyway.
anyhow-crates = ["my-cli"]

# The lines of workflows' `run:` that run Cargo rather than a recipe, each
# whole, such as a check on the minimum supported Rust version.
cargo-in-ci = ["cargo +1.85 check --locked --workspace"]

# 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.
Expand Down
5 changes: 5 additions & 0 deletions crates/sourceorigin-standard/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ pub(crate) struct Config {
pub(crate) comments: Comments,
/// The libraries that may depend on `anyhow`, as the edge of a binary.
pub(crate) anyhow_crates: Vec<Listed>,
/// The lines of workflows' `run:` that may run Cargo rather than a
/// recipe.
pub(crate) cargo_in_ci: Vec<Listed>,
}

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

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

Expand Down
35 changes: 35 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,23 @@ mod manifest;
mod modules;
mod nextest_config;
mod recipes;
mod recipes_only;
mod report;
mod rustfmt_config;
mod settings;
mod source;
mod t3;
#[cfg(test)]
mod tests;
mod text_file;
mod toml_file;
mod toolchain;
mod unsafe_modules;
mod workflows;
mod workspace_dependencies;
mod workspace_lints;
mod workspace_manifest;
mod yaml;

use std::fmt;
use std::path::{Path, PathBuf};
Expand All @@ -56,9 +60,11 @@ use nextest_config::NextestConfig;
pub use report::{Report, RuleReport};
use settings::Settings;
use source::{Source, Unparsed};
use t3::T3;
use text_file::TextFile;
use toml_file::TomlFile;
use toolchain::ToolchainFile;
use workflows::Workflow;
use workspace_lints::LintLevel;

/// Declares the rules: each variant's doc comment is the doc [`Rule::doc`]
Expand Down Expand Up @@ -197,6 +203,11 @@ rules! {
/// `doc`, `doc-test`, `audit` and `unused`, and never `fmt-check`; `test`
/// takes `*ARGS`, defaulting to `--workspace`.
Recipes = "recipes" => recipes,
/// Every command of `t3.json` runs `just`, and no line of a workflow's
/// or composite action's `run:` starts with `cargo` unless
/// `standard.toml`'s `cargo-in-ci` lists it; each listed line is one a
/// `run:` holds.
RecipesOnly = "recipes-only" => recipes_only,
}

/// Why the rules couldn't be checked.
Expand Down Expand Up @@ -232,6 +243,24 @@ pub enum Error {
/// `just --dump` printed what isn't a justfile's description.
#[error("parse `just --dump --dump-format json`")]
Justfile(#[source] serde_json::Error),
/// A workflow isn't valid YAML.
#[error("parse {}", path.display())]
Yaml {
/// The file, from the repository's root.
path: PathBuf,
/// Where the parser stopped, and why.
#[source]
source: yaml_rust2::ScanError,
},
/// A JSON file, such as `t3.json`, isn't valid or has the wrong shape.
#[error("parse {}", path.display())]
Json {
/// The file, from the repository's root.
path: PathBuf,
/// Why it couldn't be parsed.
#[source]
source: serde_json::Error,
},
/// A manifest isn't valid TOML.
#[error("{}: {message}", path.display())]
Toml {
Expand Down Expand Up @@ -377,6 +406,10 @@ struct Repository {
deny: Option<TomlFile<DenyConfig>>,
/// The justfile, as `just` describes it.
justfile: Option<Justfile>,
/// `t3.json`.
t3: Option<T3>,
/// The workflows and composite actions.
workflows: Vec<Workflow>,
}

impl Repository {
Expand All @@ -403,6 +436,8 @@ impl Repository {
nextest: TomlFile::load_or_empty(root, nextest_config::PATH)?,
deny: TomlFile::load(root, deny_config::PATH)?,
justfile: Justfile::load(root)?,
t3: T3::load(root)?,
workflows: Workflow::load_all(root)?,
metadata,
sources,
unparsed,
Expand Down
68 changes: 68 additions & 0 deletions crates/sourceorigin-standard/src/rules/recipes_only.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! `recipes-only`: T3 Code and CI run the justfile's recipes rather than
//! repeating their commands.

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

impl Repository {
/// Each `t3.json` command that isn't a recipe, each line of a workflow's
/// or action's `run:` starting with `cargo` that `cargo-in-ci` doesn't
/// list, and each listed line no `run:` holds.
pub(super) fn recipes_only(&self) -> Vec<Finding> {
let mut findings = Vec::new();
if let Some(t3) = &self.t3 {
findings.extend(
t3.scripts
.iter()
.filter(|script| script.command.split_whitespace().next() != Some("just"))
.map(|script| Finding {
path: t3::PATH.into(),
line: t3.line(script),
message: format!(
"`{}` isn't a recipe: add it to the justfile, and run it with `just`",
script.command
),
}),
);
}
let allowed = &self.config.cargo_in_ci;
let mut used = vec![false; allowed.len()];
for workflow in &self.workflows {
let runs = workflow.steps().filter_map(|step| step.get("run"));
for (line, command) in runs.flat_map(|run| run.lines()) {
let command = command.trim();
if command.split_whitespace().next() != Some("cargo") {
continue;
}
match allowed.iter().position(|listed| listed.value == command) {
Some(index) => used[index] = true,
None => findings.push(Finding {
path: workflow.path.clone(),
line,
message: format!(
"`{command}` runs Cargo rather than a recipe: run a recipe of the \
justfile, or list the line in {}'s `cargo-in-ci` if no recipe fits",
config::PATH
),
}),
}
}
}
findings.extend(
allowed
.iter()
.zip(used)
.filter(|(_, used)| !used)
.map(|(listed, _)| Finding {
path: config::PATH.into(),
line: listed.line,
message: format!(
"`cargo-in-ci` lists `{}`, which no workflow runs: remove it",
listed.value
),
}),
);
findings
}
}
62 changes: 62 additions & 0 deletions crates/sourceorigin-standard/src/rules/t3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//! `t3.json`: the scripts T3 Code runs in a worktree.

use std::path::Path;

use serde::Deserialize;

use super::Error;

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

/// `t3.json`, with its text for the lines of its scripts.
pub(super) struct T3 {
text: String,
pub(super) scripts: Vec<Script>,
}

/// A script T3 Code offers, or runs on an event.
#[derive(Deserialize)]
pub(super) struct Script {
pub(super) command: String,
}

/// `t3.json` as written.
#[derive(Deserialize)]
struct File {
#[serde(default)]
scripts: Vec<Script>,
}

impl T3 {
/// `t3.json` under `root`, or `None` when there is none.
pub(super) fn load(root: &Path) -> Result<Option<Self>, Error> {
let text = match std::fs::read_to_string(root.join(PATH)) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(source) => {
return Err(Error::Read {
path: PATH.into(),
source,
});
}
};
let file: File = serde_json::from_str(&text).map_err(|source| Error::Json {
path: PATH.into(),
source,
})?;
Ok(Some(Self {
text,
scripts: file.scripts,
}))
}

/// The line, from 1, of `script`'s command.
pub(super) fn line(&self, script: &Script) -> usize {
let quoted = serde_json::to_string(&script.command).unwrap_or_default();
self.text
.lines()
.position(|line| line.contains("\"command\"") && line.contains(&quoted))
.map_or(1, |index| index + 1)
}
}
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 @@ -15,6 +15,7 @@ mod generated_lints;
mod layout;
mod nextest_config;
mod recipes;
mod recipes_only;
mod report;
mod rustfmt_config;
mod toolchain;
Expand Down
42 changes: 42 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/recipes_only.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use super::{Fixture, INHERITS};
use crate::rules::Rule;

#[test]
fn t3_and_ci_run_recipes() {
let fixture = Fixture::new();
fixture
.add_crate("core", INHERITS)
.write(
"t3.json",
"{\n \"scripts\": [\n { \"name\": \"Lint\", \"command\": \"just lint\" },\n \
{ \"name\": \"Check\", \"command\": \"cargo check --locked\" }\n ]\n}\n",
)
.write(
".github/workflows/ci.yml",
"on: push\njobs:\n rust:\n steps:\n - run: just lint\n - run: |\n \
cargo build --locked --package xtask\n cargo +1.85 check --locked\n",
)
.write(
".github/actions/ui/action.yml",
"runs:\n using: composite\n steps:\n - run: cargo build --locked\n shell: bash\n",
)
.write(
"standard.toml",
"cargo-in-ci = [\n \"cargo +1.85 check --locked\",\n \"cargo xtask dist\",\n]\n",
);
assert_eq!(
fixture.violations(Rule::RecipesOnly),
[
".github/actions/ui/action.yml:4: `cargo build --locked` runs Cargo rather than a \
recipe: run a recipe of the justfile, or list the line in standard.toml's \
`cargo-in-ci` if no recipe fits (recipes-only)",
".github/workflows/ci.yml:7: `cargo build --locked --package xtask` runs Cargo \
rather than a recipe: run a recipe of the justfile, or list the line in \
standard.toml's `cargo-in-ci` if no recipe fits (recipes-only)",
"standard.toml:3: `cargo-in-ci` lists `cargo xtask dist`, which no workflow runs: \
remove it (recipes-only)",
"t3.json:4: `cargo check --locked` isn't a recipe: add it to the justfile, and run \
it with `just` (recipes-only)",
]
);
}
59 changes: 59 additions & 0 deletions crates/sourceorigin-standard/src/rules/workflows.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! The repository's GitHub Actions workflows and composite actions.

use std::path::{Path, PathBuf};

use super::Error;
use super::text_file::TextFile;
use super::yaml::Node;

/// The files, as git pathspecs.
const FILES: [&str; 4] = [
":(glob).github/workflows/*.yml",
":(glob).github/workflows/*.yaml",
":(glob).github/actions/**/action.yml",
":(glob).github/actions/**/action.yaml",
];

/// A workflow, or a composite action.
pub(super) struct Workflow {
/// From the repository's root.
pub(super) path: PathBuf,
pub(super) document: Node,
}

impl Workflow {
/// Every workflow and composite action under `root`.
pub(super) fn load_all(root: &Path) -> Result<Vec<Self>, Error> {
TextFile::load_all(root, &FILES)?
.into_iter()
.filter_map(|file| match Node::parse(&file.text) {
Ok(document) => Some(Ok(Self {
document: document?,
path: file.path,
})),
Err(source) => Some(Err(Error::Yaml {
path: file.path,
source,
})),
})
.collect()
}

/// Its jobs, each with its key; none for an action.
pub(super) fn jobs(&self) -> &[(Node, Node)] {
self.document.get("jobs").map_or(&[], Node::entries)
}

/// The steps of every job, or of the action.
pub(super) fn steps(&self) -> impl Iterator<Item = &Node> {
let action = self
.document
.get("runs")
.and_then(|runs| runs.get("steps"))
.map_or(&[][..], Node::items);
self.jobs()
.iter()
.flat_map(|(_, job)| job.get("steps").map_or(&[][..], Node::items))
.chain(action)
}
}
Loading
Loading