Repository navigation
Practices Studies Starship
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
findforCargo.tomlreturns exactly one file). Version1.26.0, edition2024,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 inlinemod testsblocks, with 864 call sites of theModuleRenderertest 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.
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.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:
gixis pulled withdefault-features = falseand onlymax-performance-safe,revision,status,sha1,sha256; the comment cites the issue that motivated the restriction.regexdrops default features down toperf,std,unicode-perl. - Exact pins where semver trust broke:
systemstat = "=0.2.7"and the dev-dependencymockall = "=0.15.0". - Rationale comments on non-obvious picks:
parking_lotis annotated# ... This is for poison-free locks.andos_infocarries# 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]pullsnixwith justfeature,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 = falseFinally there is a minimal [lints] table: [lints.clippy] use_self = "warn". The heavy
lint policy lives elsewhere (section 5).
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.
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).
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 withSwatinem/rust-cache. -
cargo_check: fast compile gate; the two feature-matrix checks (--no-default-features,--all-features) and the test suite all declareneeds: cargo_checkso 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} withfail-fast: false, Windows addingRUSTFLAGS: -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 viaCARGO_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 withcontinue-on-error: trueso 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.
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:
-
Mock seams live on the production type, gated by
cfg(test).Contextin extras/starship/src/context/mod.rs carriespub env: Env<'a>plus#[cfg(test)] pub cmd: HashMap<&'a str, Option<CommandOutput>>and#[cfg(test)] pub root_dir: tempfile::TempDir. Modules never callstd::envor spawn processes directly; they go throughcontext.get_envandutils::exec_cmd, andexec_cmdshort-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_cmdis a big match of canned outputs ("go version" => ... "go version go1.12.1 linux/amd64\n"), which is why the golang test above rendersv1.12.1without Go installed. -
Deterministic VCS fixtures. extras/starship/src/test/fixtures contains
git-repo.bundle,git-repo-sha256.bundleandhg-repo.bundle;fixture_repounbundles them into aTempDirper test. Fixture matrices such asCOMMON_GIT_PROVIDERSre-run the same test against classic refs and reftable backends, bare and non-bare. A hard-won flake fix is codified as data inTEST_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"),
-
Environment-dependent tests are
#[ignore]d (39 of them, mostly Mercurial and Fossil), and CI installs the tools and runs--include-ignored, so localcargo teststays 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.
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 returnsOption<Module>; missing binaries, timeouts and parse failures all becomeNoneplus a log line.exec_timeoutin extras/starship/src/utils/mod.rs converts every failure mode (spawn error, timeout via theprocess_controlcrate'scontrolled_with_output().time_limit(...).terminate_for_timeout(), non-UTF8 output, nonzero exit) into a loggedNone, 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::loadin extras/starship/src/config.rs logslog::warn!("Failed to load config value: {e}")and returnsSelf::default(); unknown keys produce a warning and a second deserialization pass that tolerates them, so a typo instarship.tomldegrades 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 manualDisplay,ErrorandFrom<String>impls (extras/starship/src/formatter/string_formatter.rs); the pest error is boxed to keep the enum small. Fallible repo discovery is stored asOnceLock<Result<GitRepo, Box<gix::discover::Error>>>onContext, 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.
Ten-plus concrete idioms, each cited:
-
Lazy per-render caching with
OnceLockfields.Contextcomputes directory listings and git discovery at most once per prompt render:dir_contents: OnceLock<Result<DirContents, std::io::Error>>andgit_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 27OnceLockuses and 35LazyLockuses in src overall. -
Cross-module shared state through a static
parking_lot::Mutexholding anArc.git_statusandgit_metricsrender in parallel but need the same expensive repo scan, so extras/starship/src/modules/git_status.rs keepsstatic REPO_STATUS: parking_lot::Mutex<Option<(Arc<RepoStatus>, PathBuf)>>keyed by path, returningArc::cloneso a holder survives cache trashing. The dependency choice is justified in the manifest: parking_lot for poison-free locks. -
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 throughSTARSHIP_NUM_THREADS. A prompt should not oversubscribe a laptop. -
Cow<'a, str>as the default string currency of the formatter. The parsed format AST isFormatElement::Text(Cow<'a, str>)(extras/starship/src/formatter/model.rs) and variable values default toSelf::Plain(Cow::Borrowed(""))(extras/starship/src/formatter/string_formatter.rs), so literal format text is never copied; only computed values allocate. -
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 aDefaultimpl gives partial-override semantics without owned strings. -
A blanket trait impl to erase serde boilerplate.
ModuleConfig<'a, E>gets one implementation for everyT: 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 untaggedEither<A, B>enum. -
Extension traits over
AsRef<str>for domain measurement. Terminal width is grapheme-cluster width, not char count, so extras/starship/src/print.rs definestrait UnicodeWidthGraphemeswith a blanketimpl<T> ... where T: AsRef<str>, backed by the newtypepub struct Grapheme<'a>(pub &'a str), and pins the behavior with an inline test asserting a family emoji has width 2. -
Iterator pipelines in place of manual loops.
FillSegment::ansi_stringfills 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 arerand::rng().sample_iter(rand::distr::Alphanumeric).take(16)in extras/starship/src/main.rs. -
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 asBox<PestError<Rule>>. Parsing config syntax with a real grammar instead of regexes keeps escaping rules exact. -
Build-time code generation with
shadow_rshooks. extras/starship/build.rs registersgen_presets_hook, which scans docs/public/presets/toml, emits a generatedget_preset_contentmatch ofinclude_str!arms, and printscargo:rerun-if-changed=docs/public/presets/toml. Presets are docs and embedded data from one source of truth;shadow!also feedsCLAP_LONG_VERSIONbuild metadata into--version(extras/starship/src/main.rs). -
Contained unsafe with RAII cleanup. The only
unsafein the tree is extras/starship/src/modules/utils/directory_win.rs, wrapping Win32 ACL checks; the raw handle is a newtype whoseDropcallsCloseHandle(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. -
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_orin the git-status cache check, andlet 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." -
PhantomDatato 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): withbatteryoff, no field would use'a, and the type would stop compiling.
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.
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.
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:
-
Adopt
disallowed-methodsin a clippy.toml with reasons per entry. For a Git tool the starship set transfers almost verbatim: banstd::process::Command::new(route every git spawn through one wrapper that resolves the binary with thewhichcrate first), banstd::env::set_var, banstd::fs::canonicalizein favor ofdunce::canonicalizefor 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. -
Wrap external git invocations in an
exec_timeoutbuilt on theprocess_controlcrate (controlled_with_output().time_limit(...).terminate_for_timeout().wait()), so a hung hook or credential helper can never freeze the TUI; copy the logged-Nonedegradation contract from extras/starship/src/utils/mod.rs. -
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 asrc/test/mod.rs. This is what lets starship keep 1,302 tests inline with zero test-only production branches beyond the seams. -
Ship deterministic repo fixtures as
git bundlefiles (like extras/starship/src/test/fixtures/git-repo.bundle) unbundled into aTempDirper test, run each scenario across a provider matrix (reftable/non-reftable, bare/non-bare as inCOMMON_GIT_PROVIDERS), and setcore.fsync=all,commit.gpgsign=falseand a dummy identity via a sharedTEST_GIT_CONFIGtable to kill flakes, especially on Windows. -
Add a generated-artifact drift check to CI: run
cargo run -- <subcommand that emits schema/docs/completions> > checked-in-filethengit diff --exit-code checked-in-filewith 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 optionalconfig-schemafeature (schemarswithpreserve_order). -
Pin every GitHub Action to a full commit SHA with a
# vX.Y.Zcomment, and add Renovate (extras/starship/.github/renovate.json5) withconfig:best-practices,minimumReleaseAge: '4 days', grouped crate updates, and weekly action-digest bumps so the pins stay fresh without PR noise. -
Split cargo-deny in CI as starship does (extras/starship/.github/workflows/security-audit.yml): a matrix of
advisoriesvsbans licenses sources, withcontinue-on-erroronly on the advisories leg so a newly published RUSTSEC advisory cannot redden unrelated PRs, and path-filter the workflow to**/Cargo.tomland**/Cargo.lock. -
Add
cargo check --locked --no-default-featuresand--all-featuresjobs gated by a fastcargo_checkvianeeds:, and run clippy and tests on a 3-OS matrix; a crossterm TUI has enoughcfg(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' }}). -
Automate releases with release-please (
googleapis/release-please-action, release-typerust,"draft": truein release-please-config.json), publish binaries for a target matrix with--locked, attachsha256files, and publish to crates.io through OIDC trusted publishing (permissions: id-token: writeplusrust-lang/crates-io-auth-action) instead of a stored token. -
Steal the product-level ergonomics: a
completions <shell>subcommand viaclap_complete(+clap_complete_nushell), build metadata in--versionviashadow-rsin build.rs, abug-reportsubcommand that pre-fills an issue with version and environment, and atimings-style self-profiling subcommand that prints per-operation durations, backed by aDurationrecorded on each rendered component as in extras/starship/src/module.rs. -
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.gitattributesentries forcingeol=lfon any file embedded viainclude_str!(extras/starship/.gitattributes) and a.codecov.ymlwithcomment: falseplus explicit project/patch thresholds are directly copyable. -
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.
Generated from docs/, edit the docs in the repo, not the wiki.
CLI reference
Pull Request
- View
- Commits
- Files
- Diff
- Conversation
- Checks
- Logs
- Open
- Merge
- Admin Merge
- Auto Merge
- Disable Auto Merge
- Dequeue
- Ready
- Draft
- Review
- Reviews
- Comment
- Edit Last Comment
- Delete Last Comment
- Edit
- Update Branch
- Lock
- Unlock
- Subscribe
- Unsubscribe
- Allow Maintainer Edits
- Disallow Maintainer Edits
- Revert
- Close
- Reopen
Guides
Optimization
Rust practices