Skip to content

Practices Studies Starship

github-actions[bot] edited this page Aug 16, 2026 · 1 revision

starship/starship (59420 stars)

1. What the project is and measurable scale

Starship is the cross-shell prompt: a single Rust binary that renders a fast, customizable shell prompt for bash, zsh, fish, PowerShell, nushell, elvish, ion, tcsh, xonsh and cmd. Industry adoption follows from three properties: it is one static binary with no runtime, it is configured by one TOML file that behaves identically on every shell and OS, and it is fast enough to run on every keystroke of a prompt redraw. The package metadata states the pitch directly in extras/starship/Cargo.toml:

description = """
The minimal, blazing-fast, and infinitely customizable prompt for any shell! ☄🌌️
"""

Scale measured from the clone:

  • One crate, no workspace: extras/starship/Cargo.toml is the only Cargo manifest in the repository (a find for Cargo.toml returns exactly one file). Version 1.26.0, edition 2024, rust-version = "1.95".
  • 246 Rust source files totaling 51,327 lines of Rust under extras/starship/src.
  • 109 entries in extras/starship/src/modules, one file per prompt module (git status, language versions, cloud contexts, battery, and so on), mirrored by a matching config struct file per module in extras/starship/src/configs.
  • 428 name = entries in extras/starship/Cargo.lock, so roughly 427 transitive dependencies resolve for the full feature set.
  • 1,302 #[test] attributes across the tree, organized into 114 inline mod tests blocks, with 864 call sites of the ModuleRenderer test harness.
  • A 5,314 line configuration reference at extras/starship/docs/config/README.md and a 7,253 line generated JSON schema at extras/starship/.github/config-schema.json.

2. Repository layout

The real top level of extras/starship:

extras/starship/
|-- build.rs                    build-time codegen (shadow-rs, presets, Windows resources)
|-- Cargo.toml                  the single crate manifest
|-- Cargo.lock                  committed lockfile, enforced with --locked in CI
|-- clippy.toml                 disallowed-methods list
|-- deny.toml                   cargo-deny advisories/licenses/bans/sources policy
|-- typos.toml                  spell-check dictionary extensions
|-- .rustfmt.toml               intentionally blank (see section 4)
|-- .dprint.json                formatter for Markdown, TOML, JSON, TypeScript
|-- .codecov.yml                coverage thresholds
|-- .gitattributes              forced LF line endings for shell scripts
|-- crowdin.yml                 translation pipeline config
|-- release-please-config.json  release automation config
|-- starship.exe.manifest       Windows application manifest, embedded by build.rs
|-- CHANGELOG.md                generated by release-please
|-- CONTRIBUTING.md             architecture notes and testing conventions
|-- docs/                       VitePress docs site plus 25+ translated copies
|-- install/                    install.sh, macOS pkg scripts, Windows choco/wix files
|-- media/                      icons and screenshots
|-- src/                        all Rust code
`-- .github/                    workflows, templates, config-schema.json, renovate.json5

Inside src the split is by responsibility, not by layer:

extras/starship/src/
|-- main.rs        clap CLI definition and dispatch
|-- lib.rs         public library surface ("Lib is present to allow for benchmarking")
|-- print.rs       prompt assembly, rayon parallel module rendering, explain/timings
|-- module.rs      Module type, ALL_MODULES registry
|-- segment.rs     styled text segments
|-- config.rs      ModuleConfig trait and TOML deserialization plumbing
|-- configs/       one default-config struct per module (109 files)
|-- modules/       one renderer per module (109 files)
|-- context/       Context: cwd, env, git repo discovery, mocking hooks
|-- formatter/     pest-based format-string engine (spec.pest, string_formatter.rs)
|-- init/          per-shell init scripts embedded with include_str!
|-- test/          ModuleRenderer harness and VCS fixture bundles
`-- utils/         command execution with timeouts, env access, serde helpers

The split works because the project is a plugin architecture without dynamic plugins: every module is a pair of files (renderer in src/modules, config in src/configs) plus one registry entry in ALL_MODULES in extras/starship/src/module.rs. A contributor adding a language module touches a known, small set of files and copies an existing pair. The comment at the top of extras/starship/src/modules/mod.rs encodes the convention:

// While adding out new module add out module to src/module.rs ALL_MODULES const array also.

3. Cargo manifest practices

extras/starship/Cargo.toml is a model of a well-tended single-crate manifest.

Packaging discipline: an explicit include list keeps the crates.io tarball minimal and documents a subtle detail inline:

# Keep `/` in front of `README.md` to exclude localized readmes
include = [
  "src/**/*",
  "/starship.exe.manifest",
  ...
  "docs/public/presets/toml/",
  ".github/config-schema.json",
]

MSRV is declared and its meaning is scoped honestly:

# Note: MSRV is only intended as a hint, and only the latest version is officially supported in starship.
rust-version = "1.95"

Feature flags exist only where a dependency fails to build somewhere, and each optional dependency carries a comment explaining exactly why, with an issue link:

[features]
default = ["battery", "notify"]
battery = ["starship-battery"]
config-schema = ["schemars"]
notify = ["notify-rust"]
# battery is optional (on by default) because the crate doesn't currently build for Termux
# see: https://github.com/svartalf/rust-battery/issues/33
starship-battery = { version = "0.11.1", optional = true }

Dependency hygiene worth copying:

  • Feature-trimming heavy dependencies: gix is pulled with default-features = false and only max-performance-safe, revision, status, sha1, sha256; the comment cites the issue that motivated the restriction. regex drops default features down to perf, std, unicode-perl.
  • Exact pins where semver trust broke: systemstat = "=0.2.7" and the dev-dependency mockall = "=0.15.0".
  • Rationale comments on non-obvious picks: parking_lot is annotated # ... This is for poison-free locks. and os_info carries # update os module config and tests when upgrading os_info.
  • Platform-conditional dependencies: [target.'cfg(windows)'.dependencies.windows] enumerates exactly five Win32 feature gates; [target.'cfg(not(windows))'.dependencies] pulls nix with just feature, fs, user.

Profiles are tuned for a latency-critical binary:

[profile.release]
codegen-units = 1
lto = true
strip = true

[profile.bench]
codegen-units = 16
lto = "thin"
strip = false

Finally there is a minimal [lints] table: [lints.clippy] use_self = "warn". The heavy lint policy lives elsewhere (section 5).

4. Formatting

The most interesting formatting artifact is a file that is deliberately empty. extras/starship/.rustfmt.toml:

# This file intentionally left almost blank
#
# The empty `rustfmt.toml` makes rustfmt use the default configuration,
# overriding any which may be found in the contributor's home or parent
# folders.

This is a defensive trick: rustfmt walks parent directories and the home directory for configuration, so an empty repo-level file pins the project to rustfmt defaults no matter what a contributor has configured globally. CI enforces it with cargo fmt --all -- --check in extras/starship/.github/workflows/workflow.yml.

Non-Rust formatting is delegated to dprint via extras/starship/.dprint.json, which formats Markdown (line width 100), TOML, JSON and the TypeScript of the docs site, excluding the generated CHANGELOG.md and all translated docs directories (docs/??-??/** patterns). The dprint plugins are WASM binaries referenced by release URL, and the Renovate config (section 6) has a custom regex manager to keep those URLs updated.

Shell scripts get their own formatter and linter: the install-script workflow runs shfmt -d install/**/*.sh and shellcheck --severity=warning install/**/*.sh (extras/starship/.github/workflows/install-script.yml). Line endings are pinned at the Git layer in extras/starship/.gitattributes:

/src/init/* text eol=lf
*.sh text eol=lf
/.github/config-schema.json text eol=lf

The init scripts are embedded into the binary with include_str!, so a CRLF checkout on Windows would otherwise corrupt what the binary emits into a user's shell.

5. Linting

Starship's clippy philosophy is the opposite of a broad severity wall: run default clippy at -D warnings on three operating systems, and add a small number of surgical, project-specific bans. The bans live in extras/starship/clippy.toml, each with its reason:

disallowed-methods = [
  # std::process::Command::new may inadvertly run executables from the current working directory
  "std::process::Command::new",
  # Setting environment variables can cause issues with non-rust code
  "std::env::set_var",
  # use `dunce` to avoid UNC/verbatim paths, where possible
  "std::fs::canonicalize",
]

These are real security and correctness policies, not style: on Windows, Command::new("git") can execute git.exe from the current directory, which for a program that runs automatically in every directory a user visits is an attack vector. Both binary roots opt in at the crate level: extras/starship/src/main.rs and extras/starship/src/lib.rs each begin with #![warn(clippy::disallowed_methods)]. The one sanctioned call site is the wrapper itself in extras/starship/src/utils/mod.rs, which first resolves the binary through which::which and then suppresses the lint locally:

    #[allow(clippy::disallowed_methods)]
    let mut cmd = Command::new(full_path);
    cmd.stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .stdin(Stdio::null());

CI runs cargo clippy --workspace --locked -- -D warnings on ubuntu, macOS and windows (extras/starship/.github/workflows/workflow.yml), because a cfg-gated module can lint clean on Linux and fail on Windows. Complementary check infrastructure: typos runs on every PR with a curated exception list in extras/starship/typos.toml (including the honest entry extentions = "extentions" # TODO: should be extensions for a config key that is a frozen public misspelling), and taplo lint validates every preset TOML file against the generated JSON schema (section 6).

6. CI/CD

There are eight workflows in extras/starship/.github/workflows. Every third-party action in every workflow is pinned to a full commit SHA with a trailing version comment, for example uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1. That is supply-chain hardening: tags are mutable, SHAs are not, and the comment keeps the pin human-readable and Renovate-updatable.

workflow.yml (the main gate) runs on push and pull_request with paths-ignore: ["docs/**", "**.md"] and sets a shared env of CARGO_INCREMENTAL: 0, CARGO_NET_RETRY: 10, RUST_BACKTRACE: short, CARGO_BUILD_WARNINGS: deny, RUSTUP_MAX_RETRIES: 10. Jobs:

  • rustfmt: format check on stable.
  • clippy: 3-OS matrix, -D warnings, cached with Swatinem/rust-cache.
  • cargo_check: fast compile gate; the two feature-matrix checks (--no-default-features, --all-features) and the test suite all declare needs: cargo_check so expensive jobs never start on code that does not compile (the file comments this: # First check then run expansive tests).
  • check_if_config_schema_up_to_date: a generated-artifact drift check. It regenerates the schema and fails with an actionable annotation:
      - name: Run | Generate Schema
        run: cargo run --locked --features config-schema -- config-schema > .github/config-schema.json

      - name: Check | Detect Changes
        run: |
          if ! git diff --exit-code .github/config-schema.json; then
            echo "::error file=.github/config-schema.json::config-schema.json is out of date. ..."
            exit 1
          fi
  • test: 3 OS x {stable, nightly} with fail-fast: false, Windows adding RUSTFLAGS: -C target-feature=+crt-static. Tests run under coverage: cargo llvm-cov --all-features --locked --workspace --lcov ... -- --include-ignored, installing Mercurial on macOS and Windows first so the #[ignore]d VCS tests can run. Nightly breakage is tolerated without losing the stable gate via CARGO_BUILD_WARNINGS: ${{ matrix.rust == 'stable' && 'deny' || 'allow' }}. The same job also smoke-builds the Windows MSI with cargo-wix, exercises the Chocolatey packaging script against dummy artifacts, and submits debug binaries to SignPath test signing, all with continue-on-error: true so packaging drift is visible but not blocking. Coverage uploads to Codecov, with thresholds in extras/starship/.codecov.yml (target: auto, threshold: 5% for project and patch, comment: false).

security-audit.yml runs cargo-deny only when **/Cargo.toml or **/Cargo.lock change, splitting checks into a matrix and making the inherently time-dependent one non-blocking:

    # Prevent sudden announcement of a new advisory from failing ci:
    continue-on-error: ${{ matrix.checks == 'advisories' }}

format-workflow.yml is path-filtered to docs and config-like files and runs four jobs: dprint check, taplo lint --schema "file://${GITHUB_WORKSPACE}/.github/config-schema.json" docs/public/presets/toml/*.toml (presets are validated against the schema the code generates, so a preset can never reference a config key that does not exist), a block-crowdin job that fails any PR touching translated docs unless it comes from the translation branch, and a full VitePress build. install-script.yml lints, formats and then actually executes the curl-piped installer on ubuntu and macOS and asserts "$HOME/.test-install/starship" --version works. spell-check.yml runs crate-ci/typos. crowdin-pretranslate.yml is a nightly cron guarded by if: github.repository == 'starship/starship' so forks do not burn failing runs.

Dependency automation is Renovate, configured in extras/starship/.github/renovate.json5 with config:best-practices and security:openssf-scorecard, automerge for minor updates, minimumReleaseAge: '4 days' (a supply-chain cooldown against hijacked releases), grouped update PRs per ecosystem (clap, gix, pest, toml, unicode crates), and three custom regex managers that version-track things Renovate cannot see natively: dprint WASM plugin URLs, cargo install --version pins inside workflows, and the ziglang== pip pin in the release workflow.

7. Testing

All tests are inline unit tests: there is no tests/ directory. Instead the crate ships a purpose-built harness in extras/starship/src/test/mod.rs that makes an inline test read like an end-to-end test. The core is ModuleRenderer, a builder over the real Context:

    #[test]
    fn folder_with_go_file() -> io::Result<()> {
        let dir = tempfile::tempdir()?;
        File::create(dir.path().join("main.go"))?.sync_all()?;

        let actual = ModuleRenderer::new("golang").path(dir.path()).collect();

        let expected = Some(format!("via {}", Color::Cyan.bold().paint("🐹 v1.12.1 ")));
        assert_eq!(expected, actual);
        dir.close()
    }

(from extras/starship/src/modules/golang.rs). Three pieces of infrastructure make this possible:

  1. Mock seams live on the production type, gated by cfg(test). Context in extras/starship/src/context/mod.rs carries pub env: Env<'a> plus #[cfg(test)] pub cmd: HashMap<&'a str, Option<CommandOutput>> and #[cfg(test)] pub root_dir: tempfile::TempDir. Modules never call std::env or spawn processes directly; they go through context.get_env and utils::exec_cmd, and exec_cmd short-circuits into a mock table in tests (extras/starship/src/utils/mod.rs):

     #[cfg(test)]
     if let Some(o) = mock_cmd(&cmd, args) {
         return o;
     }
     internal_exec_cmd(cmd, args, time_limit)

    mock_cmd is a big match of canned outputs ("go version" => ... "go version go1.12.1 linux/amd64\n"), which is why the golang test above renders v1.12.1 without Go installed.

  2. Deterministic VCS fixtures. extras/starship/src/test/fixtures contains git-repo.bundle, git-repo-sha256.bundle and hg-repo.bundle; fixture_repo unbundles them into a TempDir per test. Fixture matrices such as COMMON_GIT_PROVIDERS re-run the same test against classic refs and reftable backends, bare and non-bare. A hard-won flake fix is codified as data in TEST_GIT_CONFIG:

     // Prevent intermittent test failures and ensure that the result of git commands
     // are available during I/O-contentious tests, by having git run `fsync`.
     // This is especially important on Windows.
     ("core.fsync", "all"),
  3. Environment-dependent tests are #[ignore]d (39 of them, mostly Mercurial and Fossil), and CI installs the tools and runs --include-ignored, so local cargo test stays dependency-free while CI covers everything.

Other testing details: the logger is swapped once per process via static LOGGER: Once and writes to /dev/null/nul; the battery module defines #[cfg_attr(test, automock)] pub trait BatteryInfoProvider and injects a mockall mock through the Context field (extras/starship/src/modules/battery.rs); property-level assertions appear as doc-adjacent inline tests such as the grapheme-width test in extras/starship/src/print.rs, which pins emoji-cluster width behavior. Performance is handled as an observable product feature rather than a benchmark suite: the binary records a duration: Duration per module (extras/starship/src/module.rs) and exposes a timings subcommand that prints a per-module latency table (extras/starship/src/print.rs, pub fn timings), and extras/starship/src/lib.rs notes // Lib is present to allow for benchmarking to explain why a binary crate exports a library at all.

8. Error handling and API design

Starship uses neither anyhow nor thiserror (neither appears in extras/starship/Cargo.toml). The design constraint is unusual and drives everything: a prompt must never fail. The result is a three-tier policy:

  • Module tier: everything is Option. A module renderer returns Option<Module>; missing binaries, timeouts and parse failures all become None plus a log line. exec_timeout in extras/starship/src/utils/mod.rs converts every failure mode (spawn error, timeout via the process_control crate's controlled_with_output().time_limit(...).terminate_for_timeout(), non-UTF8 output, nonzero exit) into a logged None, including a user-actionable hint on timeout ("You can set command_timeout in your config to a higher value ...").
  • Config tier: degrade to defaults, loudly. ModuleConfig::load in extras/starship/src/config.rs logs log::warn!("Failed to load config value: {e}") and returns Self::default(); unknown keys produce a warning and a second deserialization pass that tolerates them, so a typo in starship.toml degrades one module instead of blanking the prompt.
  • Library tier: real error enums where callers can act. The format-string engine defines pub enum StringFormatterError { Custom(String), Parse(Box<PestError<Rule>>) } with manual Display, Error and From<String> impls (extras/starship/src/formatter/string_formatter.rs); the pest error is boxed to keep the enum small. Fallible repo discovery is stored as OnceLock<Result<GitRepo, Box<gix::discover::Error>>> on Context, again boxed.

Exit codes are deliberate and documented at the call site in extras/starship/src/main.rs: informational invocations exit 0, argument errors exit 2 with a comment citing clap's convention (// clap exits with status 2 on error), and genuine failures use std::process::exit(1) (configuration editing in extras/starship/src/configure.rs). Panic policy: expect/unwrap only where failure means the process cannot do its job at all (writing the prompt to stdout, initializing the rayon pool), and even stderr writes are shielded: // avoid panicking in case of stderr closing followed by let _ = writeln!(stderr, ...).

API design: the visibility split in extras/starship/src/lib.rs is exact. pub mod for what the binary and tests need (config, configs, context, formatter, print, ...), private mod modules, mod segment, mod utils for internals. Builders appear where construction is combinatorial: ModuleRenderer chains .path().config().env().cmd() in tests, and Properties is a single clap::Parser struct (extras/starship/src/context/mod.rs) that is simultaneously the CLI argument surface (#[clap(short = 's', long = "status")] and friends) and the programmatic construction API, so shell flags and test setup can never drift apart.

9. Deep Rust usage

Ten-plus concrete idioms, each cited:

  1. Lazy per-render caching with OnceLock fields. Context computes directory listings and git discovery at most once per prompt render: dir_contents: OnceLock<Result<DirContents, std::io::Error>> and git_repo: OnceLock<Result<GitRepo, Box<gix::discover::Error>>> (extras/starship/src/context/mod.rs). Modules that need the data pay for it; modules that do not, never trigger it. There are 27 OnceLock uses and 35 LazyLock uses in src overall.

  2. Cross-module shared state through a static parking_lot::Mutex holding an Arc. git_status and git_metrics render in parallel but need the same expensive repo scan, so extras/starship/src/modules/git_status.rs keeps static REPO_STATUS: parking_lot::Mutex<Option<(Arc<RepoStatus>, PathBuf)>> keyed by path, returning Arc::clone so a holder survives cache trashing. The dependency choice is justified in the manifest: parking_lot for poison-free locks.

  3. Data parallelism with rayon, bounded deliberately. Modules render via .par_iter() in extras/starship/src/print.rs, and extras/starship/src/lib.rs caps the pool: available_parallelism().map_or(1, usize::from).min(8), overridable through STARSHIP_NUM_THREADS. A prompt should not oversubscribe a laptop.

  4. Cow<'a, str> as the default string currency of the formatter. The parsed format AST is FormatElement::Text(Cow<'a, str>) (extras/starship/src/formatter/model.rs) and variable values default to Self::Plain(Cow::Borrowed("")) (extras/starship/src/formatter/string_formatter.rs), so literal format text is never copied; only computed values allocate.

  5. Zero-copy config structs borrowing from the TOML document. Every module config is lifetime-parameterized over the deserializer input, for example pub struct RustConfig<'a> { pub format: &'a str, pub symbol: &'a str, ... } with #[serde(default)] (extras/starship/src/configs/rust.rs), which combined with a Default impl gives partial-override semantics without owned strings.

  6. A blanket trait impl to erase serde boilerplate. ModuleConfig<'a, E> gets one implementation for every T: Deserialize<'a> + Default (extras/starship/src/config.rs), which is why 109 config files contain nothing but a struct and its defaults. The same file shows newtype-driven deserialization: VecOr<T> accepts scalar-or-list TOML via an untagged Either<A, B> enum.

  7. Extension traits over AsRef<str> for domain measurement. Terminal width is grapheme-cluster width, not char count, so extras/starship/src/print.rs defines trait UnicodeWidthGraphemes with a blanket impl<T> ... where T: AsRef<str>, backed by the newtype pub struct Grapheme<'a>(pub &'a str), and pins the behavior with an inline test asserting a family emoji has width 2.

  8. Iterator pipelines in place of manual loops. FillSegment::ansi_string fills remaining width by cycling a pattern: .graphemes(true).cycle().scan(0usize, |len, g| { *len += Grapheme(g).width(); if *len <= w { Some(g) } else { None } }) (extras/starship/src/segment.rs). Session ids are rand::rng().sample_iter(rand::distr::Alphanumeric).take(16) in extras/starship/src/main.rs.

  9. A pest PEG grammar as the format-string engine. extras/starship/src/formatter/spec.pest defines variables, escapes, text groups and conditionals as a commented grammar file, compiled by pest_derive; errors surface as Box<PestError<Rule>>. Parsing config syntax with a real grammar instead of regexes keeps escaping rules exact.

  10. Build-time code generation with shadow_rs hooks. extras/starship/build.rs registers gen_presets_hook, which scans docs/public/presets/toml, emits a generated get_preset_content match of include_str! arms, and prints cargo:rerun-if-changed=docs/public/presets/toml. Presets are docs and embedded data from one source of truth; shadow! also feeds CLAP_LONG_VERSION build metadata into --version (extras/starship/src/main.rs).

  11. Contained unsafe with RAII cleanup. The only unsafe in the tree is extras/starship/src/modules/utils/directory_win.rs, wrapping Win32 ACL checks; the raw handle is a newtype whose Drop calls CloseHandle (line 25), so every unsafe resource has a safe owner. Platform splits otherwise happen at the Cargo level ([target.'cfg(windows)'.dependencies]) and via #[cfg(windows)] blocks in extras/starship/build.rs.

  12. Modern std combinators and let-else for terse fallible flows: is_some_and(|p| p.len() == 1 && p[0].is_empty()) while normalizing pipestatus in extras/starship/src/context/mod.rs, is_none_or in the git-status cache check, and let Ok(log_files) = fs::read_dir(log_dir) else { return; } in the log cleanup of extras/starship/src/logger.rs, commented "Avoid noisily handling errors in this cleanup function."

  13. PhantomData to keep an API stable across feature combinations. Context<'a> ends with _marker: PhantomData<&'a ()> documented as /// Avoid issues with unused lifetimes when features are disabled (extras/starship/src/context/mod.rs): with battery off, no field would use 'a, and the type would stop compiling.

10. Documentation practices

The repository treats documentation as a build artifact with its own CI. The VitePress site lives in extras/starship/docs (config at docs/.vitepress/config.mts) and is built on every relevant PR by the vitepress job in extras/starship/.github/workflows/format-workflow.yml, then deployed to Netlify by extras/starship/.github/workflows/publish-docs.yml on workflow_dispatch. Translations are first-class: 25+ locale directories (docs/ja-JP, docs/zh-CN, ...) are machine-managed through Crowdin (extras/starship/crowdin.yml, nightly pretranslation workflow), and the block-crowdin CI job rejects direct edits to translated files so the pipeline is the only writer.

The configuration reference (extras/starship/docs/config/README.md, 5,314 lines) documents every option of every module, and its machine twin, the schemars-generated extras/starship/.github/config-schema.json, is kept honest by the CI drift check and reused to validate presets. Editors get completion for starship.toml from the same schema.

extras/starship/CONTRIBUTING.md (309 lines) is unusually operational: it defines a glossary (module, segment), states the performance philosophy, sketches the architecture starting from main.rs, and then teaches the house testing style with full code samples of context.get_env, context.exec_cmd and ModuleRenderer, so contributors learn the mock seams before writing a module. Issue templates (extras/starship/.github/ISSUE_TEMPLATE/Bug_report.md) push users toward starship bug-report, a subcommand (extras/starship/src/bug_report.rs) that pre-fills a GitHub issue with version, config and environment. The PR template (extras/starship/.github/PULL_REQUEST_TEMPLATE.md) asks for conventional-commit-typed titles (they become the changelog) and includes a per-OS testing checklist. Rustdoc is used pragmatically rather than exhaustively: public seams carry doc comments (the StringFormatter::map contract in extras/starship/src/formatter/string_formatter.rs documents the three-state None / Some(Err) / Some(Ok) protocol), while internal modules rely on precise names.

11. Release and distribution

Versioning and changelog are fully automated around conventional commits. extras/starship/.github/workflows/release.yml runs on every push to main: googleapis/release-please-action (release-type rust) maintains a rolling release PR; merging it bumps Cargo.toml, tags, and regenerates extras/starship/CHANGELOG.md with scope-grouped entries linking commit and PR (* **git:** enable sha256 support (#7531)). Releases are created as drafts (extras/starship/release-please-config.json sets "draft": true) and only published by gh release edit ... --draft=false after all binaries exist, so users never see a half-populated release.

The build matrix covers 13 targets: glibc and musl Linux on x86_64/i686/aarch64/arm, riscv64gc via cargo-zigbuild (with a pinned pip install ziglang==0.16.0), macOS x86_64/aarch64, three Windows MSVC targets with -C target-feature=+crt-static, and a FreeBSD cross build. Windows binaries and MSI installers are signed through SignPath; macOS binaries are signed and notarized in a dedicated job that builds a temporary keychain from secrets, runs xcrun notarytool, and deletes the keychain in an if: always() cleanup step. Every artifact gets an openssl dgst -sha256 checksum file. Publication to crates.io uses OIDC trusted publishing rather than a long-lived token: the cargo_publish job requests permissions: id-token: write and exchanges it via rust-lang/crates-io-auth-action for a short-lived token. Downstream package managers are updated in the same workflow: Homebrew formula bump, winget manifest via wingetcreate, and Chocolatey via a checked-in PowerShell script that CI also smoke-tests on ordinary pushes.

As a CLI, distribution polish is in-product: starship completions <shell> generates completions through clap_complete plus clap_complete_nushell (extras/starship/src/main.rs), starship init <shell> emits the embedded per-shell hook scripts from extras/starship/src/init, starship preset -o file writes any of the 12 bundled presets, and the curl-pipe installer at extras/starship/install/install.sh is linted, formatted and executed in CI before it ever reaches a user.

12. Lessons for quinjet

Quinjet already has the strict-wall side covered (clippy all+pedantic+nursery+cargo plus restrictions, rustfmt, cargo-deny, taplo, typos, coverage floor, miri, mutants). What starship adds is mostly seams, fixtures and automation:

  1. Adopt disallowed-methods in a clippy.toml with reasons per entry. For a Git tool the starship set transfers almost verbatim: ban std::process::Command::new (route every git spawn through one wrapper that resolves the binary with the which crate first), ban std::env::set_var, ban std::fs::canonicalize in favor of dunce::canonicalize for Windows path sanity. Enforce with #![warn(clippy::disallowed_methods)] at the crate root and one #[allow(clippy::disallowed_methods)] inside the wrapper, as in extras/starship/src/utils/mod.rs.

  2. Wrap external git invocations in an exec_timeout built on the process_control crate (controlled_with_output().time_limit(...).terminate_for_timeout().wait()), so a hung hook or credential helper can never freeze the TUI; copy the logged-None degradation contract from extras/starship/src/utils/mod.rs.

  3. Build a ModuleRenderer-style harness: put #[cfg(test)] mock fields (env map, command-output map, temp root dir) directly on quinjet's context/app-state type, make production code read env and spawn processes only through it, and expose a chainable builder in a src/test/mod.rs. This is what lets starship keep 1,302 tests inline with zero test-only production branches beyond the seams.

  4. Ship deterministic repo fixtures as git bundle files (like extras/starship/src/test/fixtures/git-repo.bundle) unbundled into a TempDir per test, run each scenario across a provider matrix (reftable/non-reftable, bare/non-bare as in COMMON_GIT_PROVIDERS), and set core.fsync=all, commit.gpgsign=false and a dummy identity via a shared TEST_GIT_CONFIG table to kill flakes, especially on Windows.

  5. Add a generated-artifact drift check to CI: run cargo run -- <subcommand that emits schema/docs/completions> > checked-in-file then git diff --exit-code checked-in-file with a ::error file=...:: annotation telling the contributor the exact regeneration command (extras/starship/.github/workflows/workflow.yml, check_if_config_schema_up_to_date). Apply it to quinjet's CLI reference docs and, if a config schema exists, to a schemars-generated JSON schema behind an optional config-schema feature (schemars with preserve_order).

  6. Pin every GitHub Action to a full commit SHA with a # vX.Y.Z comment, and add Renovate (extras/starship/.github/renovate.json5) with config:best-practices, minimumReleaseAge: '4 days', grouped crate updates, and weekly action-digest bumps so the pins stay fresh without PR noise.

  7. Split cargo-deny in CI as starship does (extras/starship/.github/workflows/security-audit.yml): a matrix of advisories vs bans licenses sources, with continue-on-error only on the advisories leg so a newly published RUSTSEC advisory cannot redden unrelated PRs, and path-filter the workflow to **/Cargo.toml and **/Cargo.lock.

  8. Add cargo check --locked --no-default-features and --all-features jobs gated by a fast cargo_check via needs:, and run clippy and tests on a 3-OS matrix; a crossterm TUI has enough cfg(windows) surface that Linux-only linting will eventually lie. Include a nightly test leg with warnings demoted (CARGO_BUILD_WARNINGS: ${{ matrix.rust == 'stable' && 'deny' || 'allow' }}).

  9. Automate releases with release-please (googleapis/release-please-action, release-type rust, "draft": true in release-please-config.json), publish binaries for a target matrix with --locked, attach sha256 files, and publish to crates.io through OIDC trusted publishing (permissions: id-token: write plus rust-lang/crates-io-auth-action) instead of a stored token.

  10. Steal the product-level ergonomics: a completions <shell> subcommand via clap_complete (+ clap_complete_nushell), build metadata in --version via shadow-rs in build.rs, a bug-report subcommand that pre-fills an issue with version and environment, and a timings-style self-profiling subcommand that prints per-operation durations, backed by a Duration recorded on each rendered component as in extras/starship/src/module.rs.

  11. Two small hygiene wins: an intentionally empty .rustfmt.toml-style guard is unnecessary for quinjet (it has real rustfmt config, which shields it the same way), but .gitattributes entries forcing eol=lf on any file embedded via include_str! (extras/starship/.gitattributes) and a .codecov.yml with comment: false plus explicit project/patch thresholds are directly copyable.

  12. Profile tuning: mirror starship's release profile (codegen-units = 1, lto = true, strip = true) for the shipped binary; startup latency and binary size matter for a keyboard-first tool exactly as they do for a prompt.

CLI reference

Repository
Changes
Remotes
Branch
Stash
Pull Request
Generated
Graft
Mcp
Project
Remote
Stack
Worktree

Guides

Optimization

Git Internals
Diff
Github
Rendering

Rust practices

Studies
Patterns

Clone this wiki locally