Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Code Conventions

The rules CI enforces, and the ones it cannot.

Clean code

The named standard is Robert C. Martin's Clean Code. The numbers below are the limits; the principles above them decide the cases the numbers do not cover.

  • Single Responsibility — one reason to change, per function and per module.
  • DRY — one authoritative representation per piece of knowledge. Duplication's real cost is divergence, not duplicated bytes.
  • KISS — the simplest thing that satisfies the requirement.
  • YAGNI — build the requirement, not the generalisation you imagine needing.
  • Boy Scout Rule — leave a file cleaner than you found it, which includes deleting its baseline #![allow(...)] when you can bring the module into line.

Functions

Target 20-30 lines, and 60 is the limit — clippy::too_many_lines is the lint that expresses it. Martin's own guidance is 20, which is the target rather than the threshold: match arms, builder chains and explicit error mapping cost vertical space in Rust that a Java method hides.

A function does one thing. The test is mechanical: if you can extract a function whose name is not a restatement of its own body, the original was doing more than one thing. The related rule is one level of abstraction per function — high-level orchestration and string-munging do not belong in the same body.

Nesting depth 2 is the target and 5 is the limit (clippy::excessive_nesting); clippy::cognitive_complexity catches the branchy functions that stay shallow. Three or four arguments at most — past that, introduce a params struct:

// Not this.
fn compile(a: &Path, b: &Path, c: &[Dep], d: bool, e: bool, f: &Profile) { }

// This.
fn compile(unit: &CompileUnit, profile: &Profile) { }

Keep Command-Query Separation: a function does something or answers something, not both. If it must both mutate through &mut and return data, the name says so.

Modules

One responsibility per module. A module that splits cleanly into groups of functions touching disjoint data is two modules wearing a trenchcoat, and the sign of it is usually a file over ~400 production lines.

Names carry no type or scope prefix. kargo_ops::ops_build stutters, and clippy::module_name_repetitions says so. One word per concept — fetch or download or get for a given act, not all three.

The corollary is that the module path is part of the name: the type is config::Global, not config::GlobalConfig, and the function is download::text, not download::download_text. A name that only reads with the module in front of it should be called with the module in front of it — config::Global::load() rather than an imported bare Global. The lint sees only public modules, so it follows the public surface rather than the file tree, and the handful of items where the repeated word is the one doing the work carry an #[expect] saying which word and why.

Comments

A comment explaining what the code does is a defect in the code. Rename the variable, extract the function, or give the magic number a name instead; reaching for the comment means expression lost. Martin's restatement is the operative version: don't comment bad code, rewrite it.

A comment earns its place when it carries what the code cannot — intent, a consequence worth warning about, a non-local invariant, a subtle failure mode, a coupling between two places that must stay in sync, legal text, a TODO. A /// on a public item is documentation, not a failure of expression; see Documentation comments. The rule above is aimed at // inside a function body.

Banners are banned. No // -----, no // -- fn_name ----, no // Public types. A file that needs internal signposting needs splitting, and the banner marks where to split it.

Coverage

Coverage is part of the standard, not only a CI job: new code is expected to be covered as you write it. The thresholds, and how to reproduce the measurement locally, are in Testing.

Where Clean Code and Rust part ways

Clean Code is a Java book, and some of it does not transfer. Do not "clean up" into the Java it was arguing against:

  • Result + ? with thiserror/miette stays. The exception chapters are moot here; see Errors.
  • Option stays. "Don't return null" is solved at the type level.
  • Read "class" as "module" or "type", and ignore the inheritance advice entirely.

Errors

thiserror for error types in library crates, miette for user-facing reporting with context and help text.

return Err(KargoError::Manifest {
    message: format!("package.version '{v}' is not valid semver"),
}
.into());

No .unwrap() or .expect() in library code — anything outside kargo-cli. Use ?, or return a Result. In kargo-cli, .expect() is acceptable only in main() setup.

This is not pedantry. A panic in a build tool prints a Rust backtrace at someone debugging their Kotlin project, which tells them nothing and looks like a crash rather than a message.

Add context when propagating:

let content = std::fs::read_to_string(path)
    .map_err(|e| KargoError::Manifest {
        message: format!("Failed to read {}: {e}", path.display()),
    })?;

An error message should name the file, the key, or the coordinate at fault. "Invalid manifest" is not an error message.

Logging

tracing macros only — info!, debug!, warn!, error!.

Never println! or eprintln! for diagnostics in library code. println! is correct in kargo-cli command handlers, where the point is user-facing output.

tracing::debug!("fingerprint miss for unit {}", unit.name);
tracing::warn!("Failed to remove {}: {e}", path.display());
RUST_LOG=debug cargo run -- build

API design

// Good
pub fn load(path: &Path, name: &str) -> miette::Result<Manifest>

// Avoid: forces the caller to allocate
pub fn load(path: PathBuf, name: String) -> miette::Result<Manifest>
  • &str over String, &Path over PathBuf, when ownership is not needed.
  • impl Into<String> or impl AsRef<Path> for builder-style APIs.
  • Return owned types — String, PathBuf, Vec.

Types

BTreeMap, not HashMap, wherever ordering is observable: manifests, lockfiles, anything serialized. This is what makes Kargo.lock byte-stable across runs and kargo add produce a one-line diff.

Derive Debug, Clone, Serialize, Deserialize on public data types.

#[serde(rename_all = "kebab-case")] for TOML field names, or per-field #[serde(rename = "…")]:

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default, rename = "java-target")]
    pub java_target: Option<String>,
}

Use #[serde(default)] liberally. Every optional manifest section should be omittable.

Dependencies

All external versions live in the workspace [workspace.dependencies]:

# Cargo.toml (workspace root)
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
# crates/kargo-core/Cargo.toml
[dependencies]
serde.workspace = true

Never pin a version in an individual crate manifest. One version per dependency across the workspace, or Cargo resolves two and the binary grows.

A new dependency is worth justifying in the PR description. Every one is a supply-chain surface, a compile-time cost, and a potential MSRV bump — a dependency bump can raise the Rust floor and make the workspace refuse to build, in which case rust-version and the README prerequisites move together.

Documentation comments

Public items get a doc comment, and only public items: a /// on a private helper is a reason that belongs either on the pub caller or in a // at the line it explains. Modules get a //! header saying what the module is for. missing_docs is a hard gate, so the public half is checked rather than asked for; the modules that still carry a #![allow(missing_docs)] baseline are the ones waiting on #131. missing_docs_in_private_items is deliberately off — it is the inverse of this rule.

Three sections are checked too, each exactly where it applies: missing_errors_doc asks a documented pub fn returning Result for # Errors, missing_panics_doc asks one that can panic for # Panics, and missing_safety_doc asks an unsafe fn for # Safety. Say what the caller can act on — which variant, and what it means — rather than restating the signature.

//! Target-agnostic compiler dispatch.
//!
//! Adding a new target backend requires implementing `TargetCompiler` and
//! registering it here — zero changes to the build orchestration layer.

Explain why where the code cannot. The existing defaults.rs is the model: each constant carries the reasoning for its value, so the next person bumping it knows what the constraint actually was.

Write the reason, do not cite it. A comment ending in a bare issue reference — (kargo#198) — sends a reader with the code in front of them outside the repository to read a closed issue restating the comment they came from, and nothing can check that the number still means anything. The history already keeps what the number was for: the commit that added the comment names the issue, so git log -S and git blame answer "why is this here" with the discussion rather than a link to it. scripts/check-issue-references.sh enforces this from the Conventions workflow, over crates/**/*.rs only — commit messages, pull request bodies and CHANGELOG.md are where an issue reference belongs.

Formatting and lint

cargo fmt --all
cargo clippy --workspace --all-targets -- -D warnings

Both are hard CI gates, and the hooks in .githooks/ run them on commit.

rustfmt.toml pins only what the defaults already do, plus newline_style = "Unix". That one is paired with *.rs text eol=lf in .gitattributes: without the git half, a checkout under the Windows default core.autocrlf=true yields CRLF files that cargo fmt --check then rejects wholesale. imports_granularity and group_imports are deliberately absent — they are nightly-only, and stable rustfmt ignores them with a warning, so pinning them would be configuration that does nothing.

The lints are in [workspace.lints] in the root Cargo.toml, with their thresholds in clippy.toml. File length has no lint — clippy has never shipped one — so scripts/check-file-length.sh enforces it from the Conventions workflow.

Silencing a clippy lint needs a reason, and the reason has to be about this code rather than about the backlog:

#[allow(clippy::too_many_arguments)] // mirrors the CLI flag surface

An #[allow] carrying a #131 baseline comment is the exception: those are not reviewed exceptions but a record of what was already over the limit when the gates landed, and each one is deleted by the refactor that brings its item into line.

Commit messages

Conventional Commits:

<type>(<scope>): <description>

[optional body]

Types: feat, fix, refactor, docs, test, chore, perf. There is no ci or build: chore covers build configuration, dependencies and CI.

Scopes are crate names minus the kargo- prefix: cli, core, ops, maven, resolver, compiler, plugin, lint, toolchain, util. Omit the scope for workspace-wide changes. Dependabot adds two of its own, deps and deps-dev, configured in .github/dependabot.yml.

feat(core): add flavor and variant types to manifest parsing
fix(maven): handle missing checksum in POM metadata
refactor(resolver): extract conflict resolution into its own module
docs: restructure the book around task-oriented guides
chore: update workspace dependencies

Write the subject in the imperative mood and keep it under about 72 characters. The body is where "why" belongs.

How it is enforced

scripts/check-conventional-subject.sh is the one implementation of the rule above. It reads the scope list out of [workspace].members, so adding a crate does not also mean editing the checker. Two things call it:

ChecksWhen
.githooks/commit-msgthe message you are writinggit commit
.github/workflows/conventions.ymlthe pull request titleopened, edited, pushed to

The pull request title is the one that matters. Pull requests here are squash-merged, so the title — not your local commit subjects — becomes the commit that lands on main, and that is what the changelog is generated from. A title that fails the check can be fixed in place; editing it re-runs the check without needing an empty push.

Run it yourself on anything:

scripts/check-conventional-subject.sh --subject "feat(core): add flavors"

Revert "..." titles pass as-is, since GitHub quotes a subject that already passed once.

Next