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 @@ -51,6 +51,7 @@ A repository adopts the standard in four steps:
- `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.
- `t3-setup`: A recipe `t3.json` runs on worktree creation that runs Cargo, itself or through the recipes it runs, sets `CARGO_BUILD_JOBS` to a default, half the cores, that a set one overrides, and runs the build with `nice -n 10`, both in its own body.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
2 changes: 1 addition & 1 deletion crates/sourceorigin-standard/src/rules/cargo_locked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl TextFile {
/// The words of `line`, each with the byte it starts at, trimmed of
/// quotes and of just's `@` and `-`. A `;`, `|` or `&` ends a word and
/// is a `;` word of its own.
fn tokens(line: &str) -> Vec<(usize, &str)> {
pub(super) fn tokens(line: &str) -> Vec<(usize, &str)> {
let mut words = Vec::new();
let mut start = None;
for (at, c) in line.char_indices().chain([(line.len(), ' ')]) {
Expand Down
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 @@ -28,6 +28,7 @@ mod rustfmt_config;
mod settings;
mod source;
mod t3;
mod t3_setup;
#[cfg(test)]
mod tests;
mod text_file;
Expand Down Expand Up @@ -208,6 +209,11 @@ rules! {
/// `standard.toml`'s `cargo-in-ci` lists it; each listed line is one a
/// `run:` holds.
RecipesOnly = "recipes-only" => recipes_only,
/// A recipe `t3.json` runs on worktree creation that runs Cargo, itself
/// or through the recipes it runs, sets `CARGO_BUILD_JOBS` to a
/// default, half the cores, that a set one overrides, and runs the build
/// with `nice -n 10`, both in its own body.
T3Setup = "t3-setup" => t3_setup,
}

/// Why the rules couldn't be checked.
Expand Down
4 changes: 4 additions & 0 deletions crates/sourceorigin-standard/src/rules/t3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ pub(super) struct T3 {

/// A script T3 Code offers, or runs on an event.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Script {
pub(super) command: String,
/// Whether it runs when a worktree is created.
#[serde(default)]
pub(super) run_on_worktree_create: bool,
}

/// `t3.json` as written.
Expand Down
81 changes: 81 additions & 0 deletions crates/sourceorigin-standard/src/rules/t3_setup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//! `t3-setup`: the build T3 Code starts in each new worktree leaves the
//! machine usable.

use std::collections::BTreeSet;

use super::justfile::Justfile;
use super::t3;
use super::text_file::TextFile;
use super::{Finding, Repository};

/// What the setup recipe's body holds: a default for the jobs, which a set
/// `CARGO_BUILD_JOBS` overrides, and a low priority.
const JOBS: &str = "${CARGO_BUILD_JOBS:-";
const NICE: &str = "nice -n 10";

impl Justfile {
/// Whether `recipe` runs Cargo, in its body, a dependency, or a recipe
/// its body runs with `just`.
fn builds<'a>(&'a self, recipe: &'a str, seen: &mut BTreeSet<&'a str>) -> bool {
if !seen.insert(recipe) {
return false;
}
let Some(found) = self.recipes.get(recipe) else {
return false;
};
let lines: Vec<String> = found.lines().collect();
let words: Vec<&str> = lines
.iter()
.flat_map(|line| TextFile::tokens(line))
.map(|(_, word)| word)
.collect();
let called: Vec<&'a str> = words
.windows(2)
.filter(|pair| pair[0] == "just")
.filter_map(|pair| self.recipes.get_key_value(pair[1]))
.map(|(name, _)| name.as_str())
.collect();
words.contains(&"cargo")
|| self
.dependencies(recipe)
.into_iter()
.chain(called)
.any(|other| self.builds(other, seen))
}
}

impl Repository {
/// Each script `t3.json` runs on worktree creation that builds without
/// the low priority and the default jobs in its recipe's body.
pub(super) fn t3_setup(&self) -> Vec<Finding> {
let (Some(t3), Some(justfile)) = (&self.t3, &self.justfile) else {
return Vec::new();
};
t3.scripts
.iter()
.filter(|script| script.run_on_worktree_create)
.filter_map(|script| {
let words: Vec<&str> = script.command.split_whitespace().collect();
let recipe = match words.as_slice() {
["just", recipe, ..] => *recipe,
_ => return None,
};
if !justfile.builds(recipe, &mut BTreeSet::new()) {
return None;
}
let body: Vec<String> = justfile.recipes.get(recipe)?.lines().collect();
let limited = body.iter().any(|line| line.contains(JOBS))
&& body.iter().any(|line| line.contains(NICE));
(!limited).then(|| Finding {
path: t3::PATH.into(),
line: t3.line(script),
message: format!(
"`just {recipe}` builds on every core at full priority when a worktree \
is created: in its body, `export CARGO_BUILD_JOBS=\"{JOBS}$(( ($(nproc) \
+ 1) / 2 ))}}\"` and run the build with `{NICE}`"
),
})
})
.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 @@ -18,6 +18,7 @@ mod recipes;
mod recipes_only;
mod report;
mod rustfmt_config;
mod t3_setup;
mod toolchain;
mod unsafe_modules;
mod workspace_dependencies;
Expand Down
53 changes: 53 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/t3_setup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use super::{Fixture, INHERITS};
use crate::rules::Rule;

/// A `t3.json` running `just <recipe>` when a worktree is created.
fn t3(recipe: &str) -> String {
format!(
"{{\n \"scripts\": [\n {{\n \"name\": \"Setup\",\n \"command\": \"just \
{recipe}\",\n \"runOnWorktreeCreate\": true\n }}\n ]\n}}\n"
)
}

/// A justfile whose `setup` builds through `just build`, `limited` at low
/// priority on half the cores, and `install` doesn't build.
const JUSTFILE: &str = "\
setup:
just build

limited:
#!/usr/bin/env bash
export CARGO_BUILD_JOBS=\"${CARGO_BUILD_JOBS:-$(( ($(nproc) + 1) / 2 ))}\"
exec nice -n 10 just build

install:
pnpm install

build: generate
cargo build --locked

generate:
";

#[test]
fn a_worktree_build_runs_at_low_priority_on_half_the_cores() {
let fixture = Fixture::new();
fixture
.add_crate("core", INHERITS)
.write("justfile", JUSTFILE);
for (recipe, violations) in [
(
"setup",
vec![
"t3.json:5: `just setup` builds on every core at full priority when a worktree \
is created: in its body, `export CARGO_BUILD_JOBS=\"${CARGO_BUILD_JOBS:-$(( \
($(nproc) + 1) / 2 ))}\"` and run the build with `nice -n 10` (t3-setup)",
],
),
("limited", vec![]),
("install", vec![]),
] {
fixture.write("t3.json", &t3(recipe));
assert_eq!(fixture.violations(Rule::T3Setup), violations, "{recipe}");
}
}