Repository navigation
Practices Rust Dump
The whole practices reference bound into one file, for reading straight through or searching in one place. Every part is also its own page: start from Rust Practices for the navigable version.
- Rust Practices
- Studies
- rustdesk/rustdesk (120919 stars)
- tauri-apps/tauri (110245 stars)
- denoland/deno (108251 stars)
- astral-sh/uv (88771 stars)
- zed-industries/zed (88670 stars)
- BurntSushi/ripgrep (67319 stars)
- alacritty/alacritty (65390 stars)
- sharkdp/bat (60188 stars)
- starship/starship (59420 stars)
- meilisearch/meilisearch (58979 stars)
- astral-sh/ruff (49222 stars)
- bevyengine/bevy (47648 stars)
- helix-editor/helix (45833 stars)
- sharkdp/fd (44095 stars)
- nushell/nushell (40272 stars)
- tokio-rs/tokio (32930 stars)
- gitui-org/gitui (22396 stars)
- clap-rs/clap (16634 stars)
- Patterns
- Formatting and Style Across the Rust Ecosystem
- Lints and Static Analysis
- CI/CD Patterns
- Project and Workspace Structure
- Testing Strategies
- Error Handling and API Design
- Deep Rust Language Idioms
- Dependencies, Releases, and Distribution
- Documentation Practices
- Quinjet Gap Analysis
How the most widely used Rust codebases are engineered, distilled from a direct study of eighteen repositories chosen by GitHub star count, and what that corpus implies for Quinjet itself.
Each repository was cloned and read directly: manifests, formatting and lint
configuration, CI pipelines, test suites, source idioms, documentation, and
release machinery. Paths cited as extras/<repo>/<file> refer to those local
clones, which are ignored by Git; the same file exists at the same path in the
upstream repository.
-
Studies: one chapter per repository, eighteen in all.
-
Patterns: nine cross-cutting syntheses of what the corpus agrees on, where it splits, and why.
-
Gap Analysis: Quinjet audited against everything the study found, with completed recommendations and remaining gaps tracked.
-
Rust Dump: the whole reference bound into one file for reading straight through or searching in one place.
| Repository | Stars | Study |
|---|---|---|
| rustdesk/rustdesk | 120,919 | rustdesk |
| tauri-apps/tauri | 110,245 | tauri |
| denoland/deno | 108,251 | deno |
| astral-sh/uv | 88,771 | uv |
| zed-industries/zed | 88,670 | zed |
| BurntSushi/ripgrep | 67,319 | ripgrep |
| alacritty/alacritty | 65,390 | alacritty |
| sharkdp/bat | 60,188 | bat |
| starship/starship | 59,420 | starship |
| meilisearch/meilisearch | 58,979 | meilisearch |
| astral-sh/ruff | 49,222 | ruff |
| bevyengine/bevy | 47,648 | bevy |
| helix-editor/helix | 45,833 | helix |
| sharkdp/fd | 44,095 | fd |
| nushell/nushell | 40,272 | nushell |
| tokio-rs/tokio | 32,930 | tokio |
| gitui-org/gitui | 22,396 | gitui |
| clap-rs/clap | 16,634 | clap |
Star counts were recorded in August 2026.
Start with the patterns if you want the conclusions: each one ends with a checklist a new Rust project can apply directly. Reach into a study when you want the full context behind a citation, and read the gap analysis to see the corpus turned into a concrete status and prioritized plan for this repository.
One chapter per repository, ordered by GitHub star count. Every chapter follows the same shape: what the project is and how big it really is, repository layout, manifest practices, formatting, linting, CI, testing, error handling, deep language idioms with cited examples, documentation, release machinery, and a closing list of lessons for Quinjet.
-
rustdesk: a remote desktop application, and the corpus's largest cross-platform release matrix.
-
tauri: a desktop and mobile app framework, and the reference for workspace-wide manifest inheritance and covenant-level CI.
-
deno: a JavaScript and TypeScript runtime whose CI is generated from a typed script.
-
uv: a Python package manager, and the strongest example of snapshot-first CLI testing.
-
zed: a collaborative code editor with the largest workspace in the corpus.
-
ripgrep: a regex search tool, hand-rolled release engineering, and a masterclass in performance-first crate layering.
-
alacritty: a GPU terminal emulator with a deliberately small dependency and CI footprint.
-
bat: a cat clone whose CICD workflow shows MSRV discipline and binary packaging done thoroughly.
-
starship: a shell prompt with fully automated conventional-commit releases.
-
meilisearch: a search engine, merge-queue CI, and declarative task orchestration.
-
ruff: a Python linter and formatter, and the corpus's most disciplined clippy configuration.
-
bevy: a game engine whose lint suppression discipline and example-driven docs stand out.
-
helix: a modal editor with a clean three-crate seam between core, view, and terminal.
-
fd: a find alternative, small enough to read whole, complete enough to copy from.
-
nushell: a structured-data shell, and the reference for panic hooks and terminal restoration.
-
tokio: the async runtime, and the reference for loom, miri, and public API discipline.
-
gitui: a terminal Git client, the closest neighbor to Quinjet in the corpus.
-
clap: the argument parser Quinjet already uses, studied at the source.
RustDesk is an open-source remote desktop application: a self-hostable alternative to TeamViewer and AnyDesk. The performance-critical core (screen capture, video encoding, input injection, clipboard sync, networking, IPC) is Rust; the desktop and mobile UI is Flutter, with a legacy Sciter UI kept as a fallback for 32-bit Windows. Industry adopts it because it ships on every major platform from one codebase, because the rendezvous and relay servers can be self-hosted for privacy, and because the capture and codec pipeline is genuinely fast.
Measured from the clone at extras/rustdesk:
- 242 Rust source files totaling about 149,000 lines of Rust (the
libs/hbb_commonsubmodule, declared in extras/rustdesk/.gitmodules, is fetched separately and adds more on top of this). - 9
Cargo.tomlmanifests: the root package pluslibs/scrap,libs/enigo,libs/clipboard,libs/virtual_display(and its nesteddylib),libs/portable,libs/remote_printer, andlibs/libxdo-sys-stub. - The root workspace lists 8 members and excludes one directory (extras/rustdesk/Cargo.toml):
[workspace]
members = ["libs/scrap", "libs/hbb_common", "libs/enigo", "libs/clipboard", "libs/virtual_display", "libs/virtual_display/dylib", "libs/portable", "libs/remote_printer"]
exclude = ["vdi/host"]- Version 1.4.9,
rust-version = "1.75", edition 2021 (extras/rustdesk/Cargo.toml). - 52 translation modules under extras/rustdesk/src/lang.
- The largest files show where the complexity lives:
src/server/connection.rs(7,701 lines),src/platform/windows.rs(4,747),src/client.rs(4,443),src/common.rs(3,101),src/flutter_ffi.rs(3,003). - 3,524 lines of GitHub Actions YAML across 11 workflow files under extras/rustdesk/.github/workflows.
Top-level tree (from ls of extras/rustdesk, packaging noise trimmed):
extras/rustdesk/
|-- Cargo.toml root package + workspace definition
|-- Cargo.lock committed lockfile
|-- build.rs native code compilation, version generation
|-- build.py 1,164-line packaging driver (deb/rpm/msi/dmg/apk)
|-- vcpkg.json C/C++ dependency manifest (aom, libvpx, opus, ffmpeg, ...)
|-- Dockerfile reproducible Linux build container
|-- src/ the application: client, server, ui glue, platform code
| |-- server/ capture/input/clipboard/terminal services
| |-- client/ connection and io loop
| |-- platform/ windows.rs, linux.rs, macos.rs, delegate .cc/.mm files
| |-- lang/ 52 translation tables as Rust modules
| `-- ipc/ inter-process channel handlers
|-- libs/ reusable capability crates
| |-- hbb_common (git submodule) protocol, config, tokio re-exports
| |-- scrap/ screen capture + codecs, per-backend modules
| |-- enigo/ keyboard/mouse simulation (forked library)
| |-- clipboard/ file-copy-paste clipboard engine
| |-- virtual_display/ dlopen wrapper over a driver dylib
| |-- portable/ self-extracting Windows packer binary
| |-- remote_printer/ Windows printer driver integration
| `-- libxdo-sys-stub/ local [patch.crates-io] stub crate
|-- flutter/ the Flutter UI project (Dart)
|-- res/ packaging: DEBIAN/, msi/ (WiX), rpm specs, PKGBUILD,
| desktop files, icons, bump.sh, CI helper scripts
|-- appimage/ flatpak/ fastlane/ per-channel packaging recipes
|-- examples/ ipc.rs manual harness
`-- docs/ README/CONTRIBUTING/SECURITY in ~30 languages
The split works because each libs/ crate encapsulates one capability behind a small API, while src/ owns orchestration and platform policy. scrap is a fork of an upstream crate that kept its own identity (extras/rustdesk/libs/scrap/Cargo.toml still says description = "Screen capture made easy."), which keeps capture testable through its own examples/ harnesses without booting the whole application. Shared protocol types live in the hbb_common submodule so the separate server repository can reuse them.
The root manifest (extras/rustdesk/Cargo.toml) predates workspace.package inheritance and instead uses a classic root-package-plus-members layout. Its notable practices:
One package, three crate types, three binaries. The library is compiled for FFI consumption by Flutter:
[lib]
name = "librustdesk"
crate-type = ["cdylib", "staticlib", "rlib"]plus [[bin]] entries for naming (license-name generator, extras/rustdesk/src/naming.rs) and service, with default-run = "rustdesk" so cargo run stays unambiguous.
Feature flags model real product variants. Audio resampling is selectable (use_samplerate, use_rubato, use_dasp with default = ["use_dasp"]), codecs are gated (hwcodec, vram, mediacodec), and the UI toolkit itself is a feature (flutter = ["flutter_rust_bridge"]). Optional dependencies use the dep: syntax so features do not leak implicit feature names:
unix-file-copy-paste = [
"dep:x11-clipboard",
"dep:x11rb",
"dep:percent-encoding",
"dep:once_cell",
"clipboard/unix-file-copy-paste",
]Features that are additive risk get their own gate: drm-wake = ["drm"] exists purely so the input-injecting display wake can be compiled out while keeping DRM capture, and the manifest documents why in place (extras/rustdesk/Cargo.toml).
Target-specific dependency tables carry the platform matrix. There are separate [target.'cfg(...)'.dependencies] sections for Windows, macOS, Linux, Android, combinations like cfg(any(target_os = "macos", target_os = "linux")), and negations like cfg(not(target_os = "linux")) (used to drop cpal on Linux, with a link to the discussion explaining why). The Windows section enumerates 14 winapi features and 18 windows crate features explicitly rather than enabling umbrella features.
Forks are centralized under one GitHub org. Every patched dependency points at github.com/rustdesk-org/... (rdev, cpal, arboard, magnum-opus, tao, pam, evdev, and more), which makes the fork surface auditable at a glance.
[patch.crates-io] swaps in a local stub crate:
[patch.crates-io]
libxdo-sys = { path = "libs/libxdo-sys-stub" }so Wayland-only systems without libxdo can still build and run (extras/rustdesk/Cargo.toml).
Profiles are tuned for shipping:
[profile.release]
lto = true
codegen-units = 1
panic = 'abort'
strip = true
rpath = true
[profile.dev]
debug = 1with a citation of the min-sized-rust guide in the manifest comment. debug = 1 in dev keeps line tables without full debuginfo, a deliberate compile-time and disk saving.
Build-time metadata sections configure the Windows resource block ([package.metadata.winres]) and the macOS bundle ([package.metadata.bundle] with osx_minimum_system_version = "10.14").
.cargo/config carries linker policy (extras/rustdesk/.cargo/config): static CRT on all three Windows MSVC targets, a macOS -sectcreate __CGPreLoginApp link arg so the binary can run at the login screen, and git-fetch-with-cli = true for the many git dependencies.
The repository uses default rustfmt for the application; the only rustfmt configuration on disk is one file, extras/rustdesk/libs/enigo/rustfmt.toml, whose entire content is:
wrap_comments = trueThat single setting makes rustfmt rewrap the long //! prose documentation in that crate to the line limit; the rest of the codebase accepts rustfmt defaults (4-space indent, 100-column max_width, edition-aware imports). There is no .editorconfig. Line-ending policy is delegated to git via extras/rustdesk/.gitattributes:
* text=auto
A cargo fmt -- --check CI job exists in extras/rustdesk/.github/workflows/ci.yml but is commented out (lines 28-39), so formatting is enforced socially rather than mechanically. Non-Rust formatting: the Flutter tree relies on the Dart analyzer/formatter configured by extras/rustdesk/flutter/analysis_options.yaml, and CI installs the rustfmt component wherever flutter_rust_bridge_codegen runs, because the bridge generator formats its emitted Rust (extras/rustdesk/.github/workflows/bridge.yml passes components: "rustfmt").
There are no [lints] tables and no clippy.toml anywhere in the repository. The linting posture is the opposite of a strict wall, and it is instructive to see how a mature FFI-heavy project manages that honestly:
- Crate-level
#![allow]headers are placed exactly where raw bindings make the default lints wrong, for example extras/rustdesk/libs/scrap/src/common/convert.rs:
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(improper_ctypes)]
#![allow(dead_code)]- Item-level
#[allow(...)]appears 65 times undersrc/, always local to the offending item (for example#[allow(non_snake_case)]ontest_RustDesk_intervalin extras/rustdesk/src/common.rs). - A minimum-supported-rust-version clippy job was written and then commented out in extras/rustdesk/.github/workflows/ci.yml (lines 41-66); its retained flags (
--locked --all-targets --all-features -- --allow clippy::unknown_clippy_lints) show the intended shape: clippy on the MSRV toolchain so contributors on newer toolchains cannot introduce warnings the MSRV cannot silence. - Dart-side linting is real and active: extras/rustdesk/flutter/analysis_options.yaml includes
package:lints/recommended.yamland disables exactly two rules by name.
The philosophy: correctness gates (build + test on the pinned toolchain, --locked everywhere) are enforced; style gates are not, because a codebase with 799 unsafe occurrences spread across platform bindings would spend enormous effort keeping pedantic lints green for little payoff. The check infrastructure that does exist is domain-specific instead: checksum verification of downloaded driver binaries inside CI (extras/rustdesk/.github/workflows/flutter-build.yml compares Get-FileHash output against a fetched sha256sums file before extracting the printer driver).
Eleven workflows under extras/rustdesk/.github/workflows. The architecture is a reusable core with thin trigger shells:
flutter-build.yml (2,477 lines) is the single build definition. It is declared on: workflow_call with typed inputs:
on:
workflow_call:
inputs:
upload-artifact:
type: boolean
default: true
upload-tag:
type: string
default: "nightly"Three shells invoke it: extras/rustdesk/.github/workflows/flutter-ci.yml (pull requests and pushes to master, upload-artifact: false), flutter-nightly.yml (cron: "0 0 * * *", uploads to the nightly tag), and flutter-tag.yml (tag patterns like v[0-9]+.[0-9]+.[0-9]+ and [0-9]+.[0-9]+.[0-9]+-[0-9]+, uploads to ${{ github.ref_name }}). One build graph, three release channels, zero duplication.
Job coverage inside flutter-build.yml: generate-sbom (Syft producing cyclonedx-json, published to the release), generate-bridge (flutter_rust_bridge codegen, uploaded as an artifact all platform jobs download, with two matrix rows because Windows arm64 needs a bridge generated by a newer Flutter), build-for-windows-flutter (x64 on windows-2022 and aarch64 on windows-11-arm), build-for-windows-sciter (32-bit fallback UI), build-rustdesk-ios, build-for-macOS, build-rustdesk-android plus a universal-apk job, build-rustdesk-linux plus dedicated drm and sciter variants, build-appimage, build-flatpak, build-rustdesk-web, and publish_unsigned. Every matrix sets fail-fast: false so one platform failing does not hide others.
Version pinning is exemplary. Every third-party action is pinned to a full commit SHA with the human-readable version as a trailing comment:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2The same discipline extends to toolchains: the env block at the top of flutter-build.yml pins RUST_VERSION: "1.75", FLUTTER_VERSION: "3.24.5", VCPKG_COMMIT_ID, NDK_VERSION, LLVM_VERSION, and each pin carries a comment explaining the constraint (for example that Rust 1.78's i128 ABI change breaks the Sciter build, with links). Even a helper DLL built from a sibling repository is pinned: extras/rustdesk/.github/workflows/third-party-RustDeskTempTopMostWindow.yml clones and then git checkout ecd8d6a139eee76845ea66423fb739af450fda90 before msbuild.
Caching is layered per toolchain: Swatinem/rust-cache with prefix-key: ${{ matrix.job.os }} for cargo, VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" plus an exported ACTIONS_CACHE_URL/ACTIONS_RUNTIME_TOKEN step so vcpkg's binary cache rides GitHub's cache backend, actions/cache for the generated bridge keyed on the Flutter version, and subosito/flutter-action with cache: true. When caches wedge there is a manual escape hatch: extras/rustdesk/.github/workflows/clear-cache.yml is a workflow_dispatch-only job with permissions: actions: write that deletes every repository cache through the REST API, then runs a second purge action because its own note admits the first purge is incomplete.
Security-relevant hardening: jobs that publish declare permissions: contents: write explicitly; code signing runs only when secrets exist (if: env.UPLOAD_ARTIFACT == 'true' && env.SIGN_BASE_URL != '-2') and goes through an external signing service (python3 res/job.py sign_files ./rustdesk/), while unsigned artifacts are still uploaded separately so forks without secrets get usable builds. Supply-chain refresh is automated but review-gated: extras/rustdesk/.github/workflows/update-webpki-roots.yml runs weekly (cron: "0 3 * * 1"), updates the pinned Mozilla root store in every lockfile, and opens a PR rather than pushing, under a concurrency group with cancel-in-progress: false so a manual dispatch cannot cancel a run that already pushed. Dependabot watches the submodule pointer daily (extras/rustdesk/.github/dependabot.yml, package-ecosystem: "gitsubmodule").
Cost control: both ci.yml and flutter-ci.yml use paths-ignore for docs/**, README.md, and packaging directories, and the Linux job starts with a pinned jlumbroso/free-disk-space step to make room for vcpkg-built ffmpeg. extras/rustdesk/.github/workflows/ci.yml itself is the fast Rust-only lane: one x86_64-unknown-linux-gnu build with cargo build --locked followed by tests.
There is no top-level tests/ directory; all Rust tests are inline #[cfg(test)] mod tests blocks colocated with the code, 30+ modules containing 202 #[test] functions and 14 #[tokio::test] functions across src/ and libs/. That choice fits a codebase where most logic is platform-gated: the test sits inside the same cfg scope as the code it exercises.
Representative tests worth studying:
-
Table-driven validation tests.
src/common.rstests peer-id sanitization against a literal attack string:
let cases = [
("123456789", true),
("192.168.1.10:21118", true),
(
r#"1" & oWS.Run("cmd.exe /k whoami /priv",1,False) & ""#,
false,
),
("", false),(extras/rustdesk/src/common.rs, untrusted_peer_id_validation).
- CLI surface contract tests. extras/rustdesk/src/core_main.rs ends with a test that pins which flags are management commands versus service commands, so the IPC permission scope of the command surface cannot drift silently:
fn user_main_ipc_scope_cli_command_matches_management_commands_only() {
for command in ["--password", "--set-unlock-pin", "--get-id", ...] {
assert!(is_user_main_ipc_scope_cli_command(&args(&[command])));
}- Byte-level protocol tests. extras/rustdesk/src/server/terminal_service.rs tests a UTF-8 chunk reassembler on malformed and truncated sequences:
fn utf8_split_point_detects_incomplete_trailing_sequence() {
let data = [b'a', 0xE4, 0xB8];
assert_eq!(find_utf8_split_point(&data), 1);
}-
Timing behavior tests with a real tokio runtime comparing a custom throttled interval against
tokio::time::intervaltick-for-tick (extras/rustdesk/src/common.rs,test_RustDesk_interval).
CI runs cargo test --workspace --no-fail-fast -- --skip test_get_cursor_pos --skip test_get_key_state (extras/rustdesk/.github/workflows/ci.yml): the two skipped tests need a real display and cursor, and the skip list is computed per target so ARM builds test only --lib --bin. Hardware-dependent behavior that cannot run headless is covered instead by runnable example harnesses: extras/rustdesk/libs/scrap/examples contains benchmark.rs (the project's de facto codec benchmark), screenshot.rs, record-screen.rs, and ffplay.rs, with docopt, repng, and quest as dev-dependencies to drive them (extras/rustdesk/libs/scrap/Cargo.toml), and extras/rustdesk/examples/ipc.rs exercises the IPC channel manually. There is no fuzzing, property testing, or snapshot testing infrastructure in the repository.
One Result alias for the whole application. Everything fallible returns hbb_common::ResultType<T>, an anyhow-based alias re-exported from the shared submodule, together with bail! and anyhow! (for example extras/rustdesk/src/auth_2fa.rs: fn new_totp(&self) -> ResultType<TOTP>, and .map_err(|_| anyhow!("Thread panicked"))?? to flatten a join handle's nested Results). Application code never defines ad hoc error enums for plumbing.
Library crates own typed errors. Where a crate has a real error taxonomy it uses thiserror, as in extras/rustdesk/libs/clipboard/src/lib.rs:
pub enum CliprdrError {
#[error("failure to read file metadata or content, path: {path}, err: {err}")]
FileError { path: String, err: std::io::Error },
#[error("invalid request: {description}")]
InvalidRequest { description: String },
#[error("unknown cliprdr error")]
Unknown(u32),
}scrap defines its own Error plus pub type Result<T> = std::result::Result<T, Error> (extras/rustdesk/libs/scrap/src/common/mod.rs) and converts C return codes into it via generated macros that capture module_path!()/file!()/line!()/column!() context (see section 9).
Panic policy. Release builds set panic = 'abort' (extras/rustdesk/Cargo.toml), and release binaries register a native crash handler at startup: register_breakdown_handler(breakdown_callback) is imported under #[cfg(not(debug_assertions))] in extras/rustdesk/src/main.rs. So panics are treated as crashes to be reported, not control flow.
Process lifecycle as API. core_main() returns Option<Vec<String>> and documents the contract in a doc comment (extras/rustdesk/src/core_main.rs): None means "terminate now, the CLI handled everything", Some(args) means "continue into the GUI with these residual args". The GUI entry point in extras/rustdesk/src/main.rs is exactly if let Some(args) = crate::core_main::core_main().as_mut() { ui::start(args); }.
Output discipline for a dual-mode binary. Because a windows-subsystem GUI process has no console, user-facing CLI output goes through one macro that prints on Unix and raises a message box on Windows (extras/rustdesk/src/core_main.rs):
macro_rules! my_println{
($($arg:tt)*) => {
#[cfg(not(windows))]
println!("{}", format_args!($($arg)*));
#[cfg(windows)]
crate::platform::message_box(
&format!("{}", format_args!($($arg)*))
);
};
}Visibility discipline. extras/rustdesk/src/lib.rs is a wall of platform-gated module declarations: pub mod only where the FFI or the Flutter bridge needs the symbols, mod otherwise, with /// cbindgen:ignore doc-directives excluding modules from C header generation. Constants that are protocol strings are pub const next to the trait they serve (extras/rustdesk/src/privacy_mode.rs).
Ten-plus concrete idioms, each cited:
-
cfg_if!backend dispatch on custom cfg keys. extras/rustdesk/libs/scrap/src/common/mod.rs selectsquartz/x11/dxgi/androidcapture backends with nestedcfg_if!blocks; the keys are custom cfgs emitted by the crate's build script (extras/rustdesk/libs/scrap/build.rs usestarget_build_utils), so the platform decision is made once at build time and the rest of the crate uses clean flags instead of repeatingtarget_ostriples. -
A borrowed frame enum for zero-copy capture. Captured frames never copy pixel data on the happy path:
pub enum Frame<'a> { PixelBuffer(PixelBuffer<'a>), Texture((*mut c_void, usize)) }withfn frame<'a>(&'a mut self, timeout: Duration) -> std::io::Result<Frame<'a>>on theTraitCapturertrait (extras/rustdesk/libs/scrap/src/common/mod.rs). The frame borrows the capturer's buffer, and GPU-resident frames stay as raw texture pointers until encoding.EncodeInput<'a>continues the borrow into the encoder. -
WouldBlockas a data-level signal.would_block_if_equal(old: &mut Vec<u8>, b: &[u8]) -> std::io::Result<()>returnsErrorKind::WouldBlockwhen a captured frame is identical to the previous one (extras/rustdesk/libs/scrap/src/common/mod.rs), letting the video loop reuse the same error path for "no new frame from the OS" and "frame unchanged, skip encode". -
A generic pub/sub service template with a marker-bound newtype. extras/rustdesk/src/server/service.rs defines
pub trait Service: Send + Sync,pub trait Subscriber: Default + Send + Sync + 'static, andpub struct ServiceTmpl<T: Subscriber + From<ConnInner>>(Arc<RwLock<ServiceInner<T>>>)withpub type GenericService = ServiceTmpl<ConnInner>;. Every capture service (video, audio, clipboard, terminal) instantiates this one template; theFrom<ConnInner>bound is how a raw connection is promoted into a typed subscriber.EmptyExtraFieldServicethen usesDerefto forward to the inner template, a cheap delegation idiom. -
An async trait as the UI abstraction boundary.
#[async_trait] pub trait Interface: Send + Clone + 'static + Sized(extras/rustdesk/src/client.rs) mixes sync methods, async methods (async fn handle_hash(&self, ...)), and default method bodies (fn on_error(&self, err: &str) { self.msgbox("error", "Error", err, "") }), so Sciter, Flutter desktop, and mobile sessions plug the same client engine. -
Macros that generate macros for FFI error walls. extras/rustdesk/libs/scrap/src/common/mod.rs exports
generate_call_macro!, which expands to a per-call-site macro that wraps an unsafe C call, transmutes the status toi32, and either logs or early-returns acrate::Error::FailedCallcarryingmodule_path!()/file!()/line!()/column!(). Each codec module instantiates it once and gets uniform, located error reporting for hundreds of C calls. -
A declarative-macro dlopen wrapper with graceful degradation.
make_lib_wrapper!in extras/rustdesk/libs/virtual_display/src/lib.rs takesfield: Typepairs, generates a struct holdingOption<Library>plus oneOption<fn ...>per symbol, and resolves each symbol at runtime withlib.symbol::<$tp>(stringify!($field)), logging and continuing on failure. The driver dylib being absent degrades features instead of crashing;#[repr(C)] pub struct _MonitorModeandpub type PMonitorMode = *mut MonitorMode;keep the C ABI explicit. -
Scoped runtimes via
#[tokio::main]on inner functions. Rather than one global runtime, blocking entry points wrap async bodies where needed:#[tokio::main(flavor = "current_thread")]appears on functions in extras/rustdesk/src/server.rs, src/lan.rs, src/tray.rs, and src/ui_interface.rs, giving a single-threaded runtime whose lifetime is the function call, which is exactly right for request-scoped async work called from sync UI code. -
Lock-scope discipline in iterator pipelines. extras/rustdesk/src/server/video_service.rs collects under one mutex, then drops it before taking the next:
let vec_display_idx: Vec<usize> = { let display_conn_ids = DISPLAY_CONN_IDS.lock().unwrap(); display_conn_ids .iter() .filter_map(|(display_idx, conn_ids)| { if conn_ids.contains(&conn_id) { Some(*display_idx) } else { None } }) .collect() };
The block expression bounds the guard's lifetime; the subsequent loop locks a different map. Global state is
lazy_static!(145 uses) overArc<Mutex<...>>(91),Arc<RwLock<...>>(39), and atomics (84AtomicBool/AtomicUsizesites), a pre-OnceLockvintage that is nonetheless consistently scoped like this. -
Serde-tagged state enums for IPC.
#[derive(Serialize, Deserialize)] #[serde(tag = "t", content = "c")] pub enum PrivacyModeState(extras/rustdesk/src/privacy_mode.rs) puts an explicit compact tag on the wire, and thePrivacyMode: Sync + Sendtrait behind it has multiple Windows implementations selected by string constants (PRIVACY_MODE_IMPL_WIN_MAG,..._VIRTUAL_DISPLAY) so the implementation choice is a runtime config value. -
Cowfor computed-or-static strings.fn keysequence<'a>(key: Key) -> Cow<'a, str>in extras/rustdesk/libs/enigo/src/linux/xdo.rs returns borrowed literals for named keys and owned strings for unicode escapes, avoiding allocation on the common path. -
Unsafe policy: quarantine by module. 799
unsafeoccurrences live almost entirely insrc/platform/and the FFI layers oflibs/scrap,libs/enigo, andlibs/clipboard, each such module opening with the#![allow(non_camel_case_types)]-style header block (section 5). Cross-platform logic above those modules is safe Rust;build.rscompiles the companionwindows.cc/macos.mmnative shims (extras/rustdesk/build.rs) so C++ stays out of the Rust files entirely.
-
Massively translated project docs. extras/rustdesk/docs holds README in about 30 languages, CONTRIBUTING in 14, SECURITY and CODE_OF_CONDUCT in a dozen each, all as parallel
-XX.mdfiles. The root README.md links to them. -
CONTRIBUTING encodes process, not style. extras/rustdesk/docs/CONTRIBUTING.md requires claiming an issue before working on it, small independently-correct commits, tests relevant to the change, and a Developer Certificate of Origin sign-off (
git commit -s) binding contributions to the license. -
Issue intake is a structured YAML form. extras/rustdesk/.github/ISSUE_TEMPLATE/bug_report.yaml makes description, reproduction, expected behavior, both-side OS versions, both-side RustDesk versions, and screenshots all
required: true, which matters enormously for a two-endpoint product. extras/rustdesk/.github/ISSUE_TEMPLATE/config.yml setsblank_issues_enabled: falseand routes feature requests and questions to GitHub Discussions. -
Rustdoc where a crate is a library.
libs/enigoopens with long-form//!module documentation includingno_rundoctest examples (extras/rustdesk/libs/enigo/src/lib.rs); application modules instead favor targeted doc comments on contracts, like thecore_mainreturn-value semantics (extras/rustdesk/src/core_main.rs) and functional directives such as/// cbindgen:ignorein extras/rustdesk/src/lib.rs. - Comments explain constraints with receipts. Workflow env pins, Cargo dependency choices, and feature definitions consistently carry links to the issue, discussion, or upstream blog post that forced the decision (for example the cpal-on-Linux exclusion in extras/rustdesk/Cargo.toml citing discussion 10197). There is no in-repo mdBook or docs site; user documentation lives outside the repository.
-
Versioning is manifest-driven with a mechanical bump. The version appears in extras/rustdesk/Cargo.toml, libs/portable/Cargo.toml, workflow env (
VERSION: "1.4.9"), rpm specs, PKGBUILD, pubspec, flatpak and appimage recipes; extras/rustdesk/res/bump.sh rewrites all of them in onesedpass and then runscargo runsolely to regenerateCargo.lock:
sed -i "s/\b$1\b/$2/g" res/*spec res/PKGBUILD flutter/pubspec.yaml Cargo.toml .github/workflows/*yml flatpak/*json appimage/*yml libs/portable/Cargo.toml
cargo run # to bump version in cargo lock-
Releases are tag-triggered and nightly. flutter-tag.yml fires on version-shaped tags, flutter-nightly.yml republishes the
nightlyprerelease every midnight, and both feed the same reusable build withsoftprops/action-gh-release(SHA-pinned) uploading withprerelease: true. -
The distribution matrix is extreme: signed
.msi(WiX v4 solution under extras/rustdesk/res/msi with native CustomActions, built per-arch including ARM64) and a self-extracting portable.exeproduced by thelibs/portablepacker crate;.debvia extras/rustdesk/res/DEBIAN maintainer scripts; four rpm spec variants and aPKGBUILDunder res/; AppImage recipes per-arch under extras/rustdesk/appimage; flatpak under extras/rustdesk/flatpak; Android APKs plus F-Droid delivery, where extras/rustdesk/.github/workflows/fdroid.yml computes a monotonic version code (X * 1e6 + Y * 1e4 + Z * 1e2 + A) and publishes arustdesk-version.txtunder a dedicatedfdroid-versiontag for the updater to poll; fastlane metadata under extras/rustdesk/fastlane. -
Supply-chain artifacts ship with the release: the
generate-sbomjob attachesrustdesk.sbom.json(CycloneDX from Syft) to every uploaded tag (extras/rustdesk/.github/workflows/flutter-build.yml). -
Signing is a service, not a secret file:
res/job.py sign_filesposts artifacts to a signing endpoint configured by secrets, and unsigned artifact bundles are uploaded regardless so downstream packagers are never blocked. - There is no CHANGELOG file in the repository; release notes live on the GitHub releases created by the tag workflow. As a GUI-first product it ships no man pages or shell completions; the CLI surface is hand-parsed in extras/rustdesk/src/core_main.rs.
quinjet already exceeds RustDesk on lint strictness, formatting enforcement, and test tooling, so the transferable value is in CI architecture, release mechanics, and a few testing patterns:
-
Pin every GitHub Action to a full commit SHA with a trailing version comment. Mechanism: in each workflow,
uses: owner/action@<40-char sha> # vN, as done throughout extras/rustdesk/.github/workflows/ci.yml. Dependabot or Renovate can still bump the comment and SHA together. -
Make one reusable
workflow_callbuild workflow and thin trigger shells. Mechanism: move build/test/package steps into.github/workflows/build.ymlwithon: workflow_calland typedinputs:(booleanupload-artifact, stringupload-tag), then add three callers for PR, nightlyschedule:, andpush: tags:exactly as extras/rustdesk/.github/workflows/flutter-ci.yml / flutter-nightly.yml / flutter-tag.yml do. -
Add a scheduled dependency-refresh workflow that opens a reviewable PR. Mechanism: copy the shape of extras/rustdesk/.github/workflows/update-webpki-roots.yml:
schedule:cron plusworkflow_dispatch:, aconcurrency:group withcancel-in-progress: false,permissions: contents: write, pull-requests: write, runcargo update, diff-gate withgit diff --quiet, andgh pr createfrom a fixed branch. For quinjet the payload iscargo updateplus regeneratedcargo denyoutput instead of webpki roots. -
Attach an SBOM to every release. Mechanism: a job using
anchore/sbom-action/download-syft, thensyft dir:. -o cyclonedx-json=quinjet.sbom.json, uploaded via the release action, mirroring thegenerate-sbomjob in extras/rustdesk/.github/workflows/flutter-build.yml. -
Key Rust caches per matrix row. Mechanism:
Swatinem/rust-cachewithprefix-key: ${{ matrix.os }}(extras/rustdesk/.github/workflows/flutter-build.yml) so Linux, macOS, and Windows caches never collide; add a manualclear-cache.yml(workflow_dispatch,permissions: actions: write,github.rest.actions.deleteActionsCacheById) for wedged caches, copied from extras/rustdesk/.github/workflows/clear-cache.yml. -
Use
paths-ignoreto keep docs changes out of the build lane. Mechanism: on bothpull_requestandpush, ignoredocs/**andREADME.mdas in extras/rustdesk/.github/workflows/ci.yml; pair it with a docs-only workflow if the wiki generation needs its own gate. -
Set matrix
fail-fast: falseeverywhere. Mechanism:strategy: fail-fast: falseon every OS matrix, so a Windows-only failure still yields Linux and macOS signal in the same run, as every RustDesk matrix does. -
Write a CLI-surface contract test. Mechanism: a unit test enumerating every subcommand and asserting its classification, modeled on
user_main_ipc_scope_cli_command_matches_management_commands_onlyin extras/rustdesk/src/core_main.rs; for quinjet, iterateCommand::get_subcommands()from the clap definition and assert each maps to a TUI operation and vice versa, so the "every operation is also a CLI subcommand" invariant is machine-checked. -
Table-driven validator tests with hostile inputs. Mechanism: literal
[(input, expected)]arrays including injection-shaped strings, as inuntrusted_peer_id_validation(extras/rustdesk/src/common.rs); apply to quinjet's ref-name, remote, and pathspec validation. -
Skip environment-dependent tests by name in CI, not by deleting them. Mechanism:
cargo test --workspace --no-fail-fast -- --skip <name>per target, as in extras/rustdesk/.github/workflows/ci.yml; for quinjet, tests that need a real TTY can stay runnable locally while CI skips them explicitly and visibly. -
Make the release binary small and crash-clean. Mechanism:
[profile.release] lto = true,codegen-units = 1,strip = true,panic = 'abort'(extras/rustdesk/Cargo.toml); for a TUI, pairpanic = 'abort'with a panic hook that restores the terminal first, the moral equivalent ofregister_breakdown_handlerin extras/rustdesk/src/main.rs. -
Single-source the version and bump it mechanically. Mechanism: a
bump.sh-style script or anxtaskthat rewrites every file embedding the version and refreshesCargo.lockin the same commit (extras/rustdesk/res/bump.sh); quinjet embeds its version in Cargo.toml, docs, and the wiki generator, so drift is possible today. -
Adopt structured YAML issue forms with required fields and disabled blank issues. Mechanism:
.github/ISSUE_TEMPLATE/bug_report.yamlwithvalidations: required: trueper field plusconfig.ymlblank_issues_enabled: falseand Discussion links, copied from extras/rustdesk/.github/ISSUE_TEMPLATE. -
Gate additive risk behind its own feature. Mechanism: when a feature both reads and writes where its parent only reads, give the write path a dedicated cargo feature depending on the parent, as
drm-wake = ["drm"]does in extras/rustdesk/Cargo.toml; for quinjet, destructive Git operations behind an opt-in feature or config gate follow the same principle. -
Keep runnable examples as manual harnesses for what tests cannot cover. Mechanism:
examples/*.rsdriven by dev-dependencies (extras/rustdesk/libs/scrap/examples/benchmark.rs), which for quinjet means an example that drives the TUI against a throwaway repository for eyeball and performance checks outside the test harness.
Tauri is a framework for building small, secure desktop and mobile applications whose UI is
rendered in the operating system webview while the application backend is a compiled Rust binary.
Industry adopts it as the lighter alternative to Electron: no bundled browser runtime, binaries in
the low megabytes, and a capability-based security model between the webview and the Rust core.
The repository is the entire product surface: the runtime crates, the code generator, the macro
crates, the bundler, the cargo tauri CLI, and the npm packages that wrap them.
Scale, measured directly from the clone at commit 2f1cd75b0f3fb72e6870d719bbfeadedcf8ca884:
- 14 first-party crates under
extras/tauri/crates/(tauri, tauri-build, tauri-bundler, tauri-cli, tauri-codegen, tauri-driver, tauri-macos-sign, tauri-macros, tauri-plugin, tauri-runtime, tauri-runtime-wry, tauri-schema-generator, tauri-schema-worker, tauri-utils). - 25 workspace members in
extras/tauri/Cargo.tomlonce the napi CLI wrapper (packages/cli), two integration test crates (crates/tests/restart,crates/tests/acl), four bench crates, and four example app crates are counted. - 326
.rsfiles totaling roughly 100,000 lines of Rust; about 97,000 of those lines live underextras/tauri/crates/outside the CLI project templates. - Per-crate
src/line counts: tauri 32,678; tauri-cli 22,606; tauri-utils 15,502; tauri-bundler 9,014; tauri-runtime-wry 6,748; tauri-runtime 2,851; tauri-build 2,038; tauri-codegen 1,618; tauri-macros 1,458; tauri-plugin 376. - 21 workflow files under
extras/tauri/.github/workflows/.
extras/tauri/
|-- ARCHITECTURE.md system overview, one section per crate
|-- Cargo.toml virtual workspace root, no root package
|-- Cargo.lock committed, one lock for every member
|-- rustfmt.toml shared Rust formatting
|-- .editorconfig cross-language whitespace baseline
|-- .prettierrc JS/TS/MD/YAML formatting
|-- .cargo/
| |-- config.toml [env] workaround for Windows test loading
| `-- audit.toml cargo-audit RUSTSEC ignore list with reasons
|-- .changes/ covector change files, one per pending release note
|-- .scripts/ci/ Node helper scripts run by workflows
|-- .github/workflows/ 21 CI/CD pipelines
|-- audits/ published third-party security audit PDFs
|-- supply-chain/ cargo-vet config, audits, imports.lock
|-- bench/ internal benchmark harness plus 3 app fixtures
|-- crates/ all Rust crates
| `-- tests/ integration-only crates (restart, acl)
|-- examples/ runnable example apps, some are workspace members
`-- packages/ npm packages (@tauri-apps/api, @tauri-apps/cli)
The split works because each layer has one owner crate: tauri-runtime defines the windowing
abstraction, tauri-runtime-wry implements it, tauri-utils holds config parsing and the ACL
model shared by build-time and run-time code, tauri-codegen and tauri-macros turn config into
compiled context, and tauri composes them. extras/tauri/ARCHITECTURE.md documents exactly this
decomposition, one heading per crate, and marks stability per component
("Tauri Core [STABLE RUST]"). Test-only crates live under extras/tauri/crates/tests/ so heavy
integration fixtures never bloat the published packages, and everything that is npm-facing is
quarantined in extras/tauri/packages/.
The root extras/tauri/Cargo.toml is a virtual workspace with resolver = "2" and centralizes
identity fields in [workspace.package]:
[workspace.package]
authors = ["Tauri Programme within The Commons Conservancy"]
homepage = "https://tauri.app/"
repository = "https://github.com/tauri-apps/tauri"
categories = ["gui", "web-programming"]
license = "Apache-2.0 OR MIT"
edition = "2021"
rust-version = "1.90"Every crate inherits these with the dotted form, e.g. extras/tauri/crates/tauri/Cargo.toml:
edition.workspace = true, rust-version.workspace = true. [workspace.dependencies] pins the
intra-workspace crates with both a version and a path, so members depend on
tauri-utils = { workspace = true, features = [...] } and publishing still resolves to crates.io
versions. Third-party dependencies deliberately stay per-crate rather than in the workspace table,
keeping each manifest an honest inventory of what that crate uses.
Notable manifest techniques, all in extras/tauri/crates/tauri/Cargo.toml:
- Platform-partitioned dependency tables with full
cfgexpressions, one section per platform family, so Linux GTK crates,objc2-*Apple crates,windows/webview2-com,jnifor Android, and mobile-onlyreqwestnever appear on the wrong target:
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
gtk = { version = "0.18", features = ["v3_24"] }
webkit2gtk = { version = "2", features = ["v2_40"], optional = true }- A large, additive feature graph where features forward to sub-crates with the
?syntax (tracing = ["dep:tracing", "tauri-macros/tracing", "tauri-runtime-wry?/tracing"]) anddep:gates keep optional dependencies out of the implicit feature namespace. - Inline policy comments on risky pins:
# WARNING: cookie::Cookie is re-exported so bumping this is a breaking change, documented to be done as a minor bump. -
[package.metadata.docs.rs]requesting a curated feature set and five explicit doc targets, plus[package.metadata.cargo-udeps.ignore]to silence known false positives per dependency kind (normal = ["reqwest"],build = ["tauri-build"],development = ["quickcheck_macros"]). -
exclude = ["/test", "/.scripts", "CHANGELOG.md", "/target"]and, inextras/tauri/crates/tauri-cli/Cargo.toml, an explicitinclude = [...]allowlist so the published CLI package carries only sources, templates, and licenses.
The workspace tunes profiles for shipping size, with a comment stating the intent:
# default to small, optimized workspace release binaries
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
incremental = false
opt-level = "s"
strip = trueplus [profile.dev.package.miniz_oxide] opt-level = 3 so asset compression is bearable in dev
builds, and a [patch.crates-io] section pointing schemars_derive at a fork, annotated with the
upstream issue link that justifies the patch. The only [lints] table in the repo is in
extras/tauri/crates/tauri-schema-worker/Cargo.toml, which registers an expected custom cfg:
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(wasm_bindgen_unstable_test_coverage)',
] }extras/tauri/rustfmt.toml is checked into the root and applies to all crates:
max_width = 100
hard_tabs = false
tab_spaces = 2
newline_style = "Unix"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
edition = "2021"
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = trueSetting by setting: max_width = 100 widens the default 100/comment line budget slightly for the
deeply nested builder code; tab_spaces = 2 matches the JS side of the monorepo so mixed reviews
read uniformly; newline_style = "Unix" forces LF even on Windows checkouts; reorder_imports
and reorder_modules remove import-order bikeshedding; merge_derives collapses derive lists
into a single attribute; use_try_shorthand = false and use_field_init_shorthand = false keep
explicit forms, a readability-over-brevity call; force_explicit_abi = true requires
extern "C" rather than bare extern, relevant for a codebase with FFI. Two nightly-only
options (normalize_comments, wrap_comments) are kept commented out rather than deleted, which
records the intent without breaking stable rustfmt.
extras/tauri/.editorconfig sets the baseline for every file type: charset = utf-8,
indent_style = space, indent_size = 2, end_of_line = lf, insert_final_newline = true,
trim_trailing_whitespace = true. Non-Rust formatting is Prettier, configured in
extras/tauri/.prettierrc ("singleQuote": true, "semi": false) with a heavily commented
extras/tauri/.prettierignore that excludes generated bundles, CLI templates, WiX .wxs
templates, and lock files. TOML files are formatted by taplo with default settings; the taplo
job in extras/tauri/.github/workflows/fmt.yml runs taplo fmt --check --diff.
There is no clippy.toml and, apart from the wasm worker noted above, no [lints] tables. The
clippy wall lives entirely in CI. extras/tauri/.github/workflows/lint-rust.yml runs clippy as
deny-warnings across a five-target matrix (Windows MSVC, Linux GNU, macOS aarch64, iOS aarch64,
Android via cross):
- run: ${{ matrix.platform.cargo }} clippy --target ${{ matrix.platform.target }} ${{ matrix.platform.include }}--all-targets --all-features -- -D warningsThe mobile rows lint through the example app (include: '--package api ') with the comment
"api example crate should pull in every dependency we want to lint on mobile", which is a cheap
way to lint the full mobile dependency closure without a separate harness. The philosophy is:
default clippy level, but enforced everywhere, on every platform, with warnings as errors, and
suppressions must be local and explicit. The tree contains only 47 allow(clippy::...)
attributes across ~100k lines, each scoped to one item, e.g.
#[allow(clippy::large_enum_variant)] in extras/tauri/crates/tauri-macros/src/command/wrapper.rs.
Library crates raise the bar at the crate level rather than in manifests.
extras/tauri/crates/tauri/src/lib.rs, extras/tauri/crates/tauri-utils/src/lib.rs, and
extras/tauri/crates/tauri-bundler/src/lib.rs all declare:
#![warn(missing_docs, rust_2018_idioms)]Custom check infrastructure fills the gaps clippy cannot see: extras/tauri/.scripts/ci/check-license-header.js
verifies the SPDX header on every added .rs, .js, .ts, .yml, .swift, and .kt file
(wired into extras/tauri/.github/workflows/check-license-header.yml), and
extras/tauri/.scripts/ci/check-change-tags.js validates release change files. Unused
dependencies are policed by a dedicated nightly cargo udeps --all-targets --all-features job in
extras/tauri/.github/workflows/udeps.yml, which builds a dynamic per-crate matrix from
dorny/paths-filter outputs so only touched crates are scanned.
All 21 workflows live in extras/tauri/.github/workflows/. Shared conventions: every workflow
carries the SPDX license header; almost every one declares a concurrency group
(group: ${{ github.workflow }}-${{ github.ref }}, cancel-in-progress: true); PR triggers are
path-filtered so a docs change does not spin up the Windows fleet; caching uses
Swatinem/rust-cache@v2 keyed by target triple; and jobs export
CARGO_PROFILE_DEV_DEBUG: 0 with the comment "This would add unnecessary bloat to the target
folder, decreasing cache efficiency."
-
fmt.yml: three jobs on every PR:cargo fmt --all -- --check, Prettier viapnpm format:check, andtaplo fmt --check --diff. -
lint-rust.yml: the five-target clippy matrix described above, withfail-fast: false. -
test-core.yml: a matrix of five platforms times two feature sets (--no-default-featuresvs--all-features), pinned to the MSRV toolchain (toolchain: '1.90'), where iOS and Android rows downgradetesttobuild. Cache writes are restricted withsave-if: ${{ matrix.features.key == 'all' }}so the no-default variant reuses rather than churns the cache. Android usescrossinstalled from a specific git revision with--locked. -
test-cli-rs.yml: CLI tests on four targets includingaarch64-pc-windows-msvcwith--no-default-features --features native-tls-vendored. -
test-android.yml: builds a real mobile template project on all three OS runners with Java 25 and Gradle caching, path-filtered to the mobile template and mobile CLI sources. -
audit.yml: daily cron plus lockfile-path triggers, runningrustsec/audit-check@v2andpnpm audit. Its ignore list is versioned inextras/tauri/.cargo/audit.toml, where every RUSTSEC id carries a justification comment. -
supply-chain.yml: dailycargo-vetrun with the binary cached in the runner tool cache; the config inextras/tauri/supply-chain/config.tomlimports audit sets from bytecode-alliance, Embark, Google, ISRG, Mozilla, and Zcash, andsupply-chain/audits.tomlrecords trusted publishers per crate. -
udeps.yml: nightly cargo-udeps, one matrix leg per changed crate, sharing one compiledcargo-udepsbinary between jobs via artifact upload/download. -
check-generated-files.yml: rebuilds the TS API bundle and the JSON config schemas when their sources change, then fails ifgit diffis non-empty viaextras/tauri/.scripts/ci/has-diff.sh. Generated artifacts are committed, and CI proves they are in sync. -
check-change-tags.ymlandcheck-license-header.yml: the custom Node checks, both usingdorny/paths-filter@v3withlist-files: shellto pass exactly the changed files. -
covector-status.ymlpluscovector-comment-on-fork.yml: release-note status on every PR; the fork variant is aworkflow_runfollow-up with an explicit least-privilegepermissions:block (actions: read,pull-requests: write) because fork PRs cannot comment directly. -
covector-version-or-publish.yml,publish-cli-rs.yml,publish-cli-js.yml,deploy-schema-worker.yml,docker.yml,bench.yml: release and infrastructure automation, covered in sections 7 and 11.
Action pinning is pragmatic rather than absolute: most actions ride major tags
(actions/checkout@v7, dtolnay/rust-toolchain@stable, taiki-e/install-action@v2), while the
actions that hold elevated tokens are pinned by full SHA, e.g. in
covector-version-or-publish.yml:
uses: peter-evans/repository-dispatch@ff45666b9427631e3450c54a1bcbee4d9ff4d7c0 # 3.0.0and softprops/action-gh-release@50195ba7... in publish-cli-rs.yml. The organization also
maintains a hard fork of create-pull-request, explained in extras/tauri/ARCHITECTURE.md:
"Because this is a very risky (potentially destructive) github action, we forked it in order to
have strong guarantees that the code we think is running is actually the code that is running."
Dependency update security is belt and suspenders: extras/tauri/dependabot.yml sets
open-pull-requests-limit: 0 on every ecosystem (security alerts only, no version PR spam) and
extras/tauri/renovate.json does the version bumping with "minimumReleaseAge": "3 days" so a
compromised release cannot land the day it is published.
Unit tests are conventional #[cfg(test)] mod tests blocks colocated with the code
(extras/tauri/crates/tauri-utils/src/acl/identifier.rs, .../platform.rs, .../html.rs, and
many more). Integration tests get their own workspace crates under extras/tauri/crates/tests/
so their dependencies (tempfile, insta, fixtures) never touch published manifests.
Harness infrastructure is the standout. The tauri crate ships a full mock of its own runtime
behind the test feature: extras/tauri/crates/tauri/src/test/mock_runtime.rs (1,413 lines)
implements the entire Runtime trait without a windowing system, and
extras/tauri/crates/tauri/src/test/mod.rs exposes mock_builder, mock_context, and
get_ipc_response so downstream apps can unit test IPC commands headlessly. The module doc
carries a compilable example that invokes a #[tauri::command] and asserts on the response.
Snapshot testing uses insta with per-platform snapshot routing.
extras/tauri/crates/tests/acl/src/lib.rs iterates capability fixtures and redirects
platform-specific cases to per-OS snapshot directories:
let mut settings = insta::Settings::clone_current();
settings.set_snapshot_path(
if fixture_entry.path().file_name().unwrap() == "platform-specific-permissions" {
Path::new("../fixtures/snapshots").join(Target::current().to_string())
} else {
Path::new("../fixtures/snapshots").to_path_buf()
},
);with committed .snap files under extras/tauri/crates/tests/acl/fixtures/snapshots/. The CLI
snapshots Xcode project rewrites the same way in extras/tauri/crates/tauri-cli/src/helpers/pbxproj.rs
against fixtures in extras/tauri/crates/tauri-cli/tests/fixtures/pbxproj/.
Property testing uses both proptest and quickcheck, at serious case counts.
extras/tauri/crates/tauri/src/event/listener.rs drives the listener map with
proptest! { #![proptest_config(ProptestConfig::with_cases(10000))] ... } over generated event
names, and extras/tauri/crates/tauri/src/ipc/format_callback.rs defines Arbitrary impls for
CallbackFn and a JsonStr wrapper, then quickchecks that arbitrary strings survive the
JS-injection escaping (#[quickcheck] fn qc_formatting(f: CallbackFn, a: String) -> bool). This
is exactly the code where a missed escape is a security bug, and the tests are aimed there.
Process-level behavior gets real end-to-end coverage: extras/tauri/crates/tests/restart/tests/restart.rs
compiles a helper binary, copies it into a tempfile::TempDir, invokes it through single and
nested symlinks, and asserts on stdout, including the expected macOS security failure when the
process-relaunch-dangerous-allow-symlink-macos feature is absent. The Node CLI has its own
__tests__ suite under extras/tauri/packages/cli/, run in the pre-release gate of
covector-version-or-publish.yml (run-integration-tests job runs cargo test --test '*' -- --ignored
and pnpm test on all three desktop OSes before any publish is attempted).
Benchmarks are a custom harness, not criterion: extras/tauri/bench/src/run_benchmark.rs builds
three fixture apps with nightly -Z build-std (see extras/tauri/.github/workflows/bench.yml),
measures startup, memory, thread and syscall counts by parsing strace -c -f output, and the
workflow pushes JSON results to the separate tauri-apps/benchmark_results repository on every
dev push, giving a public time series rather than a per-PR pass/fail.
Every library crate defines a thiserror enum, and the public one in
extras/tauri/crates/tauri/src/error.rs is #[non_exhaustive] (the repo has 54 non_exhaustive
attributes overall) with platform- and feature-gated variants:
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Runtime error.
#[error("runtime error: {0}")]
Runtime(#[from] tauri_runtime::Error),
/// Window label must be unique.
#[error("a window with label `{0}` already exists")]
WindowLabelAlreadyExists(String),anyhow appears in the app-facing surface (setup hooks return boxed errors), and the same file
shows a narrowly justified unsafe wrapper: SetupError holds Box<dyn std::error::Error> and
implements Send/Sync manually with the comment "safety: the setup error is only used on the main
thread and we exit the process immediately."
The CLI is the more interesting case study. extras/tauri/crates/tauri-cli/src/error.rs replaces
anyhow with a purpose-built system: a small Error enum whose Fs variant forces every
filesystem failure to carry both a static context string and the offending path, an ErrorExt
extension trait (fn fs_context(self, context: &'static str, path: impl Into<PathBuf>)), a
hand-rolled Context/with_context trait mirroring anyhow's API for both Result and Option,
and a crate-private bail! macro. Callers read like
write(&output, completions).fs_context("failed to write to completions", output)?
(extras/tauri/crates/tauri-cli/src/completions.rs). Exit discipline is centralized in
extras/tauri/crates/tauri-cli/src/lib.rs:
pub fn run<I, A>(args: I, bin_name: Option<String>)
{
if let Err(e) = try_run(args, bin_name) {
log::error!("{e}");
exit(1);
}
}with a fallible try_run kept public so the napi wrapper in extras/tauri/packages/cli can embed
the CLI without process exits. Unsupported platforms fail fast in
extras/tauri/crates/tauri-cli/src/main.rs with a #[cfg(not(...))] fn main() that prints one
line and exits 1.
API design centers on builders and sealed traits. WebviewWindowBuilder<'a, R: Runtime, M: Manager<R>>
(extras/tauri/crates/tauri/src/webview/webview_window.rs) is the canonical consuming builder
ending in pub fn build(self) -> crate::Result<WebviewWindow<R>>. The Manager trait in
extras/tauri/crates/tauri/src/lib.rs is publicly implementable in name only:
pub trait Manager<R: Runtime>: sealed::ManagerBase<R> where sealed::ManagerBase lives in a
private module, so App, AppHandle, Window, and Webview share a rich default-method surface while
the crate keeps the right to evolve the base. Visibility is tightly held elsewhere too:
EventName and StateManager::set are pub(crate), and API removals go through #[deprecated]
attributes first (five sites, e.g. extras/tauri/crates/tauri/src/window/mod.rs:876).
-
Generic runtime abstraction with associated types.
extras/tauri/crates/tauri-runtime/src/lib.rsdefinespub trait RuntimeHandle<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'staticwithtype Runtime: Runtime<T, Handle = Self>, a mutually-constrained pair that lets the whole framework be generic over the windowing backend while keeping handle and runtime types locked to each other at compile time. The mock runtime in tests is just another implementor. -
Sealed supertraits.
extras/tauri/crates/tauri/src/lib.rspairspub trait Manager<R: Runtime>: sealed::ManagerBase<R>with a privatemod sealed, exposing dozens of default methods (app_handle,config,state) that all bottom out in three private accessors. Downstream code gets a uniform API on six different types without any of them being able to be reimplemented incorrectly. -
An axum-style extractor trait with a blanket impl.
extras/tauri/crates/tauri/src/ipc/command.rsdeclarespub trait CommandArg<'de, R: Runtime>: Sized { fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError>; }and thenimpl<'de, D: Deserialize<'de>, R: Runtime> CommandArg<'de, R> for D, so any serde type is automatically a command parameter whileState,Window, andAppHandleprovide specialized impls. The#[tauri::command]proc macro generates calls into this trait. -
Lifetime-carrying newtypes for managed state.
extras/tauri/crates/tauri/src/state.rsdefinespub struct State<'r, T>(&'r T)whoseinner(&self) -> &'r Tdeliberately returns the longer lifetime, and backs it with aStateManagerbuilt onHashMap<TypeId, Box<dyn Any + Sync + Send>, BuildHasherDefault<IdentHash>>, whereIdentHashis a custom identity hasher becauseTypeIdis already a hash. The oneunsafeblock extending a borrow's lifetime is fenced by written invariants: "Once you insert a value, you can't remove/mutated/move it anymore", and the API that would violate it (unmanage) is itself markedunsafewith its own SAFETY contract. -
Storage-generic validated newtypes.
extras/tauri/crates/tauri/src/event/event_name.rshaspub(crate) struct EventName<S = String>(S)validated innew, withimpl Copy for EventName<&str>, aconst fn from_str(s: &'static str)restricted to'static"to discharge the preconditions" in const contexts, and anas_str_eventview type, giving one validation point across owned and borrowed use without allocation. -
Parser newtypes as state machines.
extras/tauri/crates/tauri-utils/src/acl/identifier.rsvalidates permission identifiers byte by byte through aValidByteenum inimpl TryFrom<String> for Identifier, stores the separator position asOption<NonZeroU8>for niche-packing, and enumerates every failure mode in aParseIdentifierErrorthiserror enum (TrailingHyphen,PrefixWithoutBase,Humongous(usize)). -
Cow-first asset APIs.
extras/tauri/crates/tauri-utils/src/assets.rstypes the asset iterator aspub type AssetsIter<'a> = dyn Iterator<Item = (Cow<'a, str>, Cow<'a, [u8]>)> + 'a;so embedded assets are served borrowed while compressed assets decompress intoCow::Owned, and the test helperNoopAssetinextras/tauri/crates/tauri/src/test/mod.rssatisfies the same trait with a borrowed iterator pipeline. -
Main-thread affinity encoded with unsafe wrappers and ManuallyDrop.
extras/tauri/crates/tauri/src/menu/mod.rsgenerates menu wrappers via agen_wrappers!macro whoseDropimpl moves the inner muda handle back to the main thread:let inner = unsafe { ManuallyDrop::take(&mut self.inner) }; // SAFETY: inner was created on main thread and is being dropped on main thread let inner = $crate::UnsafeSend(inner); let _ = self.app_handle.run_on_main_thread(move || { drop(inner.take()); });
together with the
run_item_main_thread!macro that round-trips any closure through anstd::sync::mpscchannel to the event loop. Everyunsafe impl Send/Syncin the tree carries a# Safetycomment naming the thread invariant. -
Message-passing concurrency instead of shared mutation.
extras/tauri/crates/tauri-runtime-wry/src/lib.rsfunnels all window operations throughpub enum Message<T: 'static>andsend_user_message, with agetter!/window_getter!/webview_getter!macro family that packages a oneshot channel into the message and blocks on the reply. Shared state that must be mutated (AppManagerinextras/tauri/crates/tauri/src/manager/mod.rs) uses plainMutexfields per concern (plugins: Mutex<PluginStore<R>>,resources_table: Arc<Mutex<ResourceTable>>) rather than one god lock. -
Build-script cfg aliases with check-cfg registration.
extras/tauri/crates/tauri/build.rsdefines readable platform predicates once:fn alias(alias: &str, has_feature: bool) { println!("cargo:rustc-check-cfg=cfg({alias})"); ... } let mobile = target_os == "ios" || target_os == "android"; alias("desktop", !mobile); alias("mobile", mobile);
so the code base writes
#[cfg(desktop)],#[cfg(mobile)], and#[cfg(dev)]instead of repeating target lists, andrustc-check-cfgkeepsunexpected_cfgsclean. -
Runtime resource tables with checked Arc downcasting.
extras/tauri/crates/tauri/src/resources/mod.rsdefinespub trait Resource: Any + 'static + Send + Syncwith aclose(self: Arc<Self>)hook, and adowncast_arcthat pointer-casts&Arc<dyn Resource>to&Arc<T>only after aself.is::<T>()TypeId check, a pattern adopted from Deno's resource table for JS-held handles to Rust objects. -
Measured performance thresholds instead of folklore.
extras/tauri/crates/tauri/src/ipc/format_callback.rsswitches serialized payloads toJSON.parse('...')only aboveconst MIN_JSON_PARSE_LEN: usize = 10_240;, documents the browser string limits with sourced comments (MAX_JSON_STR_LEN = 2^30 - 2), takes a closure parameter "to avoid unnecessary allocations", and guards the size assumption with a#[cfg(debug_assertions)]assert.
Rustdoc is treated as a product surface. extras/tauri/crates/tauri/src/lib.rs opens with a
crate doc that enumerates every Cargo feature with its default status and consequences, sets a
branded #![doc(html_logo_url = ..., html_favicon_url = ...)], and enables
#![cfg_attr(docsrs, feature(doc_cfg))] so feature-gated items render their requirements
(#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))] throughout
extras/tauri/crates/tauri-runtime/src/lib.rs). missing_docs is warned at crate level in the
library crates, and doc examples are runnable (the test module example builds an app against
the mock runtime). Docs.rs rendering is configured per crate via [package.metadata.docs.rs]
with five targets.
Repo-level documents divide by audience: extras/tauri/ARCHITECTURE.md for orientation (with an
explicit "What Tauri is NOT" section), extras/tauri/.github/CONTRIBUTING.md for process
(issue triage rules, signed-commit requirement, per-package development guides),
extras/tauri/.github/RELEASING.md as a maintainer runbook including a step-by-step recovery
procedure titled "Publishing failed, what to do?", and extras/tauri/SECURITY.md routing
disclosures through GitHub private vulnerability reporting with a 90-day publication target. The
.changes/README.md documents the change-file format contributors must follow. Issue intake is
structured YAML forms (extras/tauri/.github/ISSUE_TEMPLATE/bug_report.yml requires a
reproduction and the full tauri info output; config.yml diverts questions to Discord), and
extras/tauri/.github/PULL_REQUEST_TEMPLATE.md teaches title conventions by example, good and
bad. Two commissioned security audit reports are committed under extras/tauri/audits/.
Versioning is per-crate semver orchestrated by covector. Every user-visible PR adds a markdown
file to extras/tauri/.changes/ whose frontmatter names the packages and the bump with a change
tag, e.g. extras/tauri/.changes/build-config-path.md:
---
"tauri-build": minor:feat
---
Added `Attributes::config_path` to customize config path, deprecated `CodegenContext::config_path` in favor of thisextras/tauri/.changes/config.json maps tags (feat, enhance, bug, perf, sec, deps,
breaking) to changelog headings, and defines the publish pipeline per package manager,
including a prepublish hook that runs cargo audit and embeds its output in the release notes.
CI enforces the discipline twice: covector-status.yml comments the pending bump on every PR,
and check-change-tags.yml rejects malformed change files.
On every push to dev, extras/tauri/.github/workflows/covector-version-or-publish.yml first
runs the cross-platform integration suite, then either opens/updates a signed-commit
"Apply Version Updates From Current Changes" PR (version mode) or publishes to crates.io and npm
(publish mode) with GitHub releases (createRelease: true) and npm provenance
(NPM_CONFIG_PROVENANCE: true, id-token: write). Successful publishes fan out via
repository_dispatch and gh workflow run to publish-cli-rs.yml (prebuilt cargo-tauri
binaries for six targets including riscv64gc-unknown-linux-gnu and Windows ARM),
publish-cli-js.yml (napi binaries for the npm CLI), and a docs-repo update event.
Distribution details worth copying: extras/tauri/crates/tauri-cli/Cargo.toml ships
[package.metadata.binstall] templates so cargo binstall tauri-cli fetches the GitHub release
artifact instead of compiling, with per-target pkg-fmt overrides. Shell completions are a
first-class subcommand: extras/tauri/crates/tauri-cli/src/completions.rs uses clap_complete
to emit Bash, Zsh, PowerShell, and Fish scripts, and generates them for each invocation wrapper
(cargo tauri, pnpm tauri, npm run tauri, deno task tauri) by synthesizing nested clap
Command trees per package manager.
quinjet already covers rustfmt, a maximal clippy wall, cargo-deny, taplo, typos, coverage, miri, and mutants. The practices below are the ones tauri demonstrates that are still missing or partially covered, each with its mechanism.
-
Add cargo-vet on top of cargo-deny.
cargo install cargo-vet,cargo vet init, then import the same audit sets tauri does inextras/tauri/supply-chain/config.toml([imports.mozilla] url = "https://raw.githubusercontent.com/mozilla/supply-chain/main/audits.toml", plus google, bytecode-alliance, embark-studios, isrg, zcash). Runcargo vet --lockedin CI; commitsupply-chain/{config.toml,audits.toml,imports.lock}. -
Run security audits on a schedule, not only on change. Tauri's
extras/tauri/.github/workflows/audit.ymluseson.schedule: cron: '0 0 * * *'plus lockfile-path triggers withrustsec/audit-check@v2. quinjet can add a dailyscheduletrigger to its cargo-deny workflow so a freshly published RUSTSEC advisory fails the repo within a day even with no commits. -
Version the advisory ignore list with reasons. Mirror
extras/tauri/.cargo/audit.toml: every ignored id gets an inline justification and, where possible, the removal condition ("fixed when we remove kuchikiki from deps in v3"). -
Cancel superseded CI runs and slim the cache. Add to every workflow:
concurrency: { group: "${{ github.workflow }}-${{ github.ref }}", cancel-in-progress: true }andenv: CARGO_PROFILE_DEV_DEBUG: 0; cache withSwatinem/rust-cache@v2, and if any matrix exists, gate cache writes withsave-if:the wayextras/tauri/.github/workflows/test-core.ymlonly saves from the--all-featuresleg. -
Pin the MSRV in CI as an exact toolchain. Tauri sets
rust-version = "1.90"in[workspace.package]and tests withdtolnay/rust-toolchain@1.90/toolchain: '1.90'(extras/tauri/.github/workflows/test-cli-rs.yml). quinjet should add one job that builds and tests ondtolnay/rust-toolchain@<rust-version>so therust-versionkey in Cargo.toml is enforced, not decorative. -
Add a cargo-udeps job. Nightly toolchain plus
cargo udeps --all-targets --all-featuresas inextras/tauri/.github/workflows/udeps.yml; for a single crate no matrix is needed, and known false positives go in[package.metadata.cargo-udeps.ignore]as inextras/tauri/crates/tauri/Cargo.toml. -
Ship a size-tuned release profile. Copy the workspace profile from
extras/tauri/Cargo.toml:panic = "abort",codegen-units = 1,lto = true,opt-level = "s"(or3if TUI redraw speed matters more than size),strip = true,incremental = false. For a Git TUI installed by users, binary size and no-backtrace abort semantics are the right defaults. -
Add
[package.metadata.binstall]and release artifacts. Followextras/tauri/crates/tauri-cli/Cargo.toml: apkg-urltemplate pointing at GitHub release tarballs plus per-targetpkg-fmtoverrides, and a release workflow that uploadsquinjet-<target>.tgz/.zipper platform (matrix as inextras/tauri/.github/workflows/publish-cli-rs.yml), socargo binstall quinjetworks. -
Make completions a subcommand, not a build artifact. Use
clap_complete::generatebehind aquinjet completions --shell <shell> [--output <file>]subcommand exactly asextras/tauri/crates/tauri-cli/src/completions.rsdoes, defaulting to stdout and using the fs-context error helper for the file path case. -
Adopt insta snapshot tests for command output and TUI frames. Add
instaas a dev-dependency, snapshotratatui::backend::TestBackendbuffers and CLI subcommand stdout, and useinsta::Settings::set_snapshot_pathfor any platform-divergent output the wayextras/tauri/crates/tests/acl/src/lib.rsroutes snapshots perTarget::current(). -
Property-test the parsing layers. quinjet parses refnames, revision expressions, and keybinding specs; give them
proptest!blocks with elevated case counts (ProptestConfig::with_cases(10000)as inextras/tauri/crates/tauri/src/event/listener.rs) and quickcheckArbitraryimpls for domain newtypes as inextras/tauri/crates/tauri/src/ipc/format_callback.rs. -
Add a real process-level integration test. Model it on
extras/tauri/crates/tests/restart/tests/restart.rs: run the builtquinjetbinary withstd::process::Commandinside atempfile::TempDircontaining a scripted Git repository, and assert on stdout/stderr and exit codes for each CLI subcommand. This tests the actual public surface, including argv parsing and exit discipline, which unit tests cannot. -
Enforce release-note discipline in CI. Even single-crate, the covector pattern transfers: a
.changes/*.mdfile per user-visible PR with a bump tag taxonomy (extras/tauri/.changes/config.jsontags: feat, enhance, bug, perf, sec, deps, breaking), a PR check that a change file exists and its tags are valid (extras/tauri/.github/workflows/check-change-tags.ymlplusextras/tauri/.scripts/ci/check-change-tags.js), and changelog generation at release time. git-cliff with commit conventions is an acceptable single-crate substitute, but the check must run on PRs, not at release. -
Keep generated files honest with a diff check. If quinjet ever commits generated artifacts (default keymap docs, config schema, wiki pages), regenerate them in CI and fail on
git diffnon-empty via a two-line script likeextras/tauri/.scripts/ci/has-diff.sh, triggered only when the sources change (dorny/paths-filter@v3). -
Use
.cargo/config.toml[env]for test-environment quirks instead of Makefile exports. Tauri sets__TAURI_WORKSPACE__ = "true"there with a comment linking the issue it works around (extras/tauri/.cargo/config.toml); the same slot suits quinjet variables like a deterministicGIT_AUTHOR_DATEfor snapshot-stable test repositories. -
Split update automation from update security. Configure Renovate with
"minimumReleaseAge": "3 days"and grouped ecosystem rules as inextras/tauri/renovate.json, and if dependabot stays enabled, setopen-pull-requests-limit: 0as inextras/tauri/dependabot.ymlso it only surfaces security alerts. -
Mark the public error enum
#[non_exhaustive]and gate variants by cfg. If quinjet's library-side error enum is exposed for scripting or plugins, followextras/tauri/crates/tauri/src/error.rs:#[non_exhaustive], one display string per variant,#[from]conversions only where the source is unambiguous, and feature/platform cfg on variants that do not exist everywhere. -
Demote noisy third-party log targets, not the global level. The CLI's logger in
extras/tauri/crates/tauri-cli/src/lib.rsapplies.filter(Some("handlebars"), verbosity_level(n.saturating_sub(1)).to_level_filter())per chatty crate with a comment explaining each; quinjet's tracing/env_logger setup can carry the same per-target demotions for git2 or other verbose dependencies.
Deno is a JavaScript, TypeScript, and WebAssembly runtime built on V8, Rust,
and Tokio, shipped as a single deno executable that bundles a package
manager, formatter, linter, test runner, LSP, bundler, and compiler. The
README states the pitch directly (extras/deno/README.md):
[Deno](https://deno.com) ... is a JavaScript, TypeScript, and WebAssembly
runtime with secure defaults and a great developer experience. It's built on
[V8](https://v8.dev/), [Rust](https://www.rust-lang.org/), and
[Tokio](https://tokio.rs/).
Industry uses it because it is a security-first Node alternative with permissions on by default, first-class TypeScript, and a batteries-included toolchain, all delivered as one static binary.
Scale, measured on this clone:
- 1045
.rsfiles totaling about 670,000 lines of Rust, about 600,000 of which are outsidetests/(counted withwc -lover the tree). - 87
Cargo.tomlmanifests; the root workspace declares 77 explicit members in extras/deno/Cargo.toml, spanningcli/, 27ext/*extension crates, 28libs/*support crates,runtime/, and the test crates undertests/. - 2087
__test__.jsoncspec-test manifests under extras/deno/tests/specs. - The CLI crate is at version 2.9.5 (extras/deno/cli/Cargo.toml) and the changelog extras/deno/Releases.md is 659 KB of release history.
- The generated main CI workflow alone is 7676 lines (extras/deno/.github/workflows/ci.generated.yml).
Top level of the clone (directories only, ASCII tree):
extras/deno/
|-- cli/ the `deno` crate: flags, subcommands, tools, LSP, snapshot
| |-- lib/ deno_lib shared library
| |-- rt/ denort, the slim runtime used by `deno compile` binaries
| |-- rt_desktop/ desktop variant of denort
| `-- snapshot/ build-time V8 snapshot crate
|-- runtime/ deno_runtime: assembles extensions into a JS runtime
| |-- permissions/ deno_permissions crate
| |-- features/ feature-flag crate
| `-- subprocess_windows/ Windows-only process handling crate
|-- ext/ one crate per capability exposed to JS (fs, net, web, ...)
|-- libs/ deno_core, serde_v8, ops macros, resolver, npm, config, ...
|-- tests/ all integration-level testing (specs, unit, wpt, bench, util)
|-- tools/ repo automation: format.js, lint.js, release/, x.ts
|-- doc/ contributor-facing architecture and process docs
`-- .github/ workflows (generated), templates, mtime_cache action
The split is layered and the layering is documented as a hard rule in extras/deno/doc/architecture.md:
+-----------------------------------------------------------+
| cli/ the `deno` binary: subcommands, tooling |
+-----------------------------------------------------------+
| runtime/ deno_runtime: assembles the JS runtime |
+-----------------------------------------------------------+
| ext/* extensions: native capabilities for JS |
+-----------------------------------------------------------+
| libs/* deno_core + supporting crates (V8 bridge) |
+-----------------------------------------------------------+
| V8 + Tokio JavaScript engine and async runtime |
+-----------------------------------------------------------+
Each layer depends only on layers below it, which keeps lower layers
publishable and reusable (deno_runtime, deno_core, and every ext/*
crate are published to crates.io with independent versions, see the
[workspace.dependencies] path entries in extras/deno/Cargo.toml). The
layout is actively defended: ensureNoNewTopLevelEntries() in
extras/deno/tools/lint.js fails CI if a new top-level file or directory
appears outside an allowlist, with the comment
// WARNING: When adding anything to this list it must be discussed!.
There is also a one-letter developer entry point, extras/deno/x:
#!/usr/bin/env -S deno run --allow-all --ext=ts
import "./tools/x.ts";so ./x fmt, ./x lint, ./x spec are the canonical commands
(documented in extras/deno/.github/CONTRIBUTING.md). A Nix flake
(extras/deno/flake.nix) provides a reproducible dev shell and build.
The root extras/deno/Cargo.toml is the single source of truth for shared metadata and versions:
-
[workspace.package]carriesauthors,edition = "2024",license = "MIT", andrepository; member crates inherit withedition.workspace = trueand friends (see extras/deno/cli/Cargo.toml). -
[workspace.dependencies]holds every third-party version, grouped by concern with section comments:# exts,# workspace libraries,# widely used libraries,# cli,# crypto,# ffi,# napi,# macros,# unix deps,# windows deps. - Risky dependencies are pinned exactly (
base32 = "=0.5.1",rand = "=0.8.5",rustls = { version = "=0.23.40", ... }) and every pin carries a reason as a comment, for example:
pin-project = "1.0.11" # don't pin because they yank crates from cargo
reqwest = { version = "=0.12.5", ... } # pinned because of https://github.com/seanmonstar/reqwest/pull/1955- Footgun avoidance is written into the dependency table itself:
# Note: Do not use the "clock" feature of chrono, as it links us to CoreFoundation on macOS.
# Instead use util::time::utc_now()
chrono = { version = "0.4", default-features = false, features = ["std", "serde"] }- Feature flags in extras/deno/cli/Cargo.toml model real product variants:
default = ["v8"], an experimentalquickjsengine backend,hmrfor snapshot-free development,dhat-heapfor heap profiling,upgrade(disabled by Linux distro packagers), and private helper features spelled with a double underscore (__runtime_defaults,__vendored_zlib_ng) to signal they are not public API. -
[lints]tables are used sparingly and precisely: extras/deno/runtime/Cargo.toml and extras/deno/ext/ffi/Cargo.toml declareunexpected_cfgs = { level = "warn", check-cfg = ['cfg(tokio_unstable)'] }so custom--cfgflags stay checked. - Profiles are tuned aggressively.
releaseusescodegen-units = 1,lto = true,opt-level = 'z',panic = "abort",split-debuginfo = "packed",debug = "line-tables-only", and the file warns twice, "NB: the bench and release profiles must remain EXACTLY the same." About 50[profile.release.package.*]overrides re-enableopt-level = 3for hot crates (tokio, hyper, v8, serde, zstd, ...), so the binary is small overall but fast where it matters. A customrelease-liteprofile (incremental,codegen-units = 128,lto = "thin") exists purely for local iteration, and dev-profile overrides fix pathological cases ([profile.dev.package.v8]opt-level = 1with the comment# rusty-v8 needs at least -O1 to not miscompile). - There is no
rust-versionkey; the toolchain is pinned instead in extras/deno/rust-toolchain.toml:
[toolchain]
channel = "1.95.0"
components = ["rustfmt", "clippy", "rust-src", "rust-analyzer"]- extras/deno/.cargo/config.toml carries per-target
rustflags(static CRT on Windows, a 4 MB main-thread stack reserve vialink-arg=/STACK:4194304, linker ICF and chained fixups on macOS) with long comments explaining the measured effect of each flag. - extras/deno/.cargo/local-build.toml is a checked-in
[patch.crates-io]overlay for developing against sibling checkouts ofdeno_coreandrusty_v8, activated withcargo --config .cargo/local-build.toml build. -
Cargo.lockis committed and CI test runs use--locked.
extras/deno/.rustfmt.toml is three lines:
max_width = 80
tab_spaces = 2
edition = "2024"80 columns and 2-space indent match the JS/TS style so the polyglot codebase reads uniformly. The interesting part is that rustfmt is not invoked directly: dprint orchestrates every formatter through extras/deno/.dprint.json, including Rust via the exec plugin:
"exec": {
"cwd": "${configDir}",
"commands": [{
"command": "rustfmt --config imports_granularity=item --config group_imports=StdExternalCrate",
"exts": ["rs"],
"cacheKeyFiles": ["rust-toolchain.toml", ".rustfmt.toml"]
}]
}Two unstable rustfmt options are injected on the command line: one import
per use item and std/external/crate import grouping, which makes import
diffs trivially mergeable. The same file configures dprint plugins for
TypeScript, JSON, Markdown, TOML, and YAML, plus a large excludes list of
vendored and fixture files. tools/format.js runs it all;
deno run ... ./tools/format.js --check is a CI lint step.
extras/deno/.editorconfig sets lf, final newline, 2-space indent, UTF-8,
and trimmed whitespace globally, then carves out test fixtures where
byte-exactness matters:
[*.out] # make editor neutral to .out files
insert_final_newline = unset
trim_trailing_whitespace = unsetLine endings are also normalized at the git layer
(extras/deno/.gitattributes: * text=auto eol=lf, with one file forced to
eol=crlf for a Windows-specific test).
Clippy configuration lives in three cooperating places.
First, workspace-wide hard denials in extras/deno/.cargo/config.toml, which
apply to every local cargo build, not only CI:
[target.'cfg(all())']
rustflags = [
"-D", "clippy::all",
"-D", "clippy::await_holding_refcell_ref",
"-D", "clippy::missing_safety_doc",
"-D", "clippy::undocumented_unsafe_blocks",
"--cfg", "tokio_unstable",
]Second, the CI lint driver extras/deno/tools/lint.js appends more denials when it invokes clippy:
"--deny", "clippy::unused_async",
"--deny", "clippy::print_stderr",
"--deny", "clippy::print_stdout",
"--deny", "clippy::large_futures",
"--deny", "clippy::allow_attributes_without_reason",print_stdout/print_stderr are banned because the std print macros panic
on EPIPE (see section 8), large_futures protects the single-threaded
runtime's stack, and allow_attributes_without_reason forces every escape
hatch to justify itself, e.g. in extras/deno/cli/lib.rs:
#[allow(clippy::disallowed_types, reason = "definition")]. The driver even
post-processes clippy output: when a print-macro violation appears it prints
a hint pointing at drop_println! replacements.
Third, per-crate clippy.toml files (61 of them) use disallowed-methods
and disallowed-types as an architectural boundary enforcement tool.
extras/deno/cli/clippy.toml bans ambient process state:
{ path = "std::process::exit", reason = "use deno_runtime::exit instead" },
{ path = "std::env::current_dir", reason = "use crate::util::env::resolve_cwd instead and prefer passing it the initial_cwd" },
{ path = "reqwest::Client::new", reason = "create an HttpClient via an HttpClientProvider instead" },extras/deno/libs/core/clippy.toml bans nearly all of std::fs, std::env,
std::time::SystemTime::now, and chrono::Utc::now in favor of the
sys_traits capability traits, so lower layers stay testable and Wasm-safe.
The philosophy: clippy is not just style, it is a mechanized code review
that encodes project-specific invariants, and every rule states its
replacement in the reason field.
Custom lint infrastructure goes further. extras/deno/tools/lint.js also
runs: deno lint over JS/TS with custom plugin rules
(tools/lint_plugins/prefer_primordials.ts for runtime bootstrap code,
no_deno_api_in_polyfills.ts with per-file expected violation counts), a
copyright header check (tools/copyright_checker.js), a check that every
generated workflow YAML matches its generator
(ensureWorkflowYmlsUpToDate()), a check that no .out fixture is
unreferenced (ensureNoUnusedOutFiles()), a top-level directory allowlist,
a rule that every ext/ and libs/ crate has a clippy.toml with the
required disallowed methods (ensureDisallowedMethodsEnforced()), and a
CLI-design rule that uppercase short flags are reserved for permissions
(ensureNoNonPermissionCapitalLetterShortFlags()), asserted against the
actual parser tables in libs/cli_parser/src/defs.rs.
Every workflow under extras/deno/.github/workflows exists twice: a
TypeScript generator (ci.ts, pr.ts, npm_publish.ts, ...) and its
output (*.generated.yml), each headed
# GENERATED BY ./ci.ts -- DO NOT DIRECTLY EDIT. The generators use a
typed workflow-builder library (jsr:@david/gagen in
extras/deno/.github/workflows/ci.ts), so 2260 lines of TypeScript with
loops, shared step factories, and typed conditions produce the 7676-line
ci.generated.yml. Drift is impossible because tools/lint.js re-runs
every generator with --lint and fails if the YAML is stale.
Action pinning is automatic: the generator resolves tags to commit SHAs and records the mapping as trailing comments, e.g. in ci.generated.yml:
# gagen:pin actions/checkout@v6 = de0fac2e4500dabe0009e67214ff5f5447ce83dd
# gagen:pin dtolnay/rust-toolchain@master = 3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9The main ci workflow (push to main/tags, pull_request) contains 39 jobs:
-
pre_buildgates everything: draft PRs skip CI unless the commit message contains[ci]or the PR has theci-draftlabel; scriptstools/check_deno_core_changes.jsandtools/check_docs_only_changes.jspublishskip_deno_core_testanddocs_onlyoutputs that downstreamif:conditions consume. - Build and test are split per platform with artifact handoff: six targets
(linux/macos/windows, each x86_64 and aarch64) times debug and release,
with
build-*jobs uploadingdeno,denort, andtest-serverartifacts that shardedtest-*jobs download. Runner labels are chosen conditionally: XL runners only fordenoland/denoon main, tags, or theci-fulllabel (extras/deno/.github/workflows/ci.ts,Runners). - Test jobs are sharded per test crate on PRs (
CI_SHARD_INDEX/CI_SHARD_TOTALenv vars), and the shard list is computed by parsing the workspaceCargo.tomlat generation time (resolveTestCrateTests()). -
wpt-release-linux-x86_64runs the Web Platform Tests plus the Autobahn websocket fuzzing suite and uploads results to wpt.fyi. -
deno-core-testanddeno-core-mirirun the engine crates separately; Miri runs on a pinned nightly (nightly-2025-11-12) withcargo miri test -p deno_core --features v8. -
lintruns on a 3-OS matrix (linux, macos, windows) so platform-conditional code is linted on every platform, with format and jsdoc checks only on linux. -
ci-statusis the single aggregator job branch protection keys on:
- name: Ensure CI success
run: |-
if [[ "${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
echo 'CI failed'
exit 1
fi-
publish-canaryuploadscanary-latest.txttodl.deno.landon every main push, so a canary build exists for every commit.
Caching is deliberate: a manual cacheVersion = 123 constant busts all
caches at once; cargo-home and target caches are restored by prefix
(key: never_saved plus restore-keys) but saved only on main with
key: <prefix>-${{ github.sha }} so PRs always restore the freshest main
cache, and a custom local action extras/deno/.github/mtime_cache restores
file mtimes so cargo's change detection works across cache restores. Every
job sets timeout-minutes, and the workflow-level concurrency group
cancels superseded runs except when the ci-test-flaky label asks runs to
be kept. There is even a step-level workaround pinned in every job:
Pre-install rustup 1.28.2 (workaround broken 1.29.0).
Other workflows: pr lints PR titles against conventional-commit rules
(tools/verify_pr_title.js), node_compat_test runs Node's own suite
daily on a 3-shard linux/windows/macos matrix (cron 0 10 * * *),
ecosystem_compat_test runs weekday crons against real-world frameworks,
and five release workflows are described in section 11. There is no merge
queue configuration in the repo; the ci-status job is the required check.
The test tree is a top-level concern, not a per-crate afterthought.
extras/deno/doc/testing.md maps the suites: spec tests (tests/specs/, the
main CLI end-to-end suite), JS unit tests (tests/unit/), Node compat
layers (tests/unit_node/, tests/node_compat/ running Node's own suite
from a submodule), Web Platform Tests (tests/wpt/, submodule), and Rust
unit tests inline in each crate.
Spec tests are the standout design. Each of the 2087 directories under
extras/deno/tests/specs holds a __test__.jsonc manifest (validated by
#[serde(deny_unknown_fields)] structs in extras/deno/tests/specs/mod.rs
and a JSON schema at tests/specs/schema.json) describing steps: a CLI
invocation, an expected output (inline or a .out file), env vars, and a
temp_dir flag. Expected output uses a purpose-built matching language
implemented in extras/deno/tests/util/lib/wildcard.rs: [WILDCARD],
[WILDLINE], [WILDCHARS(n)], [UNORDERED_START]/[UNORDERED_END] for
nondeterministic ordering, and [# comment] lines. The runner is a custom
harness (harness = false in extras/deno/tests/specs/Cargo.toml) built on
the file_test_runner crate, with a FlakyTestTracker
(tests/util/lib/test_runner.rs) that records and retries flaky tests, and
PR-only sharding driven by CI_SHARD_INDEX.
The helper crate extras/deno/tests/util/lib is a full testing SDK:
PathRef (a newtype over PathBuf with assertion helpers),
TestContextBuilder (a builder that provisions temp dirs, env vars, and
local registries: TestContextBuilder::for_npm() spins up the mock npm
registry), a PTY driver (tests/util/lib/pty.rs) for testing the REPL and
interactive prompts against a real terminal, and wildcard assertion
functions. extras/deno/tests/util/server hosts an entire fake internet:
mock npm and JSR registries, a Node.js download mirror, gRPC, websocket,
and TLS servers (tests/util/server/servers/).
Beyond example-based testing:
- Property testing: extras/deno/runtime/permissions/lib.rs has a
proptestsmodule usingproptestto verify algebraic laws of the permission system, e.g.net_descriptor_ord_transitivityproving the manualOrdis transitive, andnet_query_never_granted_when_flag_deniedproving a security invariant over arbitrary allow/deny sets. - Fuzzing: extras/deno/libs/npm/fuzz is a
cargo-fuzzcrate (libfuzzer-sys, targetfuzz_targets/packument_index.rs) for npm registry metadata parsing. - Miri: the
deno-core-miriCI job (section 6) runs the engine under Miri. - Benchmarks: extras/deno/tests/bench is a dedicated crate with
harness = falsebenches (deno_bench,lsp_bench_standalone) that measure the real built binary (startup, HTTP throughput via installedwrk/hyperfine, LSP timings) and publish results to agh-pagesbenchmark site from thebenchCI job.
Error types are structured enums via thiserror 2, with an extra derive,
deno_error::JsError, that maps each Rust variant to the JavaScript error
class users see (extras/deno/ext/fs/ops.rs):
#[derive(Debug, Boxed, deno_error::JsError)]
pub struct FsOpsError(pub Box<FsOpsErrorKind>);
#[derive(Debug, thiserror::Error, deno_error::JsError)]
pub enum FsOpsErrorKind {
#[class(inherit)]
#[error("{0}")]
Io(#[source] std::io::Error),
...
#[class("InvalidData")]
#[error("File name or path {0:?} is not valid UTF-8")]
InvalidUtf8(std::ffi::OsString),
#[class(type)]
#[error("Invalid seek mode: {0}")]
InvalidSeekMode(i32),The Boxed derive (the boxed_error crate) wraps the large kind enum in a
one-pointer struct so Result<T, FsOpsError> stays cheap to return. At the
CLI boundary, anyhow-style AnyError (re-exported by deno_core) is used
for aggregation, and downcasting recovers structure: exit_for_error in
extras/deno/cli/lib.rs downcasts to JS errors for pretty formatting and
appends context-aware hints before exiting with code 1.
Result discipline is enforced by a small conversion trait (extras/deno/cli/lib.rs):
/// Ensures that all subcommands return an i32 exit code and an [`AnyError`] error type.
trait SubcommandOutput {
fn output(self) -> Result<i32, AnyError>;
}so every subcommand funnels into one Result<i32, AnyError> shape, and the
process exits exactly once through deno_runtime::exit(exit_code);
std::process::exit is clippy-banned (section 5). Panic policy: release
profiles use panic = "abort", an optional panic-trace feature wires a
custom panic backtrace handler (extras/deno/cli/Cargo.toml), and the
EPIPE-panic of the std print macros is designed away by
extras/deno/libs/print/lib.rs:
//! Replacements for the std `print!`, `println!`, `eprint!` and `eprintln!`
//! macros that drop write errors instead of panicking, named after Cargo's
//! macros with the same semantics.
API-design patterns visible throughout: builders with chained self
methods (TestContextBuilder in extras/deno/tests/util/lib/builders.rs),
security newtypes with private fields
(CheckedPath in extras/deno/runtime/permissions/lib.rs, section 9),
visibility discipline like the pub(crate) mod sys alias that is the only
allowed spelling of the real filesystem in the CLI
(extras/deno/cli/lib.rs), and #[doc(hidden)] on internals re-exported
only for benchmarks.
-
Proc-macro ops with typed marshaling. The
#[op2]attribute (extras/deno/libs/ops) turns a plain Rust function into a V8 binding; argument attributes choose the marshaling strategy andfastopts into V8 fast-calls (extras/deno/ext/web/lib.rs):#[op2(fast)] fn op_base64_decode_into( #[string(onebyte)] input: Cow<[u8]>, #[buffer] target: &mut [u8], #[smi] offset: u32, ) -> Result<i32, WebError> {
-
Declarative registration macros.
deno_core::extension!(deno_web, deps = [deno_webidl], ops = [op_base64_decode, ...])(extras/deno/ext/web/lib.rs line 71) assembles ops, JS sources, and state into anExtensionat compile time, keeping registration impossible to get out of sync with definitions. -
Zero-copy
Coweverywhere: 530Cow<occurrences incli,libs, andext. The op above receives V8 one-byte strings asCow<[u8]>without copying when the representation already matches, and theResourcetrait returnsCow<'_, str>for names. -
Newtypes with lifetime-encoded guarantees. Permission checking returns
CheckedPath<'a>/CheckedPathBuf(extras/deno/runtime/permissions/lib.rs):pub struct CheckedPath<'a> { // these are private to prevent someone constructing this outside the crate path: PathWithRequested<'a>, canonicalized: bool, }
Filesystem ops take
CheckedPath, notPath, so an unchecked path is a type error; the borrowed/owned pair mirrorsPath/PathBufand the escape hatch is loudly namedunsafe_new. -
Compile-time sync/unsync polymorphism. extras/deno/libs/maybe_sync/lib.rs defines
MaybeSend/MaybeSync/MaybeArc/MaybeDashMap: with thesyncfeature they aliasSend/Sync/Arc/DashMap; without it they become no-op traits,Rc, and aRefCell<HashMap>wrapper. Shared crates are written once against theMaybe*names and each consumer picks thread-safety at feature-resolution time, paying zero cost. -
Single-threaded async architecture. The whole runtime runs on a current-thread Tokio runtime (extras/deno/runtime/tokio_util.rs,
tokio::runtime::Builder::new_current_thread()), so op state isRc<RefCell<OpState>>(265Rc<RefCell<occurrences under ext/) instead ofArc<Mutex>, andclippy::await_holding_refcell_refis a hard deny to keep that safe.spawn_subcommandin extras/deno/cli/lib.rs pairs this with.boxed_local()and documents why: giant subcommand futures would otherwise blow the stack in debug builds. -
Object-safe async resource trait.
pub trait Resource: Any + 'static(extras/deno/libs/core/io/resource.rs) usesself: Rc<Self>receivers returning boxed futures, default methods that error with "not supported", and an opt-inread_byobfast path, giving JS a uniform handle table over files, sockets, and streams. -
Static data over runtime construction. The CLI parser (extras/deno/libs/cli_parser/src/types.rs) models the entire command tree as
consttables:pub struct CommandDef { pub name: &'static str, pub about: &'static str, pub aliases: &'static [&'static str], pub args: &'static [ArgDef], ... }
Parsing, help rendering, and shell completions (libs/cli_parser/src/completions.rs) all walk the same static tables, so startup does no allocation to build a parser and help/completions can never disagree with parsing.
-
Property-based verification of unsafe-to-get-wrong logic. The permissions crate proves
Ordtransitivity and deny-precedence withproptestgenerators over descriptor types (extras/deno/runtime/permissions/lib.rs,mod proptests), an idiom worth copying wherever a manualOrd/matching implementation guards security decisions. -
Audited unsafe. 1497
SAFETY:comments repo-wide, and the comments are not optional:clippy::undocumented_unsafe_blocksandclippy::missing_safety_docare denied workspace-wide in extras/deno/.cargo/config.toml, so everyunsafeblock ships with its justification or the build fails. -
Platform handling as structure, not scatter. Windows-only process code is a separate crate (extras/deno/runtime/subprocess_windows), Windows deps are scoped per crate with minimal feature lists (
[target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [...] }in extras/deno/ext/ffi/Cargo.toml), and custom cfgs are registered viacheck-cfglints so typos in#[cfg]warn (extras/deno/runtime/Cargo.toml). -
Macro-by-example for policy, not cleverness. The
drop_println!family (extras/deno/libs/print/lib.rs) is a five-line macro that encodes an OS-level policy (EPIPE tolerance), paired with the clippy denial that forces its use; the macro, the lint, and the CI hint form one closed loop.
- In-repo contributor docs live in extras/deno/doc:
architecture.md(the layer diagram and dependency rules),ci.md(how the generated CI works and its gating outputs),codebase-map.md,testing.md(which suite to reach for and when),package-management.md, anddesktop-architecture.md. These are short, current, and referenced by CI itself (the docs-only fast path in section 6 keys ondoc/). - Rustdoc is used at API boundaries with real contracts: module docs like
the
//!header of extras/deno/libs/print/lib.rs explain the why (SIGPIPE semantics, links to the tracking issue), and trait docs in extras/deno/libs/core/io/resource.rs specify default-method behavior and when to override (read_byob). - Every source file opens with a license header,
// Copyright 2018-2026 the Deno authors. MIT license., enforced by extras/deno/tools/copyright_checker.js in CI. - extras/deno/.github/CONTRIBUTING.md documents prerequisites, the
./xtool, and HMR-based iteration; extras/deno/.github/PULL_REQUEST_TEMPLATE.md demands conventional-commit titles with good/bad examples (fix(ext/net): fix race condition in TCP listenervsfix #7123), and theprworkflow lints the title mechanically. - Issue templates (extras/deno/.github/ISSUE_TEMPLATE:
bug_report.md,feature_request.md,config.yml) route support questions elsewhere. - Many crates carry their own
README.md(e.g. extras/deno/ext/url/README.md, extras/deno/libs/core/README.md) because they publish independently.
Versioning: the CLI is semver (2.9.5), and every publishable workspace
crate carries its own version in the root [workspace.dependencies] table
(extras/deno/Cargo.toml), bumped together by tooling. The changelog,
extras/deno/Releases.md, is one bullet per merged PR in conventional-commit
form with PR numbers, per release:
### 2.9.5 / 2026.08.06
- feat(add): `--unscoped` flag to alias packages by their unscoped name (#36319)
- feat(task): add --members flag to run tasks in workspace members only (#35748)The release pipeline is a chain of workflow_dispatch workflows backed by
numbered scripts in extras/deno/tools/release
(00_start_release.ts through 05_create_release_notes.ts, with the
runbook in extras/deno/tools/cut_a_release.md):
-
start_releasetakes patch/minor/major input and generates a gist of step-by-step instructions for the release captain. -
version_bumpbumps all crate versions (also patching the CIcacheVersionby regex) and opens a PR as a bot. -
cargo_publishpublishes the crates and tags. -
promote_to_releasepromotes a canary build torcor re-stamps a stable build asltsusing apatchverbinary-patching tool, then code signsdeno.exewith Azure Trusted Signing and verifies withsigntool(extras/deno/.github/workflows/promote_to_release.generated.yml). -
npm_publish(triggered byrelease: published, with adry_run: default: trueinput) wraps the binaries into npm packages.
Distribution is multi-channel: GitHub Releases archives, dl.deno.land
(with a canary for every main commit via the publish-canary job), npm,
and an in-binary deno upgrade subcommand that distro packagers can
compile out by disabling the upgrade feature
(extras/deno/cli/Cargo.toml: # This is typically disabled for (Linux) distribution packages.). Shell completions are first-class: static
generation plus dynamic completion where the shell calls back into the
binary with COMPLETE=<shell> set, including live deno task name
completion (extras/deno/cli/args/flags.rs, handle_shell_completion and
handle_dynamic_shell_completion).
quinjet already has a strict clippy wall, rustfmt, cargo-deny, taplo, typos, coverage, miri, and mutants. What Deno adds on top of that:
- Adopt
clippy.tomldisallowed-methods/disallowed-typesas architecture enforcement, not just hygiene. quinjet has a clippy.toml already; add entries withreasonstrings the way extras/deno/cli/clippy.toml does: banstd::process::exitoutside one exit function, ban directstd::env::current_dirin favor of a resolved repo root passed down, and ban rawprint!/println!outside the CLI output layer. - Make stdout EPIPE-safe. A Git TUI whose subcommands get piped
(
quinjet log | head) will panic with the std macros. Copy thedrop_println!pattern from extras/deno/libs/print/lib.rs (a 10-line macro_rules pair) and denyclippy::print_stdout/print_stderrin the Makefile lint target, exactly as extras/deno/tools/lint.js does. - Golden-file CLI spec tests. Every quinjet operation is a CLI subcommand,
which is exactly the shape of extras/deno/tests/specs: a directory per
scenario, a
__test__.jsoncmanifest,.outexpectations with[WILDCARD]/[WILDLINE]/[UNORDERED_START]matching. Use the samefile_test_runnercrate withharness = falseand port the wildcard matcher idea from extras/deno/tests/util/lib/wildcard.rs; add a lint that fails on unreferenced.outfiles (ensureNoUnusedOutFiles()in extras/deno/tools/lint.js). - PTY-based end-to-end tests for the TUI. extras/deno/tests/util/lib/pty.rs
shows the harness: spawn the real binary in a pseudo-terminal, write
keystrokes,
.expect(...)on output between writes, strip ANSI codes before asserting. This is the missing end-to-end layer for a ratatui app; theportable-ptycrate provides the primitive. - Property-test the security- and ordering-critical logic.
extras/deno/runtime/permissions/lib.rs proves
Ordtransitivity and deny-precedence withproptest. quinjet equivalents: refspec/branch name parsing round-trips, keybinding chord resolution, and any manualOrd/PartialOrdimpl. - Add a
cargo-fuzztarget for parser code, following extras/deno/libs/npm/fuzz/Cargo.toml (a tinypublish = falsecrate withlibfuzzer-sysand one[[bin]]per target). Candidate targets: whatever quinjet parses fromgitoutput or config files. - Single aggregator CI job. Mirror
ci-statusfrom extras/deno/.github/workflows/ci.generated.yml: one job thatneeds:everything and fails oncontains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled'), and make it the only required branch-protection check, so adding or sharding jobs never requires touching repo settings. - Pin actions to commit SHAs with a tag comment
(
# gagen:pin actions/checkout@v6 = de0fac2e...), settimeout-minuteson every job, and add aconcurrencygroup withcancel-in-progress: truekeyed on the head ref. - Cache policy worth copying even single-crate: version-prefixed cache
keys via one bump-able constant (
const cacheVersion = 123in extras/deno/.github/workflows/ci.ts), restore-by-prefix (key: never_savedplusrestore-keys), and save only on main with the SHA in the key so PRs always restore fresh. - Exit-code discipline via a conversion trait. Copy
SubcommandOutputfrom extras/deno/cli/lib.rs: every subcommand returnsResult<i32, Error>through one trait, and exactly one function ever exits the process. Pair it with theboxed_errorcrate plus athiserrorkind-enum when clippy'sresult_large_errstarts firing. - Structured, drift-proof generated files. quinjet generates a wiki from
docs; extend the pattern Deno uses in
ensureWorkflowYmlsUpToDate(): every generated artifact (completions, man pages, wiki) gets a CI step that regenerates and fails on diff, and the file itself carries aGENERATED BY <source> -- DO NOT DIRECTLY EDITheader. - Dynamic shell completions from the binary itself. Deno registers a
completion script that calls back into the binary with
COMPLETEset and completes live data such as task names (extras/deno/cli/args/flags.rs). quinjet can complete branch names, remotes, and stash refs the same way with clap_complete's dynamic completion support, keeping completions in lockstep with the parser. - Release-profile tuning: quinjet ships a TUI binary, so copy the
size/speed split from extras/deno/Cargo.toml:
opt-level = "z",lto = true,codegen-units = 1,panic = "abort",debug = "line-tables-only"withsplit-debuginfo = "packed", plus[profile.release.package.<hot-crate>] opt-level = 3for the hot path, and arelease-liteprofile (inherits = "release", incremental, thin LTO) for local iteration. - A tiny PR-title lint workflow (extras/deno/.github/workflows/pr.generated.yml
running one script against
github.event.pull_request.title) keeps the conventional-commit history that quinjet's changelog and squash-merge flow depend on, at the cost of a 25-line workflow. - Draft-PR gating and docs-only fast paths: expose cheap
pre_buildoutputs (docs_only,skip_build) and condition the expensive miri, mutants, and coverage jobs on them, as extras/deno/.github/workflows/ci.generated.yml does, so documentation changes do not pay the full CI bill.
uv is a Python package and project manager written in Rust, developed by Astral. It replaces
pip, pip-tools, pipx, poetry, pyenv, and virtualenv with a single, extremely fast binary. Industry
adopted it because it makes dependency resolution and installation one to two orders of magnitude
faster than the incumbent tools, while remaining a drop-in interface (uv pip install) and adding a
modern project workflow (uv sync, uv lock, uv run). The crate description in
extras/uv/crates/uv/Cargo.toml reads:
[package]
name = "uv"
version = "0.12.5"
description = "A Python package and project manager"Scale, measured directly from the clone:
- 71 crate directories under
extras/uv/crates/(each with its ownCargo.toml); 70 of them are workspace members.crates/uv-trampolineis excluded from the workspace because it needs nightly (extras/uv/Cargo.toml). - 634 Rust source files totaling roughly 520,000 lines of Rust, of which about 229,000 lines are
CLI integration tests under
extras/uv/crates/uv/tests/. - 39 workflow files under
extras/uv/.github/workflows/, about 10,200 lines of CI configuration. - Rust edition 2024 across the workspace, MSRV 1.95.0, pinned toolchain 1.97.1
(
extras/uv/rust-toolchain.toml).
extras/uv/
|-- Cargo.toml workspace root: members, shared deps, lints, profiles
|-- Cargo.lock
|-- crates/ 71 crates, all prefixed uv-*
| |-- uv/ the CLI binary crate (uv, uvx, uvw entry points)
| |-- uv-cli/ clap definitions, separated from command logic
| |-- uv-resolver/ dependency resolution (PubGrub)
| |-- uv-client/ HTTP registry client with rkyv-backed caching
| |-- uv-test/ shared integration-test harness crate
| |-- uv-trampoline/ no-std-ish Windows launcher, own workspace, nightly
| `-- ... uv-pep440, uv-pep508, uv-fs, uv-git, uv-python, ...
|-- docs/ mkdocs site: getting-started, guides, concepts, reference
|-- scripts/ release, benchmarking, snapshot, codesign helpers
|-- test/ fixture data: ecosystem, packages, scenarios, workspaces
|-- python/ the PyPI package shim
|-- changelogs/ archived changelogs per 0.x series
|-- .github/workflows/ 39 workflows, mostly reusable (workflow_call)
|-- clippy.toml disallowed types/methods, doc-valid-idents
|-- rustfmt.toml edition pinning only
|-- hawk.toml config for Astral's custom workspace lint tool
|-- dist-workspace.toml cargo-dist release configuration
|-- ruff.toml, _typos.toml, .pre-commit-config.yaml, .editorconfig
|-- CONTRIBUTING.md, STYLE.md, BENCHMARKS.md, SECURITY.md
`-- CHANGELOG.md
The split works because the binary crate (crates/uv) contains only command orchestration; every
domain concept lives in a small, focused library crate. Standards get their own crates
(uv-pep440, uv-pep508), infrastructure gets its own crates (uv-fs, uv-cache, uv-client),
and even single-type crates exist when the type is shared widely (uv-small-str, uv-once-map,
uv-redacted). This keeps compile units small, makes dependency direction explicit, and lets the
resolver, installer, and build frontend evolve independently. The circular dependency between
"resolving needs building" and "building needs resolving" is broken by a trait crate, uv-types
(see section 9).
The root extras/uv/Cargo.toml demonstrates full workspace.package inheritance:
[workspace.package]
edition = "2024"
rust-version = "1.95.0"
homepage = "https://pypi.org/project/uv/"
repository = "https://github.com/astral-sh/uv"
authors = ["uv"]
license = "MIT OR Apache-2.0"Every member crate then contains only edition = { workspace = true } style references plus
[lints] workspace = true (verified in extras/uv/crates/uv/Cargo.toml and
extras/uv/crates/uv-bench/Cargo.toml).
Distinctive manifest practices:
- Dual versioning. The
uvbinary is0.12.5, but the 60-plus internal library crates all share an independent version series,0.0.72, listed once in[workspace.dependencies]with bothversionandpathso the workspace can be published to crates.io as a unit (extras/uv/Cargo.toml). - Every third-party dependency is declared exactly once in
[workspace.dependencies], alphabetically, with explicit feature selection and frequentdefault-features = false(for examplereqwestwith 12 features and rustls instead of native TLS). - Forked dependencies are declared with
package =renames so call sites keep upstream names:pubgrub = { version = "0.6.1", package = "astral-pubgrub" }andasync_zip = { version = "0.0.20", package = "astral_async_zip", ... }. - Feature flags gate test dependencies on external services, so offline or restricted CI can turn
them off. From
extras/uv/crates/uv/Cargo.toml:
# Features that only apply when running tests, no-ops otherwise.
test-defaults = [
"test-crates-io",
"test-git",
...
]
# Introduces a testing dependency on PyPI.
test-pypi = ["uv-client/test-pypi"]- The
self-updatefeature is off by default and documented as "only enabled for uv's cargo-dist installer", so distro packages never ship a self-updater. - Eight build profiles, each with a comment explaining the tradeoff.
releaseusesstrip = true,lto = "fat",panic = "abort";profilinginherits release but disables LTO, with a long measured justification in comments ("compile times withlto = trueare completely untenable", including timed builds at 3m47s, 53.98s, and 30.09s);fast-buildandfast-build-nightlyoptimize test compile time (opt-level = 1, no debuginfo,panic = "abort"for nextest with-Z panic-abort-tests);minimal-sizeusesopt-level = "z"andcodegen-units = 1for theuv-buildbackend shim.
extras/uv/rustfmt.toml is deliberately minimal, pinning behavior rather than customizing style:
edition = "2024"
style_edition = "2024"edition tells rustfmt how to parse the source; style_edition opts into the 2024 formatting
rules (for example the new import sorting). There are no other overrides: uv accepts default
rustfmt output completely, which removes all format debate.
extras/uv/.editorconfig handles the cross-language basics: UTF-8, LF, trimmed trailing
whitespace, 2-space indent by default, 4-space for *.{rs,py,pyi}, and two precise exceptions
that show real care:
[*.snap]
trim_trailing_whitespace = false
[crates/uv/tests/help.rs]
trim_trailing_whitespace = falseSnapshot files and the help-text test contain meaningful trailing whitespace, so editors must not strip it.
Non-Rust formatters: Prettier for Markdown/YAML/JSON5 with proseWrap: "always" for Markdown
(extras/uv/.prettierrc), enforced in CI by npx prettier@3.9.0 --check .
(extras/uv/.github/workflows/check-fmt.yml); Ruff formats and lints the Python scripts
(uvx ruff format --diff . in the same workflow, config in extras/uv/ruff.toml); Markdown is
wrapped at 100 characters per extras/uv/.editorconfig and extras/uv/STYLE.md.
Linting is layered across four places.
Layer 1: [workspace.lints] in extras/uv/Cargo.toml. Rust lints first:
[workspace.lints.rust]
unsafe_code = "warn"
unreachable_pub = "warn"unsafe_code = "warn" means every unsafe block needs an explicit #[allow(unsafe_code)] opt-in,
making unsafe grep-able (23 such attributes across the tree, 56 SAFETY: comments). Clippy is
pedantic at priority = -2 with a curated allow list (too_many_lines, missing_errors_doc,
module_name_repetitions, and 12 others) plus hand-picked restriction lints promoted to warn:
print_stdout, print_stderr, dbg_macro, exit, get_unwrap, rc_buffer, rc_mutex,
rest_pat_in_fully_bound_structs, use_self, empty_drop, empty_structs_with_brackets. The
philosophy: pedantic-by-default, silence categories that produce noise for this codebase, and use
restriction lints to encode house rules (no direct printing outside the printer layer, no
std::process::exit).
Layer 2: extras/uv/clippy.toml turns clippy into an architectural boundary enforcer. All of
std::fs and tokio::fs is banned at the type and method level:
disallowed-types = [
"std::fs::DirEntry",
"std::fs::File",
...
]
disallowed-methods = [
"std::fs::canonicalize",
"std::fs::copy",
...
"tokio::fs::write",
]This funnels every filesystem call through extras/uv/crates/uv-fs, which wraps fs-err so
errors always carry paths, and centralizes Windows path handling. dotenvy entry points are
banned the same way so env-file loading happens in exactly one place. doc-valid-idents teaches
clippy's doc lint the project vocabulary (PyPI, PubGrub, CPython, every UV_* env var name)
with ".." appended to keep the defaults.
Layer 3: CI flags. extras/uv/.github/workflows/check-lint.yml runs
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings on both Linux and
Windows (Windows-only code paths get linted too), so the manifest keeps lints at warn for
development ergonomics while CI escalates to deny.
Layer 4: custom lint infrastructure. Astral ships its own workspace linter, hawk, configured in
extras/uv/hawk.toml and run in CI as cargo +1.97.1 hawk check --target-dir target/hawk -D warnings. It audits the public API surface of the workspace: which packages are production
binaries, which have doctests, and which pub items are dead or unnecessarily public, with named,
reasoned overrides:
[[override]]
lint = "hawk::unnecessary_public"
crate = "uv_client"
item = "base_client::BaseClientBuilder::<'a>::custom_client"
kind = "inherent_method"
level = "expect"
reason = "used by Pixi to provide its own HTTP client"On top of that, cargo shear --deny-warnings catches unused dependencies, typos (with
extras/uv/_typos.toml excluding snapshot dirs and defining domain words) catches spelling, and
shellcheck --shell bash --severity style lints every shell script, all in check-lint.yml.
Source code preference is visible in the numbers: 157 #[expect(...)] attributes, which fail the
build when they stop being needed, versus blanket #[allow].
The top-level extras/uv/.github/workflows/ci.yml is a pure orchestrator: it declares
permissions: {}, a concurrency group with cancel-in-progress: true, and then delegates every
job to reusable workflows referenced with the same-repository shorthand:
check-lint:
needs: plan
uses: $/.github/workflows/check-lint.yml
with:
code-changed: ${{ needs.plan.outputs.test-code }}
save-rust-cache: ${{ needs.plan.outputs.save-rust-cache }}Key structural ideas:
- A
planjob (extras/uv/.github/workflows/plan.yml) inspects the diff once and emits 17 boolean outputs (test-code,check-schema,run-bench,test-macos,build-docker, and so on). Every downstream workflow is gated on these outputs, so a docs-only PR skips the Rust build entirely and a schema change triggers the schema check. - Every
uses:of a third-party action is pinned to a full commit SHA with a version comment, for exampleactions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1, and every checkout setspersist-credentials: false. Renovate (extras/uv/.github/renovate.json5) manages the pins on a weekly schedule, withcustomManagers:githubActionsVersionsalso bumping tool versions embedded inrun:steps via# renovate:comments (seeHAWK_VERSIONandSHELLCHECK_VERSIONincheck-lint.yml). - Workflow security is itself linted:
extras/uv/.github/workflows/check-zizmor.ymlruns the zizmor static analyzer over all workflows and uploads SARIF (security-events: write), with a documented rule exception inextras/uv/.github/zizmor.yml. - Branch protection targets a single aggregation job.
ci.ymlends with arequired-checks-passedjob thatneeds:the six required workflows, runs withif: always(), and usesjqovertoJSON(needs)to fail if any dependency is neithersuccessnorskipped. Required checks stay stable even as jobs are added or conditionally skipped. - OS coverage in
extras/uv/.github/workflows/test.yml: Linux on a 16-core Depot runner with the mold linker; macOS on a Namespace runner; Windows on a 16-core runner with a Dev Drive (ReFS) created byextras/uv/.github/workflows/setup-dev-drive.ps1and the repo copied onto it for I/O speed. Windows tests are split three ways with nextest hash partitioning (--partition hash:${{ matrix.partition }}/3). Linux CI even creates btrfs, tmpfs, and minix filesystems in-loop to exercise copy-on-write, non-CoW, and low-hardlink-limit code paths, and macOS creates an HFS+ disk image with no reflink support. - Caching:
Swatinem/rust-cacheeverywhere withsave-ifwired to the plan output so only main branch (or explicitly opted-in) runs write the cache, plus a customscripts/prune_cargo_workspace_cache.pystep that deletes superseded workspace artifacts before the cache is saved. - Downstream validation beyond unit tests:
test-smoke.yml(run the built binary and eval its shell completions),test-integration.yml(nushell, conda, deadsnakes, armv7-on-aarch64, and more, about 1,160 lines),test-system.yml(29 jobs installing real packages on Debian, Fedora, even Python 3.6 on Debian Buster), andtest-ecosystem.ymlwhich runs uv against pinned commits of real projects (prefect, flask, pydantic-core). -
test-publishinci.ymlpublishes real packages to test.pypi.org through tokens, keyring, and OIDC trusted publishing, including impersonated GitLab OIDC tokens, on every relevant PR. - Environment hardening and hygiene env vars appear in every Rust workflow:
CARGO_INCREMENTAL: 0,CARGO_NET_RETRY: 10,RUSTUP_MAX_RETRIES: 10, and intest.ymlRUSTC_BOOTSTRAP: 1so stable toolchains can use-Z panic-abort-testsand-Z checksum-freshness. - Release automation is generated by cargo-dist (
extras/uv/.github/workflows/release.yml, configured viaextras/uv/dist-workspace.toml) with custom local-artifact, publish, and post-announce jobs;release-prepare.ymlis aworkflow_dispatchjob that runs./scripts/release.shto bump versions and open the release PR under a bot account with short-lived credentials from an STS broker rather than a long-lived PAT.
The test pyramid is inverted on purpose: the dominant layer is end-to-end CLI testing. The binary
crate hosts multiple integration-test targets as directories under extras/uv/crates/uv/tests/
(it, pip, sync, lock, project, tool, python, workspace, build, and more), each
with its own main.rs that composes modules and feature gates:
#[cfg(all(feature = "test-pypi", feature = "test-universal"))]
mod branching_urls;
...
#[cfg(unix)]
mod resource_limits;(extras/uv/crates/uv/tests/it/main.rs.) Splitting into several test binaries lets nextest
schedule them in parallel and lets contributors run one suite at a time.
The harness lives in a dedicated workspace crate, extras/uv/crates/uv-test/, whose lib.rs
provides a TestContext (isolated temp dirs, virtualenvs, managed Pythons, a PyPI proxy, a local
HTTP server, find-links fixtures) plus builder-style helpers like context.pip_install(). Two
macros anchor the ergonomics: test_context!, which captures env!("CARGO_BIN_EXE_uv") at
compile time so the harness always runs the freshly built binary, and uv_snapshot!
(extras/uv/crates/uv-test/src/lib.rs), which wraps command execution in insta snapshot
assertions with a default filter set:
macro_rules! uv_snapshot {
($spawnable:expr, @$snapshot:literal) => {{
uv_snapshot!($crate::INSTA_FILTERS.to_vec(), $spawnable, @$snapshot)
}};
...
}There are 6,430 uv_snapshot! call sites. Snapshots are mostly inline (@"..."), with 88
external .snap files; filters normalize timings, paths, and platform noise, and a
WindowsFilters mode rewrites Windows-only differences (for example subtracting the
Windows-only colorama dependency from package counts) so one snapshot serves all platforms.
CI runs nextest with INSTA_UPDATE: new and uploads pending snapshots as an artifact on failure
(extras/uv/.github/workflows/test.yml); extras/uv/scripts/apply-ci-snapshots.sh then applies
CI-generated snapshots locally, which is how platform-specific snapshots get updated without
owning that platform. JUnit XML from nextest is uploaded per-OS for reporting.
Unit tests exist where the domain is algorithmic (extras/uv/crates/uv-pep440,
uv-distribution-filename, uv-once-map all have inline #[cfg(test)] modules), and doctests
are tracked explicitly per package in extras/uv/hawk.toml ([[doctest]] package = "uv-pep440").
Network tests use wiremock (declared in the dev-dependency block of extras/uv/Cargo.toml) and
a vendored PyPI proxy in uv-test. There is no fuzzing or property-testing harness in-tree; the
project instead invests in scenario generation (cargo dev generate-scenario-tests against
packse scenarios, checked in extras/uv/.github/workflows/check-generated-files.yml) and the
ecosystem/system/smoke workflows described in section 6.
Benchmarks live in extras/uv/crates/uv-bench with harness = false targets (uv,
workspace_discovery, uv_pep440, uv_pypi_types) built on
criterion = { package = "codspeed-criterion-compat" }, and CI runs them through cargo-codspeed
for continuous regression tracking (extras/uv/.github/workflows/bench.yml). BENCHMARKS.md
documents the methodology and its caveats (filesystem-dependent install strategies).
The pattern is thiserror in libraries, anyhow only at the binary boundary: 150
thiserror::Error derives across extras/uv/crates/, while uv-resolver contains zero direct
anyhow:: references. The binary classifies failures for exit-code purposes with a dedicated
enum in extras/uv/crates/uv/src/commands/mod.rs:
pub enum ExitStatus {
/// The command succeeded.
Success,
/// The command reported a failure caused by user input.
Failure,
/// The command reported an unexpected failure.
Error,
/// The command's exit status is propagated from an external command.
External(u8),
}with impl From<ExitStatus> for ExitCode mapping Success/Failure/Error to 0/1/2 and passing
external codes through. Nothing calls std::process::exit directly; the restriction lint
exit = "warn" backs that up, and a UvError enum (same file) wraps anyhow::Error into
User, Argument, and internal variants so the entry point can select the exit status.
User-facing diagnostics get first-class support in extras/uv/crates/uv-errors/src/lib.rs, which
defines a Hint trait so error types can attach "hint:"-prefixed suggestions rendered after the
error, with text wrapping handled centrally.
API design conventions observed:
- Builders with lifetimes:
BaseClientBuilder<'a>inextras/uv/crates/uv-client/src/base_client.rshas 20+ private fields, 25must_useannotations, and chainable setters; hawk overrides document which builder methods exist only for downstream consumers like Pixi. - Newtypes everywhere:
pub struct PackageName(SmallString)inextras/uv/crates/uv-normalize/src/package_name.rsguarantees normalization at construction (validate_and_normalize_ref(&name).map(Self));SmallString(arcstr::ArcStr)inextras/uv/crates/uv-small-str/src/lib.rsis an O(1)-clone immutable identifier type with the fullFrom/AsRef/Borrow/Derefsurface. - Security by type:
DisplaySafeUrl(Url)inextras/uv/crates/uv-redacted/src/lib.rsis a#[repr(transparent)]RefCastwrapper whoseDisplaymasks passwords and sensitive query parameters (X-Amz-Signatureand friends), so credentials cannot leak through logging by accident. - Visibility is policed twice:
unreachable_pub = "warn"at the compiler level and hawk'sdead_public/unnecessary_publiclints at the workspace level. - Panic policy:
panic = "abort"in release with the comment "This will still show a panic message, we only skip the unwind" (extras/uv/Cargo.toml);get_unwrapis a warn lint; the Windows side installs an unhandled-exception handler (uv_windows::install_unhandled_exception_handler()inextras/uv/crates/uv/src/lib.rs).
-
A bespoke concurrency primitive for request coalescing.
extras/uv/crates/uv-once-map/src/lib.rsbuildsOnceMap<K, V>on the lock-freepapaya::HashMapplustokio::sync::Notify: "Run tasks only once and store the results in a parallel hash map. ... When multiple tasks start the same query in parallel ... we want to wait until the other task is done and get a reference to the same result." Theregister/done/waitprotocol memoizes network fetches across the whole resolver. -
Zero-copy cache deserialization with rkyv.
extras/uv/crates/uv-client/src/rkyvutil.rsdefinesOwnedArchive<A>: "Constructing the type requires validating the bytes are a valid representation of anArchived<A>, but subsequent accesses (via deref) are free." Registry metadata is written once and then memory-mapped as archived structs;uv-pep440,uv-distribution-filename, anduv-pypi-typesall deriverkyv::Archivebehind anrkyvfeature. -
Bit-packing with an explicit niche.
extras/uv/crates/uv-pep440/src/version.rsstores common versions in a singleu64(struct VersionSmall { repr: u64, len: u8, _force_niche: NonZero<u8> }) with the comment "Force a niche into the aligned type so the [Version] enum is two words instead of three." A parsed PEP 440 version is two machine words in the hot path. -
#[repr(transparent)]plusref-castfor free wrapper conversions.extras/uv/crates/uv-redacted/src/lib.rsderivesRefCastonDisplaySafeUrl(Url)so&Urlcan be reinterpreted as&DisplaySafeUrlwithout allocation, keeping redaction zero cost. -
A written-down unsafe policy, enforced by lints. With
unsafe_code = "warn"workspace-wide, the entry point inextras/uv/crates/uv/src/lib.rsis itselfpub unsafe fn main, with a# Safetysection ("It is only safe to call this routine when it is known that multiple threads are not running") because it callsstd::env::set_var; the caller inextras/uv/crates/uv/src/bin/uv.rsdischarges the obligation with aSAFETY:comment. 56SAFETY:comments exist against only 42 files that mention unsafe at all. -
Platform code isolated into dedicated crates.
extras/uv/crates/uv-unix/src/lib.rsopens with#![cfg(unix)]and exports only resource-limit handling;extras/uv/crates/uv-windows/src/holds job objects, ctrl handlers, structured-exception handling, and Wine detection. The remaining 323#[cfg(unix)]/#[cfg(windows)]attributes are for small local divergences, and thewindowscrate is imported with 17 explicitly enumeratedWin32_*features (extras/uv/Cargo.toml) to keep build times bounded. -
Lint-enforced I/O architecture. Because
clippy.tomlbansstd::fs/tokio::fs(section 5), all filesystem access flows throughextras/uv/crates/uv-fs, which layersfs-errfor path-carrying errors and defines aSimplifiedtrait (extras/uv/crates/uv-fs/src/path.rs) whosesimplified_display()strips the Windows\\?\prefix for user-facing output. An idiom (clippy config) enforces an architecture rule. -
Trait-based dependency inversion with
impl Traitin traits.extras/uv/crates/uv-types/src/traits.rsdefinesBuildContextwith an associated typeSourceDistBuilder: SourceBuildTraitand async-by-signature methods likefn interpreter(&self) -> impl Future<Output = &Interpreter> + '_;, lettinguv-resolverinvoke source builds without depending on the build crates. -
Proc macros for metadata, not magic.
extras/uv/crates/uv-macros/src/lib.rsderivesOptionsMetadataandPreviewMetadataand provides attributes (attr_hidden,attr_env_var_pattern("UV_INDEX_{name}_USERNAME")) consumed inextras/uv/crates/uv-static/src/env_vars.rs;cargo dev generate-env-vars-referencethen turns that metadata into the documentation site, so docs cannot drift from code. -
Lazily borrowed strings by default. 168
Cow<'_, ...>sites; a representative one inextras/uv/crates/uv-static/src/lib.rsreturnsCow<'_, str>fromastral_mirror_base_url, borrowing the trimmed user URL or the static default without allocating. -
Modern control flow at scale: 605
let ... elsebindings and 136Either::Left/Rightsites (branching iterator pipelines without boxing), plus lifetime-annotated iterator returns such aspub fn packages(&self) -> impl Iterator<Item = (&'lock PackageName, &'lock Version)> + '_inextras/uv/crates/uv-resolver/src/lock/mod.rs. -
Runtime tuning in the entry point.
extras/uv/crates/uv/src/lib.rsbuilds a current-thread tokio runtime with a custom stack size, boxes the main future ("Box the large main future to avoid stack overflows"), and constructs thepapaya-backed workspace cache before spawning threads so the seize memory barrier registers on the kernel's single-threaded fast path; a swappable high-performance allocator ships as its own optional crate,uv-performance-memory-allocator, kept alive viaextern crateinextras/uv/crates/uv/src/bin/uv.rs. -
A nightly
no-std-adjacent launcher.extras/uv/crates/uv-trampoline/Cargo.tomlenablescargo-features = ["panic-immediate-abort"],opt-level = "z",lto, andufmtinstead ofstd::fmtto produce the tiny Windows script trampoline, isolated in its own workspace with its own toolchain file so the main workspace stays on stable.
- Rustdoc uses intra-doc links pervasively; doc comments reference types as
[OnceMap::done](extras/uv/crates/uv-once-map/src/lib.rs) and include runnable doctests where the API is self-contained, for example the credential-masking examples inextras/uv/crates/uv-redacted/src/lib.rs. Doctest-bearing packages are tracked inextras/uv/hawk.toml, and crates that should not run doctests disable them ([lib] doctest = falseinextras/uv/crates/uv-bench/Cargo.toml). - The user documentation is an in-repo mkdocs-material site (
extras/uv/mkdocs.yml,extras/uv/docs/) split into getting-started, guides, concepts, pip compatibility, and reference. The reference section is generated from code by theuv-devcrate (extras/uv/crates/uv-dev/src/generate_cli_reference.rs,generate_options_reference.rs,generate_env_vars_reference.rs), regenerated in CI beforemkdocs build --strict(extras/uv/.github/workflows/check-docs.yml), and guarded against drift bycargo dev generate-all --mode dry-runincheck-generated-files.ymland a pre-commit hook. -
extras/uv/STYLE.mdis unusual: a style guide for CLI output and prose, covering terminology ("lockfile" not "lock file"), the no-capitalization rule for the name uv, color semantics (green success, red error, cyan hints and paths), the rule that all logging goes to stderr, and per-doc-type voice rules (guides are second person imperative, concepts third person). -
extras/uv/CONTRIBUTING.mddocuments the nextest/insta workflow, local Python setup, and a clear contribution policy (no feature PRs without prior discussion). Issue templates are typed YAML forms (extras/uv/.github/ISSUE_TEMPLATE/1_bug_report.yaml, feature request, question), andextras/uv/.github/PULL_REQUEST_TEMPLATE.mdasks for exactly two sections, Summary and Test Plan.
- Versioning: the binary follows 0.x SemVer (
0.12.5), internal crates follow their own0.0.72series;extras/uv/scripts/release.shandscripts/bump-workspace-crate-versions.pyperform the bump, driven by therelease-prepare.ymlworkflow_dispatch job. - Changelog discipline:
extras/uv/CHANGELOG.mdgroups entries per release under headings such as Python, Enhancements, Preview features, and Bug fixes, each entry linking its PR; complete historical series are archived underextras/uv/changelogs/0.1.x.mdthrough0.11.x.md. - The release pipeline is cargo-dist (
extras/uv/dist-workspace.toml): 18 prebuilt targets fromaarch64-apple-darwintos390x-unknown-linux-gnu, shell and PowerShell installers,dispatch-releases = true(releases triggered by dispatch, not tag push), GitHub build provenance attestations (github-attestations = true) with filters, per-target glibc floors (aarch64-unknown-linux-gnu = "2.28","*" = "2.17"), and a simple-hosting mirror (simple-download-url = "https://releases.astral.sh/...") falling back to GitHub releases. Even the actions used inside generated release workflows are SHA-pinned via[dist.github-action-commits]. - Binaries per platform:
uvanduvxeverywhere, plus auvw(windowless) binary on Windows ([dist.binaries]inextras/uv/dist-workspace.toml). - Distribution channels beyond GitHub: PyPI wheels built with maturin
(
build-backend = "maturin"inextras/uv/pyproject.toml, published byextras/uv/.github/workflows/publish-pypi.ymlwith trusted publishing), Docker images (build-docker.ymlwith package attestations), crates.io (publish-crates.ymlpublishes the whole workspace with a nightly-Zpublish-timeoutand a raisedpublish.timeout=600, aftercargo publish --workspace --dry-rungated every PR incheck-publish.yml), and versioned docs (publish-docs.yml,publish-versions.yml). - Shell completions ship as a hidden subcommand (
generate-shell-completionviaclap_complete_commandinextras/uv/crates/uv-cli/src/lib.rs) and are smoke-tested in CI by actually eval-ing them:eval "$(./uv generate-shell-completion bash)"(extras/uv/.github/workflows/test-smoke.yml).
quinjet already has a strict clippy wall, rustfmt, cargo-deny, taplo, typos, coverage, miri, and mutants. The following uv practices are still worth adopting, with exact mechanisms:
- Turn clippy into an architecture enforcer with
clippy.tomldisallowed-methodsanddisallowed-types. For a Git TUI: banstd::process::exitcall sites outsidemain, ban rawprintln!/eprintln!outside the presentation layer (quinjet likely hasprint_stdoutalready; the disallowed lists go further by banning specific APIs such asstd::fs::*in favor of an error-context wrapper likefs-err), and adddoc-valid-identsfor project vocabulary so pedantic doc lints stop fighting names. - Adopt insta snapshot testing for the CLI surface:
instawith thefiltersandredactionsfeatures plusassert_cmd, wrapped in one project macro modeled onuv_snapshot!(extras/uv/crates/uv-test/src/lib.rs) that applies a default filter list (temp paths, hashes, durations) and asserts stdout, stderr, and exit code together. Since every quinjet operation is a CLI subcommand, this covers the whole command layer; pair it with aTestContextthat creates a scratch Git repository per test viaassert_fs. - Add
cargo shear --deny-warnings(workflow step,taiki-e/install-actionwithtool: cargo-shear) to catch unused dependencies; cargo-deny does not do this. - Add zizmor for workflow auditing: run
zizmorcore/zizmor-actionin CI as inextras/uv/.github/workflows/check-zizmor.yml, pin every action to a full SHA with a# vX.Y.Zcomment, set top-levelpermissions: {}per workflow, and setpersist-credentials: falseon everyactions/checkout. - Create a
required-checks-passedaggregation job (if: always()plus ajqscan oftoJSON(needs)as inextras/uv/.github/workflows/ci.yml) and make it the only required branch-protection check, so jobs can be added or skipped without touching repo settings. - Switch test execution to
cargo-nextestwith a dedicated Cargo profile modeled on uv'sfast-build(opt-level = 1,debug = 0,strip = "debuginfo",lto = "off"inextras/uv/Cargo.toml), and upload JUnit XML plus pending insta snapshots as artifacts on failure (INSTA_UPDATE: newas inextras/uv/.github/workflows/test.yml). - Use
#[expect(...)]instead of#[allow(...)]for every lint suppression so stale suppressions fail the build; uv carries 157 of them. - Model the exit path on
ExitStatus: an enum with documented variants converted throughimpl From<ExitStatus> for ExitCode(extras/uv/crates/uv/src/commands/mod.rs) instead of scatteredprocess::exit, distinguishing user error (1) from internal error (2) and propagating child exit codes for pass-through Git invocations. - Adopt cargo-dist for releases: a
dist-workspace.tomlwith SHA-pinned[dist.github-action-commits], shell + PowerShell installers, GitHub attestations, andpr-run-mode = "skip", followingextras/uv/dist-workspace.toml; ship completions via a hiddengenerate-shell-completionsubcommand (clap_complete_command) and smoke-test them in CI witheval "$(quinjet generate-shell-completion bash)"as inextras/uv/.github/workflows/test-smoke.yml. - Add a generated-files drift check: if quinjet generates docs from clap (and it should, via a
devxtask likeextras/uv/crates/uv-devwithgenerate_cli_reference.rs), add a CI step running the generator in--mode check(extras/uv/.github/workflows/check-generated-files.yml) and a matching pre-commit hook. - Write a
STYLE.mdfor user-facing output modeled onextras/uv/STYLE.md: color semantics, stderr-only logging,NO_COLORcompliance, message capitalization and punctuation rules. For a TUI this doubles as the theming contract. - Keep a
Hint-style trait for errors (extras/uv/crates/uv-errors/src/lib.rs) so failure messages can carry actionable "hint:" lines (for example suggesting--forceor the matching subcommand) rendered uniformly by one printer. - Gate environment-dependent tests behind Cargo features the way uv gates
test-gitandtest-pypi(extras/uv/crates/uv/Cargo.toml), so quinjet tests needing a real remote or network can be excluded deterministically with--no-default-features. - Use Renovate custom managers (
customManagers:githubActionsVersionsplus# renovate:comments as inextras/uv/.github/workflows/check-lint.yml) so tool versions embedded in workflowrun:steps are updated automatically instead of rotting.
Zed is a high-performance, collaborative code editor written entirely in Rust, built by the team that previously created Atom and Tree-sitter. It ships its own GPU-accelerated UI framework (GPUI), its own CRDT text engine, a collaboration server, a language-server client, a debugger client, and a WebAssembly extension host, all in one repository. Industry studies this codebase because it is one of the largest coherent Rust workspaces in the open, and because it demonstrates how to keep sub-second incremental builds and deterministic tests at that scale.
Measured directly from the clone:
- 250 workspace members declared in
extras/zed/Cargo.toml: 243 undercrates/, 4 underextensions/, 3 undertooling/(tooling/compliance,tooling/lintsis deliberately excluded from the workspace, see Section 5). - Roughly 1,554,000 lines of Rust across
crates/,tooling/, andextensions/(sum ofwc -lover all.rsfiles). - The root manifest
extras/zed/Cargo.tomlalone is 1,134 lines. -
default-members = ["crates/zed"]so a barecargo buildbuilds only the editor binary, not all 250 members. - The toolchain is pinned exactly in
extras/zed/rust-toolchain.toml:
[toolchain]
channel = "1.97.1"
profile = "minimal"
components = [ "rustfmt", "clippy", "rust-analyzer", "rust-src" ]
targets = [
"wasm32-wasip2", # extensions
"wasm32-unknown-unknown", # gpui on the web
"x86_64-unknown-linux-musl", # remote server
]The comments on each target are typical of this repo: every pinned thing carries its reason inline.
Why industry keeps studying it: the same repository contains a production GUI framework, a CRDT engine that survives randomized fuzzing, a WebSocket collaboration server deployed from the repo (extras/zed/.github/workflows/deploy_collab.yml), and the build engineering needed to keep 250 crates compiling quickly. Few open codebases show all four at once, and none at this line count with a three-line rustfmt config.
Selected top level of extras/zed/:
zed/
|-- Cargo.toml 250-member workspace root, all shared config
|-- Cargo.lock
|-- rust-toolchain.toml exact toolchain pin (1.97.1)
|-- rustfmt.toml 3 lines, defaults plus edition
|-- clippy.toml disallowed-methods with reasons
|-- typos.toml spell-check config with per-file justifications
|-- lychee.toml link-checker config for docs
|-- renovate.json dependency-update bot config
|-- REVIEWERS.conl reviewer routing by code area
|-- .cargo/ config.toml, ci-config.toml, collab-config.toml
|-- .github/ workflows (46 files), templates, actionlint/zizmor config
|-- assets/ icons, themes, default settings, keymaps
|-- crates/ 243 first-party crates
| |-- gpui/ the UI framework
| |-- editor/ the editor itself
| |-- rope/ sum_tree/ text/ clock/ core data structures
| |-- cli/ the `zed` command-line entry point
| |-- collab/ the collaboration server
| `-- util/ collections/ paths/ shared foundations
|-- docs/ mdBook user documentation
|-- extensions/ first-party extensions built as wasm
|-- legal/ CLA and licensing texts
|-- nix/ Nix packaging (plus flake.nix, shell.nix at root)
|-- script/ 120+ operational scripts (bash, ps1, py, js)
`-- tooling/ compliance, lints (dylint), perf, xtask
Why the split works: each feature is a crate (crates/git_ui, crates/file_finder, crates/vim, ...), so incremental compilation and CI test selection operate at crate granularity, and licensing can differ per crate (GPL for the app, Apache for reusable infrastructure). The scaffold script extras/zed/script/new-crate enforces this: it symlinks the right license file into the new crate, forbids AGPL for first-party crates, validates the crate name against ^[a-z0-9_]+$, and emits a manifest that already contains [lints] workspace = true:
if [[ ! "$CRATE_NAME" =~ ^[a-z0-9_]+$ ]]; then
echo "Error: Crate name must be lowercase and contain only alphanumeric characters and underscores"
exit 1
fiTwo further conventions keep the layout navigable. First, a crate's root source file is named after the crate rather than lib.rs ([lib] path = "src/cli.rs" in extras/zed/crates/cli/Cargo.toml), so editor tabs and stack traces are unambiguous across 243 crates. Second, script/ is treated as production code: it is shellcheck-gated in CI (run_shellcheck step in extras/zed/.github/workflows/run_tests.yml runs ./script/shellcheck-scripts error), and Windows variants sit next to their POSIX twins (clippy and clippy.ps1, bundle-linux and bundle-windows.ps1).
extras/zed/Cargo.toml is a reference example of a large workspace manifest.
Inheritance is minimal but total: [workspace.package] sets only publish = false and edition = "2024", and every member manifest uses edition.workspace = true and publish.workspace = true (see extras/zed/crates/zed/Cargo.toml). Versions stay per-crate; the app crate carries the product version (version = "1.17.0" in extras/zed/crates/zed/Cargo.toml).
Dependency organization: [workspace.dependencies] is split into two labeled blocks, # Workspace member crates (all 243 path dependencies listed once, so member manifests only ever say editor.workspace = true) and # External crates (alphabetized). Every fork is pinned to a rev under the zed-industries org, and renamed forks carry warnings:
# WARNING: If you change this, you must also publish a new version of zed-reqwest to crates.io
reqwest = { git = "https://github.com/zed-industries/reqwest.git", rev = "c15662463bda39148ba154100dd44d3fba5873a4", ... package = "zed-reqwest", version = "0.12.15-zed" }Feature flags are used to cut compile time and binary size aggressively: image disables default features and re-enables 15 named codecs, objc2-foundation enables 24 individually named Foundation classes, and the windows crate gets its own [workspace.dependencies.windows] table listing about 60 API features. The zed crate defines composite features like test-support and visual-tests that fan out to gpui/test-support, editor/test-support, and so on (extras/zed/crates/zed/Cargo.toml).
Profiles are the standout section:
[profile.dev]
split-debuginfo = "unpacked"
incremental = true
codegen-units = 16
debug = "limited"
# mirror configuration for crates compiled for the build platform
# (without this cargo will compile ~400 crates twice)
[profile.dev.build-override]
codegen-units = 16
split-debuginfo = "unpacked"
debug = "limited"Then [profile.dev.package] sets opt-level = 3 for every proc-macro crate plus syn, quote, proc-macro2, tree-sitter, wasmtime, and serde_json, and sets codegen-units = 1 on about 35 single-source-file crates with the comment "Build single-source-file crates with cg=1 as it helps make cargo build of a whole workspace a bit faster":
[profile.dev.package]
# proc-macros start
gpui_macros = { opt-level = 3 }
sqlez_macros = { opt-level = 3, codegen-units = 1 }
quote = { opt-level = 3 }
syn = { opt-level = 3 }
proc-macro2 = { opt-level = 3 }
# proc-macros endRelease is lto = "thin", codegen-units = 1, but the leaf binary is exempted ([profile.release.package] zed = { codegen-units = 16 }) because it never benefits from cross-crate inlining as much as it costs. Two extra profiles exist: dbg (dev plus full debuginfo, "debug" being a reserved name, per the comment in extras/zed/Cargo.toml) and release-fast (release minus LTO for iteration on optimized builds). A [patch.crates-io] section redirects nine crates (async-process, calloop, livekit, notify, and others) to pinned org forks, keeping every transitive user of those names on the patched code without editing member manifests.
Two [workspace.metadata] tables integrate third-party tools directly from the manifest: cargo-machete gets an ignored list, and dylint discovers the custom lint library:
# Dylint discovers our custom lints through this entry, so `cargo dylint --all`
# runs them without a `--path` argument.
[workspace.metadata.dylint]
libraries = [{ path = "tooling/lints" }]extras/zed/.cargo/config.toml adds rustflags = ["-C", "symbol-mangling-version=v0", "--cfg", "tokio_unstable"] (v0 mangling for better closure backtraces) and cargo aliases xtask, perf-test, and perf-compare. There is no MSRV field; the pinned toolchain file replaces rust-version since nothing is published.
extras/zed/rustfmt.toml is three lines:
# https://github.com/rust-lang/rustfmt?tab=readme-ov-file#rusts-editions
edition = "2024"
style_edition = "2024"The philosophy is stock rustfmt: zero custom settings, so no contributor ever fights the formatter and no nightly-only options are needed. CI runs cargo fmt --all -- --check in the check_style job of extras/zed/.github/workflows/run_tests.yml.
Non-Rust formatting is layered per language:
- Prettier, version-pinned inside the script itself, formats the docs and the default settings JSON:
extras/zed/script/prettierrunspnpm dlx "prettier@3.5.0"againstassets/settings/default.json(as JSONC) and thedocs/tree, printing the exact fix command on failure.extras/zed/.prettierrcsets only"printWidth": 120. - Tree-sitter query files are formatted by a dedicated language server binary fetched in CI: the
check_stylejob downloadsts_query_lsv3.15.1 from a GitHub release and runsts_query_ls format --check .(extras/zed/.github/workflows/run_tests.yml). - Protobuf is formatted and linted with
buf format --diff --exit-code crates/proto/protoin thecheck_postgres_and_protobuf_migrationsjob. - Formatting-only commits are erased from history archaeology via
extras/zed/.git-blame-ignore-revs, whose header explains that GitHub picks the file up automatically for blame views.
There is no repo-root .editorconfig; the pinned formatters make it redundant.
Lint policy lives in three places, each with a distinct job.
First, [workspace.lints.clippy] in extras/zed/Cargo.toml denies a short list of correctness and hygiene lints (dbg_macro, todo, declare_interior_mutable_const, redundant_clone, disallowed_methods) and then does something unusual: it allows the entire style group, with the reasoning written into the manifest:
# We currently do not restrict any style rules
# as it slows down shipping code to Zed.
#
# Running ./script/clippy can take several minutes, and so it's
# common to skip that step and let CI do it. Any unexpected failures
# (which also take minutes to discover) thus require switching back
# to an old branch, manual fixing, and re-pushing.
style = { level = "allow", priority = -1 }Each additional allow carries a reason: single_range_in_vec_init ("We use vec![a..b] a lot when dealing with ranges in text"), too_many_arguments ("in Rust it can be very tedious to reduce argument count without running afoul of the borrow checker"), large_enum_variant, nonminimal_bool. The philosophy is explicit: deny only what is objectively wrong, never block a merge on taste, and document every exception.
Second, extras/zed/clippy.toml turns disallowed_methods into a project-specific API firewall, with a reason and a replacement per entry:
disallowed-methods = [
{ path = "std::process::Command::spawn", reason = "Spawning `std::process::Command` can block the current thread for an unknown duration", replacement = "smol::process::Command::spawn" },
{ path = "smol::Timer::after", reason = "smol::Timer introduces non-determinism in tests", replacement = "gpui::BackgroundExecutor::timer" },
{ path = "serde_json::from_reader", reason = "Parsing from a buffer is much slower than first reading the buffer into a Vec/String, ... Use `serde_json::from_slice` instead." },
]It also sets avoid-breaking-exported-api = false (internal workspace, no API stability debt) and allow-private-module-inception = true. extras/zed/script/clippy runs cargo clippy --workspace --release --all-targets --all-features -- --deny warnings, and when run locally (not in CI) it opportunistically chains cargo machete, typos, and buf lint if those tools are installed. CI-side warning denial is done without the RUSTFLAGS trap: extras/zed/.cargo/ci-config.toml is copied to ./../.cargo/config.toml on runners so cargo merges it with the repo config instead of clobbering it, and its long header comment explains exactly why RUSTFLAGS was rejected (it would override the entire config file, citing rust-lang/cargo#5376). The file uses [target.'cfg(all())'] rustflags = ["-D", "warnings"] because target tables merge cumulatively where [build] would not.
Third, custom compiler-plugin lints. extras/zed/tooling/lints is a dylint library (linked against clippy_utils at a pinned rev) that encodes rules no off-the-shelf linter knows: shared_string_from_str_literal (use SharedString::from_static for literals), async_block_without_await, entity_update_in_render, notify_in_render, owned_string_into_shared, and blocking_io_on_foreground (blocking IO on the main thread). The crate pins its own nightly via extras/zed/tooling/lints/rust-toolchain.toml and keeps itself out of the main workspace:
# Keep this crate out of the zed workspace. It pins its own nightly toolchain
# (see `rust-toolchain.toml`) to match `clippy_utils`.
[workspace]Individual crates can be stricter than the workspace: extras/zed/tooling/perf/Cargo.toml layers a full pedantic wall on top of the permissive workspace default:
[lints.clippy]
all = "warn"
pedantic = "warn"
missing_docs_in_private_items = "warn"
as_underscore = "deny"
allow_attributes = "deny"
allow_attributes_without_reason = "deny" # This covers `expect` also, since we deny `allow`
let_underscore_must_use = "forbid"
undocumented_unsafe_blocks = "forbid"
missing_safety_doc = "forbid"Conformity itself is linted: cargo xtask package-conformity (extras/zed/tooling/xtask/src/tasks/package_conformity.rs) walks every member with cargo_toml::Manifest and reports any crate missing [lints] workspace = true or using a non-workspace dependency (if !is_using_workspace_lints { eprintln!("{package:?} is not using workspace lints", ...) }).
Spell checking is configured as carefully as clippy: extras/zed/typos.toml (118 lines) excludes files only with a written justification per entry:
# Vim makes heavy use of partial typing tables.
"crates/vim/",
# We have some base64-encoded data that is incorrectly being flagged.
"crates/rpc/src/auth.rs",and sets check-filename = true so file names are spell-checked too.
The defining practice: workflows are Rust programs. Every YAML file in extras/zed/.github/workflows/ begins with:
# Generated from xtask::workflows::run_tests
# Rebuild with `cargo xtask workflows`.The generator lives in extras/zed/tooling/xtask/src/tasks/workflows/ (one module per workflow: run_tests.rs, release.rs, danger.rs, ...), built on a fork of the gh-workflow crate. CI itself guards the invariant: the check_scripts job runs cargo xtask workflows and fails if git diff --exit-code .github shows drift. Shared steps become Rust functions, which is why step names read like paths (steps::checkout_repo, run_tests::check_style::check_for_typos). 46 workflow files cover CI, releases, and a large amount of community automation (issue triage, stale-PR reminders, duplicate detection).
extras/zed/.github/workflows/run_tests.yml (982 generated lines) is the main gate:
- Triggers:
pull_request,pushtomainandv[0-9]+.[0-9]+.xstable branches, andmerge_group(GitHub merge queue). Most heavy jobs carrygithub.event_name != 'merge_group'so the merge queue re-runs only the cheap, high-signal subset (Linux clippy, style, migrations) after the full PR run already passed. - An
orchestratejob diffs against the merge base, maps changed directories to package names viacargo metadatapiped throughjq, and emits acargo nextestfilterset so test jobs run only reverse dependencies of what changed:
# Build nextest filterset with rdeps for each package
FILTERSET=$(echo "$ALL_CHANGED_PKGS" | \
sed 's/.*/rdeps(&)/' | \
tr '\n' '|' | \
sed 's/|$//')
echo "changed_packages=$FILTERSET" >> "$GITHUB_OUTPUT"Toolchain, .github/, or root Cargo.* changes force the full suite (grep -qP '^(rust-toolchain\.toml|\.cargo/|\.github/|Cargo\.(toml|lock)$)' in the same job), and downstream jobs splice the filter into the runner invocation: cargo nextest run --workspace --no-fail-fast --no-tests=warn${{ ... format(' -E "{0}"', needs.orchestrate.outputs.changed_packages) ... }}.
- OS coverage: clippy on four targets (Windows, Linux, macOS aarch64, macOS x86_64 via
rustup target add),cargo nextest run --workspace --no-fail-faston Windows, Linux, and macOS, with a digest-pinnedpostgres:15service container for collab tests on Linux. - Specialized jobs:
miri_scheduler(nightly Miri over theschedulercrate),doctests(cargo test --workspace --doc),check_workspace_binaries(cargo build --workspace --bins --examples),build_visual_tests_binary,check_wasm(cargo -Zbuild-std check --target wasm32-unknown-unknownfor two crates),check_dependencies(cargo-machete,cargo update --locked --workspace, crate-graph tests, and GitHubdependency-review-actionon PRs),check_docs(mdBook build plus two lychee link-check passes),check_licenses, and protobuf breaking-change detection withbuf-breaking-action. - The whole graph funnels into a single
tests_passaggregation job that reads everyneeds.*.resultand fails unless each issuccessorskipped; that one job is the required check, so the branch-protection list never changes when jobs are added:
check_result() {
echo "* $1: $2"
if [[ "$2" != "skipped" && "$2" != "success" ]]; then EXIT_CODE=1; fi
}
check_result "clippy_linux" "$RESULT_CLIPPY_LINUX"Security hardening is thorough: every action is pinned to a full commit SHA (enforced by "helpers:pinGitHubActionDigests" in extras/zed/renovate.json), Linux jobs start with step-security/harden-runner in egress-audit mode, top-level permissions: contents: read is the default, and the check_scripts job runs shellcheck over script/, actionlint (with runner labels declared in extras/zed/.github/actionlint.yml), and zizmor at min-severity: high. Caching is two-tier: a namespace-runner cache for ~/.rustup plus sccache writing to a Cloudflare R2 bucket, with CARGO_INCREMENTAL: '0' and a clear-target-dir-if-larger-than script guarding runner disks. Concurrency cancels superseded runs per ref but never on main (github.ref_name == 'main' && github.sha || 'anysha'), and every shell step runs under bash -euxo pipefail via workflow defaults. A Danger JS job (extras/zed/.github/workflows/danger.yml) lints PR descriptions themselves, routed through a token-less proxy (DANGER_GITHUB_API_BASE_URL: https://danger-proxy.zed.dev/github). Renovate batches updates weekly ("after 3pm on Wednesday") behind a dependency dashboard with approval.
Tests are colocated: #[cfg(test)] modules inside source files, plus dedicated sibling files for big suites (extras/zed/crates/editor/src/editor_tests.rs). Cross-crate test utilities ship behind a test-support cargo feature; the pattern appears over 800 times across crates/*/Cargo.toml, e.g. util = { workspace = true, features = ["test-support"] } in extras/zed/crates/cli/Cargo.toml dev-dependencies. This gives integration-style tests real fakes (in-memory fs::FakeFs, test app contexts) without shipping them in release builds.
The harness centerpiece is the #[gpui::test] proc macro (extras/zed/crates/gpui_macros/src/gpui_macros.rs), used in 334 files. Its doc comment explains the model: tests get a TestAppContext and an StdRng "seeded with the SEED environment variable and is used internally by the ForegroundExecutor and BackgroundExecutor to run tasks deterministically in tests." Supported arguments include iterations = N (run with seeds 0..N), seeds(10, 20, 30), retries, and on_failure = "path::to::reporter". Real usage: #[gpui::test(iterations = 100)] in extras/zed/crates/editor/src/display_map.rs:2743. Because async scheduling itself is derived from the seed, one attribute turns an ordinary test into a concurrency fuzzer, and the clippy.toml ban on smol::Timer::after ("introduces non-determinism in tests") keeps the whole codebase on the deterministic clock.
Beyond that:
- Property testing:
proptest(a pinned git rev with theattr-macrofeature) plus a customArbitrary for SumTree<T>impl and asum_treestrategy inextras/zed/crates/sum_tree/src/property_test.rs, exposed behindtest-supportso any dependent crate can generate trees:
impl<T> Arbitrary for SumTree<T>
where
T: Debug + Arbitrary + Item + 'static,
T::Summary: Debug + Summary<Context<'static> = ()>,
{
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
any::<Vec<T>>()
.prop_map(|vec| SumTree::from_iter(vec, ()))
.boxed()
}
}- Randomized distributed tests:
extras/zed/script/randomized-test-cigenerates a random u64 seed, runs the collab randomized suite against it, and on failure callsminimizeTestPlanfromscript/randomized-test-minimizeto shrink the failing operation plan before filing it. - Miri: CI runs
cargo +nightly -q miri test -p scheduleron every PR (run_tests.yml,miri_schedulerjob), targeting exactly the crate with the trickiest unsafe concurrency. - Benchmarks: Criterion (
criterionwithhtml_reportsin the workspace deps) across manybenches/dirs (crates/rope/benches,crates/fuzzy_nucleo/benches,crates/language/benches, plus dedicatedcrates/benchmarksandcrates/editor_benchmarkscrates). A separate perf harness (extras/zed/tooling/perf) wraps hyperfine: theperf-testcargo alias rebuilds with--cfg perf_enabledunder therelease-fastprofile, times tests marked#[perf], emits Markdown, andcargo perf-comparediffs saved JSON runs. - Doctests get their own CI job, and a
visual-testsfeature builds azed_visual_test_runnerbinary for screenshot-style verification. - The CLI surface is tested at the unit level in
extras/zed/crates/cliand end to end by CI building every workspace binary (check_workspace_binaries) and by the bundling workflows exercising real packaging on all three OS families.
The split is conventional and disciplined: anyhow for propagation (166 crate manifests depend on it) and thiserror where callers must match on causes (23 manifests). Two representative shapes:
#[derive(Debug, thiserror::Error)]
pub enum TrashRestoreError {
#[error("The specified `path` ({}) was not found in the system's trash.", path.display())]
NotFound { path: PathBuf },
...
}from extras/zed/crates/fs/src/fs.rs, and a struct error carrying full subprocess context in extras/zed/crates/git/src/repository.rs:
#[derive(Error, Debug)]
#[error("Git command failed:\n{stdout}{stderr}\n")]
struct GitBinaryCommandError {
stdout: String,
stderr: String,
status: ExitStatus,
}which callers recover through error.downcast_ref::<GitBinaryCommandError>() (same file, around line 3098), a deliberate pattern: anyhow at the surface, typed recovery where it matters.
Result discipline is supported by helpers in extras/zed/crates/util/src/util.rs: a ResultExt extension trait whose log_err() converts Result<T, E> into Option<T> while logging, so background failures are visible without unwinding the UI. Panic policy is graded: some_or_debug_panic in extras/zed/crates/gpui_util/src/lib.rs panics under debug_assertions and degrades to None in release; production panics are captured as minidumps and uploaded to Sentry by extras/zed/crates/zed/src/reliability.rs; and the PR template requires "Unsafe blocks (if any) have justifying comments" (extras/zed/.github/pull_request_template.md). The CLI forwards child exit codes faithfully: std::process::exit(status.code().unwrap_or(1)) in extras/zed/crates/cli/src/main.rs.
API design leans on fluent builders generated by macros rather than hand-written ones: the Styled trait in extras/zed/crates/gpui/src/styled.rs pulls in gpui_macros::margin_style_methods!() and friends to produce a Tailwind-like chainable surface (div().flex().size_full()). Newtypes are pervasive: pub struct ReplicaId(u16) with named constants LOCAL and REMOTE_SERVER (extras/zed/crates/clock/src/clock.rs), pub struct SharedString(SmolStr) (extras/zed/crates/gpui_shared_string/gpui_shared_string.rs). Visibility discipline is mostly structural, 243 crates make crate boundaries the visibility boundaries, and public-surface crates opt into #![deny(missing_docs)] (extras/zed/crates/theme/src/theme.rs, extras/zed/crates/release_channel/src/lib.rs) while gpui runs #![warn(missing_docs)].
-
Generic B-tree over summaries with a GAT context.
SumTree(extras/zed/crates/sum_tree/src/sum_tree.rs) definestrait Summary { type Context<'a>: Copy; fn zero(cx) -> Self; fn add_summary(&mut self, other, cx); }andtrait Dimension<'a, S: Summary>so the same tree can be sought by bytes, chars, or lines. A blanketimpl<T: ContextLessSummary> Summary for Tplus aNoSummarymarker avoids blanket-impl collisions, with the reasoning documented in a comment on the impl. -
Cheap immutable strings.
SharedString(SmolStr)derefs tostr, has aconst fn new_static(&'static str), and a custom dylint lint (owned_string_into_sharedinextras/zed/tooling/lints) rejects allocating conversions from literals intoSharedString,Arc<str>,Rc<str>, orCow<'_, str>. -
Workspace-wide hasher swap by alias.
extras/zed/crates/collections/src/collections.rsre-exports the whole standard collection vocabulary with faster defaults, so every crate importscollections::HashMapand the hashing strategy is a one-file decision:pub type HashMap<K, V> = FxHashMap<K, V>; pub type HashSet<T> = FxHashSet<T>; pub type IndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>; pub type TypeIdHashMap<V> = std::collections::HashMap<std::any::TypeId, V, gpui_util::TypeIdHashBuilder>;
-
?in any context. Themaybe!macro inextras/zed/crates/gpui_util/src/lib.rsexpands to an immediately-invoked closure, enabling early-return chains inside functions that do not returnResult:/// Expands to an immediately-invoked function expression. Good for using the ? operator /// in functions which do not return an Option or Result. macro_rules! maybe { ($block:block) => { (|| $block)() }; (async move $block:block) => { (async move || $block)() }; }
-
Distributed registration via
inventory.extras/zed/crates/gpui/src/action.rsdeclaresmacro_rules! actions!andinventory::collect!(MacroActionBuilder)(line 282); any crate can register keyboard actions and the app enumerates them at startup withinventory::iter, no central registry file to merge-conflict on. -
Determinism as an architectural property. The test dispatcher runs all async tasks from a seeded RNG (Section 7), and the lint wall (
clippy.tomldisallowed-methods) makes non-deterministic APIs unreachable, turning schedule fuzzing into#[gpui::test(iterations = 100)]. -
Interior mutability, chosen narrowly.
parking_lotis the workspace lock (extras/zed/Cargo.toml),declare_interior_mutable_constis denied workspace-wide, andclippy.tomldocuments the one accepted exception viaignore-interior-mutabilityforagent_ui::context::AgentContextKey"as the Eq and Hash impls do not use fields with interior mutability." -
Platform handling by crate, then by target table. The windowing layer is split into
crates/gpui_macos,crates/gpui_linux,crates/gpui_windows,crates/gpui_webbehindcrates/gpui_platform, whose manifest selects them with[target.'cfg(target_os = "macos")'.dependencies]tables (extras/zed/crates/gpui_platform/Cargo.toml); even the CLI has four per-OS dependency tables (extras/zed/crates/cli/Cargo.toml). -
Unsafe policy at the edge.
extras/zed/crates/gpui_windows/src/window.rsopens with#![deny(unsafe_op_in_unsafe_fn)];tooling/perfforbidsundocumented_unsafe_blocks; and small named helpers turn invariants into readable panics, e.g.CapacityResultExt::unwrap_oobinextras/zed/crates/sum_tree/src/sum_tree.rswith the message "item should fit into fixed size ArrayVec". -
Zero-copy text traversal. The rope exposes borrowed iterators,
pub fn chunks(&self) -> Chunks<'_>andchunks_in_rangeover apub struct Chunks<'a>cursor (extras/zed/crates/rope/src/rope.rs), so search, rendering, and diffing walk&strchunks without materializing the buffer. -
CRDT plumbing with cache-friendly types. Vector clocks store observed Lamport timestamps in a
SmallVec(deletions: SmallVec<[clock::Lamport; 2]>inextras/zed/crates/text/src/text.rs), andReplicaId(u16)keeps identifiers copyable and tiny. -
Proc-macro leverage.
extras/zed/crates/gpui_macros/src/contains twelve macro modules (derives forRender,IntoElement, action registration, style-method generation, a#[gpui::bench]Criterion bridge, and the test macro), concentrating boilerplate where the compiler can generate it.
User documentation is an mdBook rooted at extras/zed/docs/book.toml, with a twist: the HTML renderer is wrapped by a first-party crate (command = "cargo run -p docs_preprocessor -- postprocess" under [output.zed-html]), because "post-processing is not possible with mdbook in the same way pre-processing is" (comment in the same file). Docs are built and link-checked in CI (check_docs job runs lychee twice, on sources and on rendered output, configured by extras/zed/lychee.toml with retry and status-code policy), and deployed by deploy_docs.yml and deploy_nightly_docs.yml.
Contributor documentation lives in extras/zed/CONTRIBUTING.md, which is unusually candid about culture ("The Zed culture values working code and synchronous conversations over long discussion threads") and routes big features to a written process doc at extras/zed/docs/src/development/feature-process.md. Per-platform development guides sit in extras/zed/docs/src/development/ (macos.md, linux.md, windows.md, freebsd.md, debugging-crashes.md, glossary.md, release-notes.md).
Rustdoc conventions: public-surface crates deny or warn on missing_docs (Section 8); macro entry points carry executable usage documentation (the #[gpui::test] doc block in extras/zed/crates/gpui_macros/src/gpui_macros.rs enumerates every accepted argument with examples); and design rationale is written next to the code it justifies (the NoSummary impl comment in sum_tree.rs). Process templates: extras/zed/.github/ISSUE_TEMPLATE/ uses YAML issue forms (10_bug_report.yml, 11_crash_report.yml), and the PR template ends in a five-item self-review checklist covering security, unsafe justification, UI guidelines, tests, and performance. Reviewer routing is data, not tribal knowledge: extras/zed/REVIEWERS.conl maps code areas to volunteer reviewers.
Zed releases on channels, modeled in code: ReleaseChannel::{Dev, Nightly, Preview, Stable} in extras/zed/crates/release_channel/src/lib.rs, resolved once through a LazyLock:
pub static RELEASE_CHANNEL: LazyLock<ReleaseChannel> =
LazyLock::new(|| match ReleaseChannel::from_str(&RELEASE_CHANNEL_NAME) {The product version is the zed crate version (1.17.0 in extras/zed/crates/zed/Cargo.toml), bumped by generated workflows (bump_zed_version.yml, bump_patch_version.yml) and branched to v[0-9]+.[0-9]+.x stable branches with a cherry_pick.yml helper for hotfixes. The channel names even flow into platform identifiers (ReleaseChannel::Nightly => "Zed-Editor-Nightly" in the same file), so parallel installs of different channels never collide.
Pushing a v* tag triggers extras/zed/.github/workflows/release.yml (1,029 lines), which re-runs the full test suite on macOS and Linux, then fans out to bundling jobs (run_bundling.yml builds macOS, Linux, Windows, and FreeBSD artifacts), and finally drafts the GitHub release: release notes are assembled from merged PRs by script/draft-release-notes and published via script/create-draft-release, so changelog discipline is enforced upstream by the Danger job that checks each PR carries a "Release Notes:" section (Renovate PRs even get "prFooter": "Release Notes:\n\n- N/A" in extras/zed/renovate.json). Nightly is a cron: 0 */4 * * * in extras/zed/.github/workflows/release_nightly.yml checks the nightly tag and rebuilds every four hours. Distribution beyond GitHub releases includes an in-app updater (crates/auto_update, crates/auto_update_helper), an install script (extras/zed/script/install.sh), Nix packaging (extras/zed/flake.nix, extras/zed/nix/), and Flatpak/snap scripts under script/.
The CLI generates completions for six shells, including two most projects forget: extras/zed/crates/cli/src/completions.rs defines a Shell value-enum covering Bash, Elvish, Fish, Nushell, PowerShell, and Zsh, implementing clap_complete::Generator by delegating to clap_complete's shells plus clap_complete_nushell.
quinjet already has the strict clippy wall, rustfmt, cargo-deny, taplo, typos, a coverage floor, miri, and mutants. What zed adds on top of that baseline, each with its exact mechanism:
- Turn the lint wall into an API firewall. Add
disallowed-methodsentries toclippy.tomlwithreasonandreplacementkeys for quinjet-specific hazards, e.g. banstd::process::Command::spawnoutside the one sanctioned Git-execution module, exactly asextras/zed/clippy.tomlbans it in favor ofsmol. For a TUI, also ban directprintln!/eprintln!paths that would corrupt the alternate screen. - CI-only
-D warningswithout RUSTFLAGS. Copy the trick fromextras/zed/.cargo/ci-config.toml: keep a second cargo config containing[target.'cfg(all())'] rustflags = ["-D", "warnings"], copied into a parent.cargo/config.tomlon CI so it merges with the repo config instead of replacing it. - Seeded deterministic test iteration. Adopt the
#[gpui::test(iterations = N)]idea at quinjet scale: useproptestfor state-machine tests over Git operations, and honorSEED/ITERATIONSenvironment variables in a small attr macro or test helper, as documented inextras/zed/crates/gpui_macros/src/gpui_macros.rs. -
cargo nextestas the runner.cargo nextest run --no-fail-fast --no-tests=warn(installed in CI viataiki-e/install-actionwithtool: nextest, perextras/zed/.github/workflows/run_tests.yml) gives per-test isolation, retries, and better CI output thancargo test. - A single aggregation gate job. Replicate the
tests_passpattern: one job withneeds:on everything,if: always(), iteratingneeds.*.resultand accepting onlysuccessorskipped, so branch protection references exactly one check forever. - Workflow security hardening. Pin every action to a commit SHA and let Renovate maintain the pins (
"helpers:pinGitHubActionDigests"inextras/zed/renovate.json); addpermissions: contents: readat workflow top level; runactionlintandzizmor(viazizmorcore/zizmor-action) in CI; start Linux jobs withstep-security/harden-runnerin egress-audit mode. - Merge queue awareness. Enable GitHub merge queue and add
merge_group: {}to the CIon:block, gating the expensive jobs withgithub.event_name != 'merge_group'asrun_tests.ymldoes, so queue throughput stays high. - Dev-profile build speed. Steal the profile block from
extras/zed/Cargo.toml:split-debuginfo = "unpacked",debug = "limited",[profile.dev.package]withopt-level = 3forsyn,quote,proc-macro2, and any heavy parser dependencies; for release,lto = "thin"withcodegen-units = 1. - Unused-dependency and lockfile checks. Add
cargo machete(with[workspace.metadata.cargo-machete] ignored = [...]for false positives) and acargo update --locked --workspacestep to CI, both from thecheck_dependenciesjob inrun_tests.yml. -
.git-blame-ignore-revs. Record formatting-only commits there so blame stays useful; GitHub honors the file automatically (header comment inextras/zed/.git-blame-ignore-revs). - Completions for all six shells. quinjet already uses clap; add
clap_complete_nushellnext toclap_completeand mirror theShellvalue-enum plusGeneratorimpl fromextras/zed/crates/cli/src/completions.rsto cover Bash, Zsh, Fish, PowerShell, Elvish, and Nushell. - Typed errors where callers branch. Keep anyhow at the surface but introduce a
GitBinaryCommandError { stdout, stderr, status }-style thiserror type for subprocess failures, recovered viadowncast_ref, as inextras/zed/crates/git/src/repository.rs; forward child exit codes withexit(status.code().unwrap_or(1))as inextras/zed/crates/cli/src/main.rs. - Documented lint exceptions. Every
allowin quinjet's clippy wall should carry a comment stating why, in the style of the annotated allows inextras/zed/Cargo.toml[workspace.lints.clippy]; undocumented exceptions rot. - Criterion benchmarks with a comparison story. Add a
benches/directory using workspacecriterionwithhtml_reports, and consider theperf-test/perf-comparecargo-alias pattern fromextras/zed/.cargo/config.tomlfor tracking regressions between runs. - If a project-specific rule cannot be expressed in
clippy.toml, a dylint library is the escalation path: acdylibcrate depending onclippy_utilsanddylint_linting, registered under[workspace.metadata.dylint]and pinned to its own nightly, exactly asextras/zed/tooling/lintsis structured.
ripgrep is a line-oriented search tool that recursively searches a directory
tree for a regex pattern while respecting gitignore rules. The root manifest
states the mission directly, in extras/ripgrep/Cargo.toml:
description = """
ripgrep is a line-oriented search tool that recursively searches the current
directory for a regex pattern while respecting gitignore rules. ripgrep has
first class support on Windows, macOS and Linux.
"""Industry adoption follows from two properties visible in the clone itself.
First, it is a single static binary with first-class support on every major
platform, produced for 14 targets by extras/ripgrep/.github/workflows/release.yml.
Second, it is not a monolith: the hard parts are published as reusable
library crates (globset, ignore, grep-searcher, grep-printer, and so
on), each with its own docs.rs link and README. extras/ripgrep/crates/core/README.md
says so explicitly:
much of the heavy lifting of ripgrep is done via its constituent crates,
which can be reused independent of ripgrep.
Scale indicators measured directly from the clone (HEAD is commit
3fce3b5bb0236da2df6d99672afb8a719642eca7, package version 15.2.0):
| Metric | Value |
|---|---|
| Rust source files | 110 |
| Total Rust LOC | 56,386 |
LOC under crates/
|
50,356 |
LOC under tests/ (integration suite) |
5,777 |
| Workspace member crates | 10 (plus the root ripgrep package) |
| Standalone packages outside the workspace | 1 (fuzz/) |
unsafe sites across all crates |
5 |
| Largest single file |
crates/core/flags/defs.rs at 8,161 lines |
The 10 workspace members are listed in extras/ripgrep/Cargo.toml:
crates/globset, crates/grep, crates/cli, crates/index,
crates/matcher, crates/pcre2, crates/printer, crates/regex,
crates/searcher, crates/ignore.
ripgrep/
|-- Cargo.toml root package (the rg binary) + [workspace]
|-- build.rs embeds git hash, Windows manifest linking
|-- rustfmt.toml 3 lines of formatting policy
|-- .cargo/config.toml per-target rustflags (static CRT)
|-- CHANGELOG.md 90 KB of release notes
|-- GUIDE.md 40 KB user guide
|-- FAQ.md 42 KB frequently asked questions
|-- RELEASE-CHECKLIST.md human release runbook
|-- ci/ shell helpers used by workflows
| |-- test-complete zsh script diffing --help vs completions
| `-- ubuntu-install-packages
|-- .github/
| |-- ISSUE_TEMPLATE/ bug_report.yml, feature_request.md, config.yml
| `-- workflows/ ci.yml, release.yml
|-- crates/
| |-- core/ binary source, no own Cargo.toml
| | |-- main.rs entry point (root [[bin]] points here)
| | |-- flags/ the entire CLI surface
| | `-- index/ feature-gated indexing (enabled.rs/disabled.rs)
| |-- matcher/ grep-matcher: the Matcher trait
| |-- regex/ grep-regex: default engine
| |-- pcre2/ grep-pcre2: optional engine
| |-- searcher/ grep-searcher: line-oriented search executor
| |-- printer/ grep-printer: standard/JSON/summary output
| |-- cli/ grep-cli: CLI plumbing utilities
| |-- globset/ glob matching (widely reused)
| |-- ignore/ gitignore + parallel directory walker
| `-- grep/ facade crate re-exporting the above
|-- tests/ one integration test binary against the real rg
|-- fuzz/ cargo-fuzz package, excluded from the workspace
|-- benchsuite/ Python benchmark runner + committed result runs
|-- pkg/
| |-- brew/ripgrep-bin.rb Homebrew formula (HomebrewFormula symlinks here)
| `-- windows/Manifest.xml long-path-aware manifest linked by build.rs
`-- scripts/copy-examples keeps doc code blocks and examples in sync
The split works because the dependency arrows only point one way: core is
pure glue over the published crates, and each library crate has a single
responsibility with its own README, LICENSE pair, and version. An unusual
detail: the binary's source lives in crates/core/ but that directory has no
manifest. The root package claims it via extras/ripgrep/Cargo.toml:
[[bin]]
bench = false
path = "crates/core/main.rs"
name = "rg"So the repository root is the binary crate, and crates/ holds both its
source and its libraries in one uniform place.
Workspace inheritance is used for exactly the two keys that must stay in
lockstep, in extras/ripgrep/Cargo.toml:
[workspace.package]
edition = "2024"
rust-version = "1.96"Member crates opt in with edition.workspace = true and
rust-version.workspace = true. Crucially, inheritance is not forced where it
would be wrong: extras/ripgrep/crates/globset/Cargo.toml and
extras/ripgrep/crates/ignore/Cargo.toml both pin their own
rust-version = "1.88", because those crates are consumed by third parties
with older toolchains than the binary requires. MSRV is a per-crate contract,
not a workspace-wide slogan, and CI enforces the binary's MSRV with a
pinned build using rust: 1.96.0 in extras/ripgrep/.github/workflows/ci.yml.
Other notable manifest practices:
-
Version lines carry a machine-readable marker, e.g.
version = "0.4.20" #:versioninextras/ripgrep/crates/globset/Cargo.toml. The#:versioncomment is the anchor for thecargo-uprelease tool named inextras/ripgrep/RELEASE-CHECKLIST.md. -
autotests = falseplus an explicit[[test]] name = "integration"pointing attests/tests.rscollapses the whole end-to-end suite into one test binary, which shares one harness and links once. -
Dependencies that need trimming get the long form with explicit features, as in
extras/ripgrep/crates/globset/Cargo.toml:[dependencies.regex-automata] version = "0.4.18" default-features = false features = ["std", "perf", "syntax", "meta", "nfa", "hybrid"]
-
A renamed dependency documents a fork migration in place:
memmap = { package = "memmap2", version = "0.9.0" }inextras/ripgrep/crates/searcher/Cargo.toml. -
Platform-conditional dependencies are the norm:
[target.'cfg(windows)'.dependencies.winapi-util]inextras/ripgrep/crates/cli/Cargo.toml, and the allocator swap in the root manifest applies only tocfg(all(target_env = "musl", target_pointer_width = "64")). -
Feature flags are additive and forwarded: the root
pcre2feature maps togrep/pcre2, which maps to the optionalgrep-pcre2crate. The risky in-development feature is named honestly:unstable-index = ["dep:grep-index"]. Deprecated features are kept as documented no-ops rather than removed (simd-accel = []with aDEPRECATEDcomment in several manifests), which preserves downstream builds. -
Profiles are layered. The everyday release profile keeps
debug = 1so backtraces from users are useful. Shipping builds use a dedicated profile:[profile.release-lto] inherits = "release" opt-level = 3 debug = "none" strip = "symbols" lto = "fat" panic = "abort" codegen-units = 1
and
[profile.deb]inheritsrelease-ltoforcargo deb. -
package.metadata.debin the root manifest declares the full Debian asset map, including generated man pages and completions. -
extras/ripgrep/.cargo/config.tomlsets-C target-feature=+crt-staticfor MSVC targets andlink-self-contained=yesfor musl, so distributed binaries are truly static. -
The fuzz package (
extras/ripgrep/fuzz/Cargo.toml) setspublish = falseand its own[workspace]table so it never pollutes the main lockfile.
There are no [lints] tables anywhere in the repository.
extras/ripgrep/rustfmt.toml is three lines:
max_width = 79
use_small_heuristics = "max"
edition = "2024"-
max_width = 79: the classic terminal width, stricter than rustfmt's 100 default; it keeps side-by-side diffs readable. -
use_small_heuristics = "max": all the width-based heuristics (when to break a struct literal, a chain, an argument list) are allowed to use the fullmax_width, producing denser, more horizontal code. -
edition = "2024": keeps rustfmt parsing in sync with the workspace edition even when invoked standalone.
Enforcement is a dedicated CI job in
extras/ripgrep/.github/workflows/ci.yml running
cargo fmt --all --check. There is no .editorconfig and no formatter for
non-Rust files; shell and Python under ci/ and benchsuite/ are formatted
by hand. One interesting committed editor file, extras/ripgrep/.nvim.lua,
configures rust-analyzer to check with features = 'all', so anyone opening
the repo in Neovim analyzes the same feature set CI builds.
The headline finding: ripgrep uses no clippy at all. There is no
clippy.toml, no [lints] table, no clippy CI job, and zero clippy::
attributes in the source tree. The lint strategy is instead built from three
narrow, high-signal gates:
- Every published library crate denies missing documentation at the crate
root:
#![deny(missing_docs)]appears inextras/ripgrep/crates/cli/src/lib.rs,extras/ripgrep/crates/matcher/src/lib.rs,extras/ripgrep/crates/regex/src/lib.rs,extras/ripgrep/crates/pcre2/src/lib.rs,extras/ripgrep/crates/printer/src/lib.rs,extras/ripgrep/crates/ignore/src/lib.rs,extras/ripgrep/crates/globset/src/lib.rs, andextras/ripgrep/crates/searcher/src/lib.rs. The one exception is the explicitly unstable crate:extras/ripgrep/crates/index/src/lib.rsopens with#![allow(warnings)], an honest marker for code still in flux. - Rustdoc is a lint pass. The
docsjob inextras/ripgrep/.github/workflows/ci.ymlrunsRUSTDOCFLAGS: -D warningswithcargo doc --no-deps --document-private-items --workspace, so broken intra-doc links and malformed docs fail CI, including on private items. - Invariants are checked by purpose-built tests rather than generic lints.
extras/ripgrep/crates/core/flags/defs.rscontains an inventory test that walks the globalFLAGSslice and prints which ASCII short flags remain unclaimed, and CI runs it visibly (cargo test --bin rg ... flags::defs::tests::available_shorts -- --nocapture).extras/ripgrep/ci/test-completeparsesrg --helpoutput with ripgrep itself and diffs the flag list against the hand-written zsh completion inextras/ripgrep/crates/core/flags/complete/rg.zsh, failing CI when the two drift.
Suppressions are correspondingly rare: only 16 occurrences of allow( exist
across roughly 50,000 lines under crates/, and each is targeted, such as
#[allow(dead_code)] // unused on Windows in extras/ripgrep/tests/util.rs.
The philosophy is legible: invest in documentation completeness, doc
correctness, and domain-specific consistency checks; skip style lawyering.
extras/ripgrep/.github/workflows/ci.yml triggers on pull_request, on
pushes to master, and on a nightly cron (00 01 * * *). The first thing in
the file after the triggers is a least-privilege block with an unusually
thorough justification comment:
# By specifying any permission explicitly all others are set
# to none. By using the principle of least privilege the damage a compromised
# workflow can do (because of an injection or compromised third party tool or
# action) is restricted.
permissions:
# to fetch code (actions/checkout)
contents: readThe test job is an 18-entry include matrix with fail-fast: false:
channel coverage (pinned 1.96.0, stable, beta, nightly) plus target
coverage via cross (musl, i686, aarch64 gnu and musl, three armv7 flavors,
powerpc64, s390x, riscv64gc), plus macOS, two Windows toolchains, and
windows-11-arm. Cross-compiled targets run the full test suite under qemu,
so ripgrep's integration tests execute the real binary even on big-endian
s390x. cross itself is pinned (CROSS_VERSION: v0.2.5) and installed from
a prebuilt release tarball, with the reason recorded inline:
# In the past, new releases of 'cross' have broken CI. So for now, we
# pin it. We also use their pre-compiled binary releases because cross
# has over 100 dependencies and takes a bit to compile.Tests run twice per platform where affordable: once with
--features unstable-index and once with --features pcre2; under emulation
the PCRE2 pass is skipped with a comment explaining the runtime cost. Debug
aids are built into the pipeline: a step dumps the newest build.rs stderr
file from the target directory, and two --nocapture test invocations print
the detected hostname and the free short flags.
Four more jobs: wasm (build for wasm32-wasip1), rustfmt
(cargo fmt --all --check), docs (rustdoc with -D warnings), and
fuzz_testing (installs cargo-fuzz, then cargo check on the fuzz
package so targets can never rot).
Notably absent: any caching (no actions/cache, no sccache) and any merge
queue configuration. Every build is from scratch, trading minutes for
reproducibility. Actions are referenced at three pinning levels:
actions/checkout@v4 (major tag), dtolnay/rust-toolchain@master
(deliberately floating, it is a toolchain installer), and, in the release
workflow, full commit-SHA pinning for the supply-chain-sensitive step:
- name: Attest build provenance
uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0extras/ripgrep/.github/workflows/release.yml triggers only on tags
matching "[0-9]+.[0-9]+.[0-9]+" and escalates permissions explicitly
(contents: write, id-token: write, attestations: write for provenance
signing). A create-release job verifies the tag equals the manifest
version before anything builds:
if ! grep -q "version = \"$VERSION\"" Cargo.toml; then
echo "version does not match Cargo.toml" >&2
exit 1
fithen creates a draft release with gh release create $VERSION --draft --verify-tag. The build-release job fans out over 14 targets, builds with
--profile release-lto --features pcre2 and PCRE2_SYS_STATIC=1, strips
foreign-arch binaries by running the target's strip tool inside the
ghcr.io/cross-rs Docker image, and generates the man page and all four
shell completions by executing the just-built binary, under qemu when the
architecture demands it. Archives get sha256 sums and provenance
attestations before gh release upload. A third job builds a .deb with
cargo-deb, working around its inability to reference build-time assets by
generating the man page and completions into deployment/deb/ first.
The layout is a textbook unit/integration split. Unit tests live inline in
#[cfg(test)] mod tests blocks next to the code, including one test per flag
directly under each impl Flag in extras/ripgrep/crates/core/flags/defs.rs
(parse_low_raw(["-A5"]) style assertions covering every spelling of every
flag). Integration tests are one binary, mapped in
extras/ripgrep/tests/tests.rs with a comment-documented module list:
binary (binary file handling), feature (1,174 lines, per-feature tests),
json, misc, multiline, and regression (1,744 lines of tests named
after issue numbers), plus infrastructure modules macros, hay (a shared
Sherlock Holmes corpus), and util.
The harness in extras/ripgrep/tests/util.rs is the pattern worth stealing:
setup(test_name) returns a (Dir, TestCommand) pair, where Dir creates
an isolated scratch directory using a global AtomicUsize counter and
TestCommand wraps std::process::Command pointed at the compiled rg
with its working directory set to the scratch dir. Every end-to-end test
therefore runs the real user-facing binary. The rgtest! macro in
extras/ripgrep/tests/macros.rs then doubles coverage for free:
macro_rules! rgtest {
($name:ident, $fun:expr) => {
#[test]
fn $name() {
let (dir, cmd) = crate::util::setup(stringify!($name));
$fun(dir, cmd);
if cfg!(feature = "pcre2") {
let (dir, cmd) = crate::util::setup_pcre2(stringify!($name));
$fun(dir, cmd);
}
}
};
}Each of the 334 rgtest! invocations runs once per regex engine. A
companion eqnice! macro prints expected and actual output between tilde
rulers, a hand-rolled substitute for snapshot tooling that keeps failures
readable without any dev-dependency.
Other layers:
- Library-internal harness:
extras/ripgrep/crates/searcher/src/testutil.rsprovides aRegexMatcherwhose line-terminator optimization can be forced on or off, so searcher tests exercise both fast and slow paths on the same inputs. - Data-driven fixtures:
extras/ripgrep/crates/ignore/tests/pairs test files with real.gitignorefixtures such asgitignore_matched_path_or_any_parents_tests.gitignore. - Fuzzing with property assertions:
extras/ripgrep/fuzz/fuzz_targets/fuzz_glob.rsis a libFuzzer target that asserts round-trip invariants (Glob::newequalsGlob::from_str;glob.glob()reproduces the input), enabled by an optionalarbitraryfeature with derive support declared inextras/ripgrep/crates/globset/Cargo.toml. CI compiles the fuzz targets on every run so they cannot bit-rot. - Benchmarks at two levels: micro-benchmarks in
extras/ripgrep/crates/globset/benches/bench.rs, and a full comparative macro-benchmark suite,extras/ripgrep/benchsuite/benchsuite(a Python 3 runner over multi-gigabyte subtitle corpora), with historical results committed underextras/ripgrep/benchsuite/runs/going back to 2016. - The public CLI surface is additionally cross-checked by
extras/ripgrep/ci/test-complete, which diffs flags parsed out ofrg --helpagainst the zsh completion spec.
The split is disciplined: the binary uses anyhow (declared in
extras/ripgrep/Cargo.toml), while every library defines a hand-written
error type; neither thiserror nor any other derive-based error crate
appears anywhere. extras/ripgrep/crates/globset/src/lib.rs has a struct Error wrapping a pub enum ErrorKind whose variants document themselves,
including deprecated variants kept for compatibility with an explanation:
/// **DEPRECATED**.
///
/// This error used to occur for consistency with git's glob specification,
/// but the specification now accepts all uses of `**`. ...
InvalidRecursive,extras/ripgrep/crates/regex/src/error.rs follows the same kind-wrapped
shape with private constructors (Error::regex, Error::generic) that
translate regex_automata errors into domain terms.
Exit-code discipline is exemplary. extras/ripgrep/crates/core/main.rs
declares fn main() -> ExitCode, maps a broken pipe found anywhere in the
anyhow chain to exit 0 (matching Unix convention, with a comment explaining
why Rust programs must do this manually), prints other errors as {:#} and
returns 2. The 0/1/2 convention (match/no match/error) is computed in run
from the search result combined with a global errored flag.
extras/ripgrep/crates/core/messages.rs implements the non-fatal error
policy: per-file errors print a message and flip a static ERRORED: AtomicBool, the search continues, and the final exit status consults the
flag. Error printing itself is careful about interleaving, via a macro that
locks stdout before writing to stderr (quoted in section 9).
API-design patterns visible across the crates:
- Builders everywhere, all
&self-consuming-config style:SearcherBuilder::buildinextras/ripgrep/crates/searcher/src/searcher/mod.rs,StandardBuilder::build<W: WriteColor>inextras/ripgrep/crates/printer/src/standard.rs,WalkBuilderinextras/ripgrep/crates/ignore/src/walk.rs. - Newtypes over private enums to keep representation changeable:
pub struct MmapChoice(MmapChoiceImpl)inextras/ripgrep/crates/searcher/src/searcher/mmap.rs,pub struct LineTerminator(LineTerminatorImp)andpub struct ByteSet(BitSet)inextras/ripgrep/crates/matcher/src/lib.rs. - Invariant-carrying newtype:
Matchin the matcher crate is aCopyrange that assertsstart <= endat construction and implements slice indexing. - Error plumbing as a trait:
SinkErrorinextras/ripgrep/crates/searcher/src/sink.rsdefines constructor hooks (error_message,error_io,error_config) sostd::io::Errorworks out of the box while custom error types remain possible; the matcher crate offerspub struct NoError(())for infallible matchers. - A tri-state parse result instead of overloading
Result:enum ParseResult<T> { Special(SpecialMode), Ok(T), Err(anyhow::Error) }inextras/ripgrep/crates/core/flags/parse.rs, letting-h/-Vshort circuit before config files are even read. - Visibility is tight: the whole flag system is
pub(crate), struct fields are private with accessors, and shared config is wrapped aspub struct HyperlinkConfig(Arc<HyperlinkConfigInner>)inextras/ripgrep/crates/printer/src/hyperlink/mod.rs. - Panic policy: panics mark programmer errors only (
Match::newdocuments its panic), user-facing failures areResults, and shipped binaries build withpanic = "abort"via therelease-ltoprofile.
-
Trait-object plugin registry for flags. Every CLI flag is a unit struct implementing the
Flagtrait, collected into one global&[&dyn Flag]slice. The trait bound list inextras/ripgrep/crates/core/flags/mod.rsis itself instructive:trait Flag: Debug + Send + Sync + UnwindSafe + RefUnwindSafe + 'static {
One implementation carries the parser behavior, the short/long names, the
-htext, the--helptext, and the roff man-page text (doc_short/doc_longinextras/ripgrep/crates/core/flags/defs.rs), so help, man page, and completions can never disagree with the parser. -
Internal iteration as a deliberate trait-design choice. The matcher crate documents why it uses the push model, in
extras/ripgrep/crates/matcher/src/lib.rs:A key design decision made in this crate is the use of *internal iteration*, or otherwise known as the "push" model of searching.with two stated reasons: some engines cannot expose external iterators, and Rust's type system makes a generic pull-model interface cost either ergonomics or performance.
-
Callback trait with associated error type and default methods.
Sinkinextras/ripgrep/crates/searcher/src/sink.rsrequires onlymatched;context,context_break,begin, andfinishhave default bodies, and returningOk(false)anywhere stops the search, which is how--max-countstyle limits compose without special cases. -
Zero-copy path printing with
Cowand platformcfgon a struct field.extras/ripgrep/crates/printer/src/util.rs:pub(crate) struct PrinterPath<'a> { #[cfg(not(unix))] path: &'a Path, bytes: Cow<'a, [u8]>, hyperlink: OnceCell<Option<HyperlinkPath>>, }
On Unix the borrowed bytes are the path, so nothing allocates; only Windows pays for UTF-8 conversion, and the hyperlink form is computed lazily via
OnceCellinterior mutability. -
Cowin an algorithmic hot path. The did-you-mean flag suggester inextras/ripgrep/crates/core/flags/parse.rsbuilds 3-gram bags asBTreeSet<Cow<'a, [u8]>>: real windows borrow (slice.windows(3).map(Cow::Borrowed)), while short names get padded owned grams, then a Jaccard index ranks candidates. -
Work-stealing parallelism from
crossbeam-deque, not a thread pool crate.extras/ripgrep/crates/ignore/src/walk.rsbuildsWalkParallelonStealer/Workerdeques (stealers: Arc<[Stealer<Message>]>at line 1655) and exposes backpressure through a control-flow enum,pub enum WalkState(Continue,Skip,Quit), returned by user visitors. -
Modern std lazies instead of
lazy_static/once_celldependencies:static RE: OnceLock<Regex>inextras/ripgrep/crates/ignore/src/gitignore.rs,static P: OnceLock<Parser>inextras/ripgrep/crates/core/flags/parse.rs, andstatic DOC: LazyLock<String>for a computed doc string inextras/ripgrep/crates/core/flags/defs.rs. Global state that must be mutable is confined to threeAtomicBools inextras/ripgrep/crates/core/messages.rs. -
Unsafe as a priced-in API contract. The entire tree has five
unsafesites: twolibccalls inextras/ripgrep/crates/cli/src/hostname.rs, two in the mmap module, and one call site inextras/ripgrep/crates/core/flags/hiargs.rs. The interesting one is thatMmapChoice::auto()inextras/ripgrep/crates/searcher/src/searcher/mmap.rsis anunsafe fnwhose safety comment admits the contract is environmental:This constructor is not safe because there is no obvious way to encapsulate the safety of file backed memory maps on all platforms without simultaneously negating some or all of their benefits.The binary accepts that risk exactly once, in
hiargs.rsline 242. -
Feature stubs via
#[path]module swapping. Instead of scattering#[cfg(feature = ...)]through call sites,extras/ripgrep/crates/core/index/mod.rsselects a whole module body:#[cfg(not(feature = "unstable-index"))] #[path = "disabled.rs"] mod imp; #[cfg(feature = "unstable-index")] #[path = "enabled.rs"] mod imp;
disabled.rsis nine lines ofanyhow::bail!stubs with identical signatures, somain.rscompiles unconditionally. -
Macros only where functions cannot go.
eprintln_locked!inextras/ripgrep/crates/core/messages.rslocks stdout before writing to stderr, an intentional abstraction violation with the reasoning inline:// This is a bit of an abstraction violation because we explicitly // lock stdout before printing to stderr. This avoids interleaving // lines within ripgrep because `search_parallel` uses `termcolor`, // which accesses the same stdout lock when writing lines.
The other macros (
message!,err_message!,rgtest!,eqnice!) are equally small and local; there is no proc-macro anywhere. -
let ... elsefor early-exit plumbing, used the day it made sense:let Ok(target_os) = std::env::var("CARGO_CFG_TARGET_OS") else { return };inextras/ripgrep/build.rs, andlet Some(zeropos) = buf.iter().position(|&b| b == 0) else { ... }when defending against POSIX's non-NUL-terminatedgethostnameinextras/ripgrep/crates/cli/src/hostname.rs. -
Conditional global allocator with a written cost-benefit analysis.
extras/ripgrep/crates/core/main.rsinstalls jemalloc only for 64-bit musl builds, after a 20-line comment explaining that musl's allocator is slow for ripgrep while glibc's is fine and jemalloc bloats compile times, a model of documenting a non-obviouscfg. -
Byte-first text handling.
bstr::ByteSliceis imported across the tree (e.g.extras/ripgrep/crates/searcher/src/testutil.rs,extras/ripgrep/tests/util.rs); searching operates on&[u8]with an amortized rolling buffer (fn rollinextras/ripgrep/crates/searcher/src/line_buffer.rs), and UTF-8 is a printer-level concern, not a search-level one. -
Iterator pipelines at the orchestration layer.
extras/ripgrep/crates/core/main.rscomposes the walk asargs.walk_builder()?.build().filter_map(|result| haystack_builder.build_from_result(result))before optional sorting, keeping the single-threaded path lazy end to end.
Documentation is enforced, generated, and layered:
- Enforced:
#![deny(missing_docs)]in all eight published library crates (section 5), plus the CIdocsjob compiling rustdoc for private items with warnings denied. - Module-level
//!docs open every significant module;extras/ripgrep/crates/core/flags/mod.rsbegins with a full paragraph explaining that the module owns flags, completions,--help, and the man page. Evenmain.rshas one (/*! The main entry point into ripgrep. */). - Generated from one source of truth: help text, the roff man page
(
extras/ripgrep/crates/core/flags/doc/template.rg.1, filled byTEMPLATE.replace("!!VERSION!!", ...)inextras/ripgrep/crates/core/flags/doc/man.rs), and four shell completion scripts all derive from theFlagimplementations, exposed to users asrg --generate manandrg --generate complete-{bash,zsh,fish,powershell}(seeGenerateModeinextras/ripgrep/crates/core/flags/lowargs.rs). - User-facing books live in the repo as flat Markdown:
extras/ripgrep/GUIDE.md(a full user guide including a documented sample config file) andextras/ripgrep/FAQ.md.extras/ripgrep/scripts/copy-examplesextracts code blocks from documentation so examples stay compilable. - Per-crate
README.mdplusLICENSE-MITandUNLICENSEin every crate directory;extras/ripgrep/crates/core/README.mddoubles as a short architecture note for the binary. - Issue intake is engineered:
extras/ripgrep/.github/ISSUE_TEMPLATE/bug_report.ymlis a structured form that lists the three most common non-bugs with issue references and requires a checkbox (I have a different issue.) before filing;config.ymlroutes questions to GitHub Discussions;feature_request.mdasks requesters to draft the ideal man-page text for their feature.extras/ripgrep/CONTRIBUTING.mdis a short pointer to the project's contribution policy document at the repository root.
Versioning and cadence are managed by a committed runbook,
extras/ripgrep/RELEASE-CHECKLIST.md, which encodes hard-won ordering: run
cargo update and cargo outdated first; release constituent crates in
dependency order (globset, ignore, cli, matcher, regex, pcre2,
searcher, printer, grep, then core); bump minimal versions in
dependents; push master and wait for CI to go green before pushing the
tag, with the reason recorded:
Once CI for `master` finishes successfully, push the version tag. (Trying to
do this in one step seems to result in GitHub Actions not seeing the tag
push and thus not running the release workflow.)
Changelog discipline is visible at the top of
extras/ripgrep/CHANGELOG.md: a standing TBD section
(Unreleased changes. Release notes have not yet been written.) followed by
dated releases whose entries are categorized (Platform support,
Performance improvements, Feature enhancements, bug fixes) and each
prefixed with a typed, linked reference such as
[PERF #3293](https://github.com/BurntSushi/ripgrep/issues/3293).
Distribution artifacts, all produced by
extras/ripgrep/.github/workflows/release.yml: 14 target archives
containing the stripped binary, licenses, CHANGELOG/FAQ/GUIDE, a
generated man page, and generated completions for four shells; a .sha256
sum per archive; a signed build-provenance attestation per archive; and a
Debian package built by cargo-deb from [package.metadata.deb]. The
Homebrew formula for the prebuilt binary lives in-repo at
extras/ripgrep/pkg/brew/ripgrep-bin.rb, reachable through the
HomebrewFormula symlink that Homebrew taps expect, and updated each
release by ci/sha256-releases. Version metadata is embedded at build time:
extras/ripgrep/build.rs exports the short git hash as
RIPGREP_BUILD_GIT_HASH, consumed via option_env! in
extras/ripgrep/crates/core/flags/doc/version.rs, and links
extras/ripgrep/pkg/windows/Manifest.xml into MSVC builds to enable
long-path awareness.
quinjet already exceeds ripgrep on lint tooling (clippy wall, cargo-deny, taplo, typos, miri, mutants, coverage floor), so the transferable value is in test architecture, CLI surface integrity, and release engineering:
- Collapse integration tests into one binary with a real-process harness.
Set
autotests = falseand an explicit[[test]]inCargo.tomlas inextras/ripgrep/Cargo.toml, then port theDir/TestCommandharness fromextras/ripgrep/tests/util.rs: per-test scratch directories from anAtomicUsize, commands running the compiledquinjetbinary with cwd set inside a throwaway git repository. Every CLI subcommand gets tested as a user would run it. - Add an
rgtest!-style macro that runs each end-to-end test under every relevant configuration (extras/ripgrep/tests/macros.rs). For quinjet the axes are natural: with and without a config file, and against repositories in different states. - Start
tests/regression.rsnow, one test per fixed issue, named after the issue number, followingextras/ripgrep/tests/regression.rs. It is the cheapest possible insurance against reintroducing bugs. - Adopt the exit-code and broken-pipe discipline of
extras/ripgrep/crates/core/main.rs:fn main() -> ExitCode, walk theanyhowchain forErrorKind::BrokenPipeand exit 0, reserve distinct codes for "nothing to do" versus "error", and track non-fatal errors in astatic AtomicBoolconsulted at exit (extras/ripgrep/crates/core/messages.rs). - Copy the
eprintln_locked!idea for any code path where the TUI or CLI writes to stdout and stderr concurrently: lock stdout before writing stderr so lines never interleave on a tty. - Write inventory tests over the command surface, modeled on
available_shortsinextras/ripgrep/crates/core/flags/defs.rs: assert every operation is reachable as both a subcommand and a keybinding, and print unassigned keys with-- --nocapturein CI. - Generate man pages and completions from the binary itself and verify
them. With clap, wire
clap_mangenandclap_completebehind aquinjet generate man|complete-<shell>subcommand mirroring ripgrep's--generatemodes, ship the outputs in release archives, and add a CI step in the spirit ofextras/ripgrep/ci/test-completethat diffs--helpflags against the completion output. - Harden CI structure: top-level
permissions: contents: read, a nightlyschedule:cron,fail-fast: false, and a matrix with apinnedMSRV entry plusbetaandnightlyrows, exactly as inextras/ripgrep/.github/workflows/ci.yml. Pin any release-critical third-party action by full commit SHA with a version comment, as ripgrep pinsactions/attest-build-provenance. - Make rustdoc a gate even for a binary crate: a CI job running
cargo doc --no-deps --document-private-itemswithRUSTDOCFLAGS: -D warnings, per thedocsjob inextras/ripgrep/.github/workflows/ci.yml. - Split profiles: keep
[profile.release] debug = 1for field-debuggable builds and add[profile.release-lto]withlto = "fat",codegen-units = 1,panic = "abort",strip = "symbols"used only by the release workflow, perextras/ripgrep/Cargo.toml. - Build a tag-triggered release workflow that verifies the tag against
Cargo.tomlbefore building, creates a draft release withgh release create --draft --verify-tag, attaches.sha256sums, and signs artifacts withactions/attest-build-provenance, followingextras/ripgrep/.github/workflows/release.yml. Addextras/ripgrep/.cargo/config.toml-stylecrt-staticrustflags if shipping musl or Windows binaries. - Add a
fuzz/package (excluded from the workspace,publish = false) withcargo-fuzztargets for every parser quinjet owns (git porcelain output, config files), asserting round-trip properties inside the target asextras/ripgrep/fuzz/fuzz_targets/fuzz_glob.rsdoes, and a CI job that at minimumcargo checks the fuzz package. - Embed the short git hash via a
build.rsrustc-envand surface it in--versionthroughoption_env!, perextras/ripgrep/build.rsandextras/ripgrep/crates/core/flags/doc/version.rs. - Commit a
RELEASE-CHECKLIST.mdand keep a standingTBDchangelog section with typed, issue-linked entries, perextras/ripgrep/RELEASE-CHECKLIST.mdandextras/ripgrep/CHANGELOG.md. - Use structured issue forms with a triage checkbox and links to known
non-bugs (
extras/ripgrep/.github/ISSUE_TEMPLATE/bug_report.yml), and route questions to Discussions viaconfig.yml. - When quinjet grows an experimental subsystem, gate it the ripgrep way:
an
unstable-*feature flag plus the#[path]module-swap stub pattern fromextras/ripgrep/crates/core/index/mod.rs, so mainline code never branches on the feature at call sites.
Alacritty is a cross-platform, GPU-accelerated terminal emulator. The binary crate describes
itself in extras/alacritty/alacritty/Cargo.toml as "A fast, cross-platform, OpenGL terminal
emulator". It is one of the most widely deployed end-user Rust desktop applications: it ships on
Linux (X11 and Wayland), macOS, Windows, FreeBSD, and OpenBSD, renders with OpenGL, and is a
default terminal for a large population of developers. For industry, it is a reference for three
things at once: a long-lived Rust GUI application, a reusable terminal-emulation library
(alacritty_terminal is published on crates.io for other emulators to build on), and a
disciplined multi-platform release pipeline that produces DMGs, MSIs, man pages, terminfo, and
shell completions from one repository.
Measurable scale from the clone:
| Metric | Value | How measured |
|---|---|---|
| Workspace members | 4 |
[workspace] members in extras/alacritty/Cargo.toml
|
| Rust source files | 88 | find . -name "*.rs" |
Rust lines (all .rs) |
33,710 |
cat piped to wc -l
|
Lines in alacritty (binary) |
20,984 | per-crate wc -l
|
Lines in alacritty_terminal
|
11,877 | per-crate wc -l
|
Lines in alacritty_config_derive
|
748 | per-crate wc -l
|
Lines in alacritty_config
|
101 | per-crate wc -l
|
Cargo.lock lines |
2,831 | wc -l |
| Ref-test fixtures | 45 | ls alacritty_terminal/tests/ref | wc -l |
| User changelog | 1,457 lines | wc -l CHANGELOG.md |
The striking ratio: a full terminal emulator in under 34k lines of Rust, with the emulation core at under 12k lines. The project optimizes for a small, heavily reviewed core rather than breadth.
extras/alacritty/
|-- Cargo.toml workspace root, profiles, patch table
|-- Cargo.lock committed (binary project)
|-- rustfmt.toml nightly rustfmt configuration
|-- .editorconfig whitespace rules for all file types
|-- Makefile macOS app/dmg packaging only
|-- CHANGELOG.md user-facing keep-a-changelog
|-- CONTRIBUTING.md testing, style, and release process
|-- INSTALL.md 380 lines of per-OS build instructions
|-- docs/features.md prose feature tour (vi mode, hints, search)
|-- scripts/ color and flamegraph helper shell scripts
|-- extra/ everything shipped that is not the binary
| |-- man/ 5 scdoc man page sources
| |-- completions/ checked-in bash/fish/zsh completions
| |-- linux/ .desktop entry, appdata.xml
| |-- osx/Alacritty.app app bundle template
| |-- alacritty.info terminfo source
| `-- logo/, promo/ artwork
|-- .github/workflows/ GitHub Actions (Windows, macOS) + release
|-- .builds/ sourcehut CI (Linux, FreeBSD)
|-- alacritty/ the binary: UI, renderer, config, CLI
| `-- src/{cli,config,display,input,renderer,migrate,macos,...}
|-- alacritty_terminal/ reusable emulation library: grid, tty, vte
| |-- src/{grid,term,tty,event_loop.rs,index.rs,selection.rs,...}
| |-- tests/ref.rs golden "ref test" harness
| `-- tests/ref/<name>/ 45 recorded terminal sessions
|-- alacritty_config/ tiny trait crate (SerdeReplace)
`-- alacritty_config_derive/ proc-macro crate for config deserialization
The split works because each crate has one reason to exist. alacritty_terminal contains zero
windowing or rendering code, so it is testable headlessly and reusable (its manifest at
extras/alacritty/alacritty_terminal/Cargo.toml says "Library for writing terminal emulators").
The proc-macro crate is separated because proc macros must be their own crate, and
alacritty_config exists only so the derive crate and the binary can share the SerdeReplace
trait without a dependency cycle. Distribution assets live under extras/alacritty/extra/, away
from source, and the Makefile only handles the one platform (macOS bundling) that cargo cannot.
The root extras/alacritty/Cargo.toml is only 24 lines and is worth reading in full:
[workspace]
members = [
"alacritty",
"alacritty_terminal",
"alacritty_config",
"alacritty_config_derive",
]
resolver = "2"
[workspace.package]
edition = "2024"
rust-version = "1.85.0"
[profile.release]
lto = "thin"
debug = 1
incremental = false
[workspace.dependencies]
toml = "0.9.11"
toml_edit = "0.24.0"
# TODO: Validation of fix for #6978. Remove before next release and use released `x11-clipboard`.
[patch.crates-io]
x11-clipboard = { git = "https://github.com/quininer/x11-clipboard.git", rev = "19ab2163cf0bd0db607e827a5214571990307866" }Practices to note:
-
workspace.packagecarries exactly the two fields every member must agree on:editionandrust-version. Members inherit withedition.workspace = trueandrust-version.workspace = true(seeextras/alacritty/alacritty/Cargo.toml). Versions, authors, and licenses stay per-crate because they genuinely differ: the binary is Apache-2.0 whilealacritty_configisMIT OR Apache-2.0. -
workspace.dependenciesis used surgically, not exhaustively: onlytomlandtoml_editare hoisted, because three crates must deserialize configuration with the exact same TOML version. Everything else is declared where it is used. - The release profile trades a little speed for debuggability:
lto = "thin"plusdebug = 1keeps line tables in release builds so user crash reports have symbols. -
[patch.crates-io]pins a dependency to an exact git revision to validate an upstream fix, with a TODO stating the removal condition ("Remove before next release"). Temporary patches carry their own expiry note. - Dependency tables are split by target.
extras/alacritty/alacritty/Cargo.tomlhas[target.'cfg(not(windows))'.dependencies],[target.'cfg(target_os = "macos")'.dependencies], and[target.'cfg(windows)'.dependencies], soobjc2never appears in a Linux build plan andwindows-sysnever appears on Unix. - Big-surface dependencies get minimal feature lists.
windows-sysenables only fourWin32_*feature gates;objc2-app-kitsetsdefault-features = falseand lists five classes;ahashusesfeatures = ["no-rng"];glutinsetsdefault-features = falsewith explicit["egl", "wgl"]. - Feature design is user-facing:
default = ["wayland", "x11"], and each feature fans out into the features of five dependencies, e.g.:
wayland = [
"copypasta/wayland",
"glutin/wayland",
"winit/wayland",
"winit/wayland-dlopen",
"winit/wayland-csd-adwaita-crossfont",
]- The library uses the
dep:syntax to keep optional deps out of the implicit feature list, inextras/alacritty/alacritty_terminal/Cargo.toml:
[features]
default = ["serde"]
serde = ["dep:serde", "bitflags/serde", "vte/serde"]- Internal path dependencies always carry a version (
version = "0.26.1-dev"next topath = "../alacritty_terminal") so the crates remain publishable to crates.io. - Development versions use a
-devsuffix (version = "0.18.0-dev"), which the release process inextras/alacritty/CONTRIBUTING.mdstrips on the release branch.
There is no [lints] table anywhere; lint policy lives in crate roots (section 5).
extras/alacritty/rustfmt.toml runs on nightly (cargo +nightly fmt in
extras/alacritty/.builds/linux.yml) and enables 15 unstable options:
format_code_in_doc_comments = true
match_block_trailing_comma = true
condense_wildcard_suffixes = true
use_field_init_shorthand = true
normalize_doc_attributes = true
overflow_delimited_expr = true
imports_granularity = "Module"
use_small_heuristics = "Max"
normalize_comments = true
reorder_impl_items = true
use_try_shorthand = true
newline_style = "Unix"
format_strings = true
wrap_comments = true
comment_width = 100Setting by setting: format_code_in_doc_comments formats Rust inside doc examples;
match_block_trailing_comma forces a comma after block match arms (visible throughout, e.g. the
grid_clamp match in extras/alacritty/alacritty_terminal/src/index.rs);
condense_wildcard_suffixes turns (a, _, _) into (a, ..); use_field_init_shorthand
rewrites Foo { x: x } to Foo { x }; normalize_doc_attributes converts #[doc = "..."] to
///; overflow_delimited_expr lets a trailing collection literal overflow instead of
indenting, which is why the Registry::new(...).write_bindings(...) call in
extras/alacritty/alacritty/build.rs reads naturally; imports_granularity = "Module" merges
imports per module, giving the consistent use std::sync::{Arc, Mutex, OnceLock}; style;
use_small_heuristics = "Max" packs anything that fits into the width onto one line (the
one-line struct literal in FairMutex::new in
extras/alacritty/alacritty_terminal/src/sync.rs is a direct product);
normalize_comments converts /* */ to //; reorder_impl_items groups consts, types, then
fns inside impls; use_try_shorthand replaces r#try!/try! with ?;
newline_style = "Unix" forces LF even on Windows checkouts; format_strings breaks long
string literals; wrap_comments plus comment_width = 100 rewraps prose comments at 100
columns while code stays at the default width.
Non-Rust files are governed by extras/alacritty/.editorconfig: UTF-8, LF, trimmed trailing
whitespace and final newline for every file, 4-space indent for glsl, rs, and toml, tabs
for Makefile, and tabs with tab_width = 4 for the scdoc man sources:
[*.{glsl,rs,toml}]
indent_style = space
indent_size = 4
[Makefile]
indent_style = tab
[*.scd]
indent_style = tab
tab_width = 4Beyond machine formatting, extras/alacritty/CONTRIBUTING.md adds a human rule: "All comments
should be fully punctuated with a trailing period. This applies both to regular and
documentation comments."
There is no clippy.toml and no [lints] table. The entire lint wall is three attribute lines
repeated at every crate root, e.g. extras/alacritty/alacritty/src/main.rs:
#![warn(rust_2018_idioms, future_incompatible)]
#![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use)]
#![cfg_attr(clippy, deny(warnings))]The same lines appear in extras/alacritty/alacritty_terminal/src/lib.rs and
extras/alacritty/alacritty_config_derive/src/lib.rs. The philosophy:
-
clippy::allis denied, not warned, so correctness and style lints are hard CI failures. - Exactly two opt-in lints are added by name:
clippy::if_not_else(readability of negated conditionals) andclippy::enum_glob_use(nouse Enum::*). No pedantic or nursery groups: the project prefers a small, permanent set over a large set with many localallows. -
#![cfg_attr(clippy, deny(warnings))]denies all rustc warnings only when theclippycfg is set, so ordinarycargo buildnever fails on a new rustc warning but lint CI does. The sourcehut jobs get the same effect for feature builds viaRUSTFLAGS="-D warnings" cargo test --no-default-features --features=wayland(extras/alacritty/.builds/linux.yml). - Allows are local, justified, and rare. Generated code gets a blanket exemption in
extras/alacritty/alacritty/src/main.rs:
mod gl {
#![allow(clippy::all, unsafe_op_in_unsafe_fn)]
include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs"));
}and a single-expression allow appears as #[allow(clippy::iter_skip_zero)] in
extras/alacritty/alacritty/src/string.rs, where skip(0) is intentional to unify types.
- CI runs
cargo clippy --all-targetson every platform (extras/alacritty/.github/workflows/ci.ymland both.buildsmanifests), so tests and examples are linted too. -
extras/alacritty/alacritty/src/main.rsalso carries a build-time configuration lint:
#[cfg(not(any(feature = "x11", feature = "wayland", target_os = "macos", windows)))]
compile_error!(r#"at least one of the "x11"/"wayland" features must be enabled"#);CI is split across two systems by operating system, which is the most unusual choice in the repository.
extras/alacritty/.github/workflows/ci.yml covers Windows and macOS, triggered by
on: [push, pull_request]:
jobs:
build:
strategy:
matrix:
os: [windows-latest, macos-latest]Its steps: cargo test on stable; cargo test -p alacritty_terminal --no-default-features (the
library must build without serde); an "Oldstable" step that extracts the MSRV from the manifest
so there is one source of truth:
- name: Oldstable
run: |
rustup default $(cat Cargo.toml | grep "rust-version" | sed 's/.*"\(.*\)".*/\1/')
cargo testand cargo clippy --all-targets. A second job, check-macos-x86_64, cross-checks the Intel
macOS target from an ARM runner (rustup target add x86_64-apple-darwin then
cargo build --target=x86_64-apple-darwin).
Linux and FreeBSD run on sourcehut builds, configured in extras/alacritty/.builds/linux.yml
(Arch image) and extras/alacritty/.builds/freebsd.yml. The Linux manifest adds jobs GitHub
does not run: nightly rustfmt (rustup toolchain install nightly -c rustfmt then
cargo +nightly fmt -- --check), man page compilation as a docs gate
(cat extra/man/alacritty.1.scd | scdoc > /dev/null for all five pages), the same
grep-the-manifest MSRV job, and a per-feature matrix run as separate tasks:
- feature-wayland: |
cd alacritty/alacritty
RUSTFLAGS="-D warnings" cargo test --no-default-features --features=wayland
- feature-x11: |
cd alacritty/alacritty
RUSTFLAGS="-D warnings" cargo test --no-default-features --features=x11Hardening and hygiene observations: the only third-party action used anywhere is
actions/checkout@v4, pinned by major tag; there is no dependency caching at all (build times
are acceptable because the tree is small, and no cache means no cache-poisoning surface); the
release workflow's token exposure is limited to secrets.GITHUB_TOKEN; there is no merge queue
or required-check configuration visible in-repo. Release automation
(extras/alacritty/.github/workflows/release.yml) triggers on tag pushes matching
tags: ["v[0-9]+.[0-9]+.[0-9]+*"], and every packaging job re-runs cargo test --release
before building artifacts, so the exact optimized binaries being shipped are the ones tested.
Three layers, each in the conventional Rust location:
-
Inline unit tests. Nineteen files contain a
mod testsblock, found viagrep -rn "mod tests": parser-adjacent logic (extras/alacritty/alacritty_terminal/src/term/search.rs,.../selection.rs,.../vi_mode.rs,.../grid/storage.rs), and UI-side pure logic (extras/alacritty/alacritty/src/config/bindings.rs,.../display/damage.rs,.../string.rs,.../migrate/mod.rs). The grid gets a dedicated sibling file wired asmod tests;inextras/alacritty/alacritty_terminal/src/grid/mod.rs; that file even implementsGridCell for usize(extras/alacritty/alacritty_terminal/src/grid/tests.rs) so grid algorithms are tested on plain integers instead of full cells. -
Golden "ref tests", the project's signature harness. A real Alacritty run with the hidden
--ref-testflag (declared inextras/alacritty/alacritty/src/cli.rswith#[clap(long, conflicts_with("daemon"))]) records the raw PTY byte stream and final state to disk. Each fixture directory, e.g.extras/alacritty/alacritty_terminal/tests/ref/vim_large_window_scroll/, holds four files:alacritty.recording,grid.json,size.json,config.json. The harnessextras/alacritty/alacritty_terminal/tests/ref.rsreplays the bytes through a headlessTermand diffs the resulting grid cell by cell. Test registration is a declarative macro:macro_rules! ref_tests { ($($name:ident)*) => { $( #[test] fn $name() { let test_dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/ref")); let test_path = test_dir.join(stringify!($name)); ref_test(&test_path); } )* }; }
45 fixtures cover vttest sequences, tmux, vim, fish, zsh completion, hyperlinks, and named regressions like
issue_855. Headless replay is possible because the UI is abstracted behind a no-op listener:struct Mock; impl EventListener for Mock { fn send_event(&self, _e: Event) {} }.extras/alacritty/CONTRIBUTING.mdrequires that a bug-fix ref test fail against the unpatched binary before it is accepted. -
Integration tests for the proc macro.
extras/alacritty/alacritty_config_derive/tests/config.rs(245 lines) exercises every derive attribute (#[config(alias)],deprecated,removed,skip,flatten,#[doc(hidden)]) and asserts on the log records the derive emits for bad input, using a captured logger.
The CLI surface is tested end to end in an unusual way: the checked-in shell completions are
asserted byte-for-byte against what clap_complete generates, in
extras/alacritty/alacritty/src/cli.rs:
let mut generated = Vec::new();
clap_complete::generate(*shell, &mut clap, "alacritty", &mut generated);
...
assert_eq!(generated, completion);so any CLI flag change that forgets to regenerate extras/alacritty/extra/completions/ fails
cargo test. There is no fuzzing, property testing, or in-repo benchmark suite; throughput is
benchmarked with the external vtebench tool and latency with typometer, both mandated by the
Performance section of extras/alacritty/CONTRIBUTING.md.
Neither thiserror nor anyhow appears anywhere in the workspace (verified by grep across all
manifests). Errors are hand-written enums with manual Display and source, e.g.
extras/alacritty/alacritty/src/config/mod.rs:
/// Errors occurring during config loading.
#[derive(Debug)]
pub enum Error {
/// Couldn't read $HOME environment variable.
ReadingEnvHome(env::VarError),
/// io error reading file.
Io(io::Error),
/// Invalid toml.
Toml(TomlError),
...
}with a module-local alias pub type Result<T> = std::result::Result<T, Error>;. The dependency
cost of an error-derive crate is judged not worth five variants.
Result discipline and exit behavior: fn main() -> Result<(), Box<dyn Error>>
(extras/alacritty/alacritty/src/main.rs) propagates startup errors; non-interactive
subcommands print to stderr and exit nonzero explicitly, as in
extras/alacritty/alacritty/src/migrate/mod.rs:
None => {
eprintln!("No configuration file found");
std::process::exit(1);
},The migrate subcommand also runs a forced dry-run pass before any wet run touches the user's
file, and writes through tempfile::NamedTempFile. Panic policy: panics are reserved for
programmer errors (expect("thread spawn works") in
extras/alacritty/alacritty_terminal/src/thread.rs), and on Windows, where there is no console,
a custom hook mirrors the panic into a native dialog
(extras/alacritty/alacritty/src/panic.rs, MessageBoxW with "Press Ctrl-C to Copy").
Resource cleanup is typed: struct TemporaryFiles in extras/alacritty/alacritty/src/main.rs
removes the IPC socket and log file in its Drop impl, so every exit path cleans up.
API design: newtypes over raw indices (Line, Column in
extras/alacritty/alacritty_terminal/src/index.rs, with
#[must_use = "this returns the result of the operation, without modifying the original"] on
the pure arithmetic methods); visibility is deliberate, e.g. Shell in
extras/alacritty/alacritty_terminal/src/tty/mod.rs exposes pub(crate) fields behind a public
constructor; options structs (tty::Options, term::Config) with Default play the role of
builders; and the library re-exports its parser (pub use vte; in
extras/alacritty/alacritty_terminal/src/lib.rs) so downstreams never fight version skew on
shared types.
-
Fairness-augmented mutex.
extras/alacritty/alacritty_terminal/src/sync.rscomposes twoparking_lot::Mutexes into aFairMutex<T>with alease()method, so the render thread can reserve the terminal lock while the PTY reader thread is hammering it. The comment inlock()even documents a subtle temporary-lifetime hazard: "Must bind to a temporary or the lock will be freed before going into data.lock()". -
Newtype index arithmetic with generic defaults.
extras/alacritty/alacritty_terminal/src/index.rsdefinespub struct Point<L = Line, C = Column>, so the same type serves grid-space and viewport-space coordinates, and implementsAdd,Sub,AddAssign,Ord, and clamping (grid_clampwith aBoundaryenum) so off-by-one line math is centralized and#[must_use]guarded. -
A ring buffer with measured
unsafe.Storage<T>inextras/alacritty/alacritty_terminal/src/grid/storage.rsscrolls by rotating azerooffset instead of moving memory, reimplementsIndex/IndexMutaround the wraparound, and deliberately provides noDereftoVec("Anything fromVecthat should be exposed must be done so manually"). Its customswapcopies four qwords throughMaybeUninit<usize>pointers, justified by counted instructions ("The default implementation from swap generates 8 movups and 4 movaps instructions") and guarded bydebug_assert_eq!(mem::size_of::<Row<T>>(), mem::size_of::<usize>() * 4). -
Trait-decoupled core.
Term<U: EventListener>sends UI-relevant events through the trait inextras/alacritty/alacritty_terminal/src/event.rs(window title, clipboard, bell), including callback-carrying variants likeClipboardLoad(ClipboardType, Arc<dyn Fn(&str) -> String + Sync + Send + 'static>). This one boundary is what makes headless ref tests and the library's reuse by other emulators possible. -
Cow<'static, [u8]>on the hot write path. The PTY event loop (extras/alacritty/alacritty_terminal/src/event_loop.rs) queues writes asMsg::Input(Cow<'static, [u8]>)and storeswrite_list: VecDeque<Cow<'static, [u8]>>, so static escape sequences are enqueued without allocation while dynamic input still fits the same channel. -
Platform layering via
cfgre-export.extras/alacritty/alacritty_terminal/src/tty/mod.rspresents one API from two implementations:#[cfg(not(windows))] mod unix; #[cfg(not(windows))] pub use self::unix::*; #[cfg(windows)] pub mod windows;
The same discipline extends to docs:
extras/alacritty/alacritty/src/cli.rsdeclaresconfig_filethree times under differentcfgs purely so--helpshows the correct default path per OS. -
Build-script codegen plus embedded version.
extras/alacritty/alacritty/build.rsgenerates OpenGL bindings withgl_generatorintoOUT_DIR, and computesprintln!("cargo:rustc-env=VERSION={version}")including the short git hash; the CLI then uses#[clap(author, about, version = env!("VERSION"))](extras/alacritty/alacritty/src/cli.rs), soalacritty --versionidentifies dev builds by commit. -
A purpose-built derive macro for resilient config.
extras/alacritty/alacritty_config_derive/src/lib.rsships#[proc_macro_derive(ConfigDeserialize, attributes(config))]andSerdeReplace. The derive makes every field individually recoverable: a bad value logs a warning and falls back to that field's default rather than rejecting the file, and attributes encode config lifecycle (#[config(deprecated = "use field2 instead")],#[config(removed = "it's gone")],#[config(alias = ...)]) as shown inextras/alacritty/alacritty_config_derive/tests/config.rs.SerdeReplacethen lets a CLI dotted path like-o window.opacity=0.5splice into the deserialized struct (extras/alacritty/alacritty_config/src/lib.rs). -
Lazy DFA regex over a ring buffer. Scrollback search (
extras/alacritty/alacritty_terminal/src/term/search.rs) drops down from theregexcrate toregex-automata's hybrid lazy DFA, holding four DFAs (forward and reverse, left and right anchored) to find both ends of matches while iterating the grid bidirectionally, with smart-case derived bysearch.chars().any(|c| c.is_uppercase())and cache bounds copied from the meta engine with a citation link in the comment. -
Small ergonomic infrastructure everywhere: named threads via a nine-line wrapper (
spawn_namedinextras/alacritty/alacritty_terminal/src/thread.rs, "Likethread::spawn, but with anameargument"); lazy statics throughOnceLockreadingALACRITTY_EXTRA_LOG_TARGETSinextras/alacritty/alacritty/src/logging.rs; anIteratorimplementation for width-aware string truncation (StrShortenerinextras/alacritty/alacritty/src/string.rs) driven by a smallTextActionstate enum; and single-threaded interior mutability chosen deliberately (OnceCell,RefCell,Rcinextras/alacritty/alacritty/src/config/ui_config.rs) where the UI thread owns the data, versusArc<FairMutex<...>>only where the PTY thread truly shares it.
- Module-level
//!docs open most files and state contracts, not just topics:extras/alacritty/alacritty/src/logging.rsbegins "The main executable is supposed to callinitialize()exactly once during startup." Doc comments use intra-doc links and reference definitions (see theStorageheader inextras/alacritty/alacritty_terminal/src/grid/storage.rs). -
extras/alacritty/CONTRIBUTING.mdis the process spine: how to add ref tests, which benchmarking tools to use, the API-guidelines pointer for style, the trailing-period comment rule, the rule that config changes must update the man pages, and a fully scripted release process (14 numbered steps for a feature release, 6 for a patch release). - User docs are split by audience:
extras/alacritty/README.mdfor the pitch,extras/alacritty/INSTALL.md(380 lines) for building on every OS,extras/alacritty/docs/features.mdfor feature discovery, and five scdoc man pages inextras/alacritty/extra/man/as the configuration reference, withalacritty.5.scdalone at 1,075 lines. Man pages are compiled in CI so they cannot rot (extras/alacritty/.builds/linux.yml). -
extras/alacritty/CHANGELOG.mdopens by legislating its own format: "The sections should follow the orderPackaging,Added,Changed,FixedandRemoved", and points to the separateextras/alacritty/alacritty_terminal/CHANGELOG.mdfor library consumers. - There is no ARCHITECTURE.md and no issue-template directory; the PR template
(
extras/alacritty/.github/pull_request_template.md) is a single checkbox line asserting the patch complies with the project's contribution-provenance policy.
Versioning follows a release-branch model documented step by step in
extras/alacritty/CONTRIBUTING.md: master only ever carries X.Y.0-dev versions; each major
release gets a vX.Y branch where -rcN tags, the final tag, and patch releases live; fixes
are cherry-picked from master into the branch; and the library crate is tagged separately as
alacritty_terminal_vX.Y.Z with suffixes kept in sync.
Tagging vX.Y.Z fires extras/alacritty/.github/workflows/release.yml:
- macOS: installs
scdoc, adds both Apple targets, runscargo test --releaseon x86_64, builds ARM, thenmake dmg-universal. The Makefile (extras/alacritty/Makefile) lipo-merges the two binaries, gzips the man pages, compiles terminfo withtic -xe alacritty,alacritty-direct, copies completions into the app bundle, and ad-hoc codesigns (codesign --force --deep --sign -). - Windows: uploads a portable
Alacritty-vX.Y.Z-portable.exeand builds an MSI with WiX 4 fromalacritty/windows/wix/alacritty.wxs. - Linux: uploads no binaries at all, only integration assets: gzipped man pages, the SVG logo,
three shell completions,
Alacritty.desktop, andalacritty.info. Distro packagers build the binary; the project ships the surrounding material.
Uploads go through extras/alacritty/.github/workflows/upload_asset.sh, a 100-line bash script
that finds or creates a draft release for the current tag via the GitHub API
(-d "{\"tag_name\":\"$tag\",\"draft\":true}"), so a human publishes the release after all
three OS jobs have attached their artifacts. Completions are not generated at release time; they
are checked in under extras/alacritty/extra/completions/ and enforced by the unit test in
extras/alacritty/alacritty/src/cli.rs (section 7), which keeps packaging simple and diffs
reviewable.
Practices worth adopting, with mechanisms:
-
Completion drift test. Add
clap_completeto[dev-dependencies], check generated completions intoextra/completions/, and add a#[test]that runsclap_complete::generate(shell, &mut Options::command(), "quinjet", &mut buf)andassert_eq!against the checked-in files, exactly asextras/alacritty/alacritty/src/cli.rsdoes. Everyclapchange then fails tests until completions are regenerated. -
Golden replay tests for the TUI. Mirror the ref-test harness (
extras/alacritty/alacritty_terminal/tests/ref.rs): a hidden--ref-test-style flag dumps the final ratatui buffer plus the inputs that produced it into a fixture directory undertests/ref/<name>/, and aref_tests! { ... }declarative macro expands one#[test]per fixture that replays and diffs cell by cell, printing only mismatched cells before panicking. -
Version with commit hash. In
build.rs, rungit rev-parse --short HEAD, emitcargo:rustc-env=VERSION={pkg_version} ({hash}), and use#[clap(version = env!("VERSION"))], copyingextras/alacritty/alacritty/build.rs. Dev-build bug reports become attributable. -
Debuggable release profile. Set
debug = 1alongside the existing optimizations in[profile.release]as inextras/alacritty/Cargo.toml, so user-reported backtraces from a Git TUI crash carry line numbers. -
MSRV from one source in CI. Replace any hardcoded toolchain in the MSRV job with the grep-the-manifest pattern from
extras/alacritty/.github/workflows/ci.yml(rustup default $(grep "rust-version" Cargo.toml | sed ...)thencargo test), so bumpingrust-versionis a one-line change. -
Feature and no-default-features CI legs. Add
cargo test --no-default-features(and one leg per meaningful feature withRUSTFLAGS="-D warnings") as inextras/alacritty/.builds/linux.yml, so optional-dependency breakage is caught. -
Docs compiled in CI. If quinjet ships man pages, write them as scdoc in
extra/man/and add a CI step that pipes each throughscdoc > /dev/null(extras/alacritty/.builds/linux.yml); a syntax error in docs then fails the build. -
Changelog with legislated section order. Start
CHANGELOG.mdwith the format rule itself, asextras/alacritty/CHANGELOG.mddoes ("sections should follow the orderPackaging,Added,Changed,FixedandRemoved"), and require entries for user-visible changes in CONTRIBUTING. -
Typed cleanup on exit. Wrap temp artifacts (sockets, log files, lock files) in a struct whose
Dropremoves them, likeTemporaryFilesinextras/alacritty/alacritty/src/main.rs, instead of scattering cleanup across exit paths. -
Dry-run before wet-run for destructive subcommands. Quinjet's history-rewriting operations can copy
extras/alacritty/alacritty/src/migrate/mod.rs: force a silent dry-run first, exit nonzero on any failure, and only then perform the real mutation, writing throughtempfile::NamedTempFile. -
Named threads. Add a
spawn_namedhelper identical toextras/alacritty/alacritty_terminal/src/thread.rsfor any background Git work, so thread names show up in panics and debuggers. -
compile_error!for invalid feature sets. If quinjet ever grows mutually optional backends, guard them at the crate root asextras/alacritty/alacritty/src/main.rsdoes. -
Release asset script with draft releases. For binary distribution, adopt the find-or-create-draft pattern of
extras/alacritty/.github/workflows/upload_asset.sh: jobs attach artifacts to a draft, and a human clicks publish, decoupling build success from release visibility.
Two practices quinjet already exceeds: Alacritty has no equivalent of quinjet's clippy restriction wall, cargo-deny, taplo, typos, coverage floor, miri, or mutants; and Alacritty performs no dependency caching or action SHA-pinning in CI. The traffic in lessons on those axes flows the other way.
bat is "a cat(1) clone with wings": a syntax-highlighting file printer with Git modification markers, automatic paging, and theming. The manifest at extras/bat/Cargo.toml describes it in one line:
description = "A cat(1) clone with wings."
categories = ["command-line-utilities"]
license = "MIT OR Apache-2.0"Industry uses it for two reasons. First, as a daily-driver CLI it replaces cat and less for
code reading, and it ships in every major package manager (the CI builds Debian packages and
publishes to Winget directly, see section 6). Second, it is also a library: tools such as delta
depend on the bat crate for pretty-printing, which is why the crate carries an unusually
disciplined feature-flag surface separating "bat the application" from "bat the library"
(section 3).
Measured scale from the clone at extras/bat:
- Single crate, no workspace. One package
bat, version 0.26.1, edition 2021, MSRV 1.88. - 67 Rust source files, 18,173 lines of Rust total: 12,094 in extras/bat/src, roughly 5,452 in extras/bat/tests, 490 in the build script under extras/bat/build, the rest in extras/bat/examples and extras/bat/assets/theme_preview.rs.
- 93 git submodules (extras/bat/.gitmodules), almost all of them Sublime Text syntax and theme repositories vendored under extras/bat/assets.
- 273
#[test]functions in extras/bat/tests/integration_tests.rs alone.
The striking property of the codebase is leverage: a small core (about 12k lines) drives a very large data surface (syntaxes, themes, mappings) through build-time code generation and binary asset embedding.
Top level of extras/bat:
bat/
|-- assets/ syntax/theme submodules, completions templates, man page template,
| pre-built binary assets (syntaxes.bin, themes.bin, acknowledgements.bin)
|-- build/ the build script, split into modules (main.rs, application.rs,
| syntax_mapping.rs, util.rs)
|-- diagnostics/ info.sh, the script behind `bat --diagnostic` bug reports
|-- doc/ assets.md, alternatives.md, release-checklist.md, long-help.txt,
| short-help.txt, translated READMEs (ja, ko, ru, zh)
|-- examples/ 7 library-usage examples (cat.rs, advanced.rs, yaml.rs, ...)
|-- src/ the library crate root
| |-- assets/ asset loading, lazy theme set, serialized syntax set
| |-- bin/bat/ the application binary (app.rs, clap_app.rs, config.rs, main.rs, ...)
| `-- syntax_mapping/ builtin.rs plus builtins/ TOML rule files per platform
|-- tests/ integration tests, snapshot tests, syntax regression corpus, benchmarks
|-- .cargo/ config.toml (crt-static for Windows), audit.toml (RUSTSEC ignores)
|-- .github/ two workflows, dependabot.yml, four issue templates
|-- Cargo.toml, Cargo.lock, rustfmt.toml, flake.nix, .envrc
`-- CHANGELOG.md, CONTRIBUTING.md, SECURITY.md, NOTICE, LICENSE-MIT, LICENSE-APACHE
Why this split works:
- Library and binary live in one crate but are physically separated: extras/bat/src/lib.rs is the library, and the application lives under extras/bat/src/bin/bat/ as eight modules (app.rs, clap_app.rs, config.rs, directories.rs, input.rs, completions.rs, assets.rs, main.rs). CLI parsing, config-file merging, and environment handling never leak into the library.
- The build script is a directory, not a single file. extras/bat/build/main.rs is 17 lines and
delegates to
syntax_mapping.rs(368 lines of code generation) andapplication.rs(man page and completion rendering), keeping each build concern reviewable. - Data lives next to the code that owns it: syntax mapping rules are TOML files under extras/bat/src/syntax_mapping/builtins/{common,unix-family,bsd-family,linux,macos,windows}, with a README.md in that directory explaining the format. 27 TOML files exist in common/ alone.
- Tests own their fixtures: extras/bat/tests/examples is a small fake filesystem (config files,
control_characters.txt, a git directory), extras/bat/tests/mocked-pagers holds fake
moreandmostexecutables, and extras/bat/tests/snapshots holds committed expected outputs.
extras/bat/Cargo.toml is a single-package manifest, so there is no workspace.package
inheritance, but it demonstrates several practices worth copying.
MSRV is explicit, with a policy comment right in the manifest:
edition = '2021'
# You are free to bump MSRV as soon as a reason for bumping emerges.
rust-version = "1.88"CI reads that value back out with cargo metadata so the MSRV is stated in exactly one place
(section 6).
Feature flags encode the library/application split:
[features]
default = ["application", "git"]
# Feature required for bat the application. Should be disabled when depending on
# bat as a library.
application = [
"bugreport",
"build-assets",
"minimal-application",
]
# Mainly for developers that want to iterate quickly
minimal-application = [
"clap",
"etcetera",
"paging",
"regex-onig",
"wild",
]
git = ["gix"] # Support indicating git modifications
paging = [ "shell-words", "grep-cli", "minus"] # Support applying a pager on the output
lessopen = ["execute"] # Support $LESSOPEN preprocessorNotice that nearly every heavyweight dependency (clap, gix, minus, grep-cli, wild, bugreport,
regex, walkdir) is optional = true and pulled in only via a feature. A library consumer that
disables default features gets a much smaller dependency tree, and the manifest tells them what
they must choose: regex-onig or regex-fancy, the two syntect regex engines.
Dependency hygiene details:
- Transitive default features are trimmed aggressively:
gixis declared withdefault-features = false, features = ["sha1", "blob-diff"],syntectwithdefault-features = false, features = ["parsing"],clircleandpath_abswithdefault-features = false. - Platform-conditional dependencies are used instead of cfg-gated code with unused deps:
[target.'cfg(target_os = "macos")'.dependencies] plist = "1.9.0"and[target.'cfg(unix)'.dev-dependencies] nix = { ... features = ["term"] }. - Packaging excludes the huge submodule trees:
exclude = ["assets/syntaxes/*", "assets/themes/*"], so the crates.io tarball ships only the pre-built .bin assets. - The build script has its own substantial dependency set (
prettyplease,proc-macro2,quote,syn,serde_with,indexmap,toml) under[build-dependencies]because the build script does real code generation (section 9).
The release profile is tuned for a distributed binary:
[profile.release]
lto = true
strip = true
codegen-units = 1There is no [lints] table and no clippy.toml; lint policy lives in CI flags and crate
attributes (section 5). Cargo-level config that does exist is in extras/bat/.cargo/config.toml:
# On Windows MSVC, statically link the C runtime so that the resulting EXE does
# not depend on the vcruntime DLL.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]with the same for i686 and aarch64 MSVC, and extras/bat/.cargo/audit.toml pins accepted advisory
exceptions: ignore = ["RUSTSEC-2024-0320", "RUSTSEC-2024-0421"].
extras/bat/rustfmt.toml is a single comment line:
# Defaults are usedThis is a deliberate statement, not an omission: the file exists so that editors and CI agree
that stock rustfmt is the standard, and so nobody adds unstable options later without a visible
diff to this file. CI enforces it with cargo fmt -- --check in the lint job of
extras/bat/.github/workflows/CICD.yml.
There is no .editorconfig and no formatter config for the shell, Python, YAML, or TOML files in
the repository. Non-Rust quality is enforced through behavior instead: the shell scripts use
strict modes (set -o errexit -o nounset -o pipefail in extras/bat/tests/scripts/license-checks.sh,
set -euo pipefail in extras/bat/assets/create.sh), and the syntax-comparison tooling is Python
scripts under extras/bat/tests/syntax-tests that are themselves exercised by CI.
bat's lint setup is minimal and CI-centric. There is no clippy.toml, no deny.toml, and no
[lints] table in extras/bat/Cargo.toml. Instead:
-
CI runs clippy as a hard wall over every target and feature combination (extras/bat/.github/workflows/CICD.yml, lint job):
- run: cargo fmt -- --check - run: cargo clippy --locked --all-targets --all-features -- -D warnings
-
Both crate roots forbid unsafe code at the source level. extras/bat/src/lib.rs line 22 and extras/bat/src/bin/bat/main.rs line 1 carry:
#![deny(unsafe_code)]and there is not a single
unsafeblock anywhere under extras/bat/src. -
Allows are narrow, local, and justified. The whole of src contains only a handful, for example extras/bat/src/vscreen.rs uses
#[allow(clippy::upper_case_acronyms)]on individual ANSI-sequence enum variants, and extras/bat/build/syntax_mapping.rs uses#[allow(clippy::enum_variant_names)]on one enum. Nothing is allowed crate-wide. -
Rustdoc is linted as strictly as code: the documentation CI job runs
cargo doc --locked --no-deps --document-private-items --all-featureswithRUSTDOCFLAGS: -D warnings.
The philosophy: default clippy at -D warnings with --all-targets --all-features, kept
green permanently, beats a curated lint list that drifts. The custom check infrastructure that
does exist targets project-specific invariants that no lint can see:
- extras/bat/tests/scripts/license-checks.sh greps the whole tree, submodules included, for "General Public License" to prevent GPL contamination of an MIT/Apache project, with an explicit exclude list for false positives.
- extras/bat/tests/no_duplicate_extensions.rs asserts that no two embedded syntaxes claim the
same file extension, with a
KNOWN_EXCEPTIONSlist documenting each collision that is allowed (.h,.js,.sass,.fs,.v) and why.
There are exactly two workflows in extras/bat/.github/workflows: CICD.yml (464 lines, the whole pipeline) and require-changelog-for-PRs.yml (33 lines).
Triggers: workflow_dispatch, pull_request, and push to master plus all tags. One
workflow covers PR validation, master builds, and tag releases; release-only steps are gated by
if: startsWith(github.ref, 'refs/tags/v') style conditions rather than a separate file.
The jobs:
-
all-jobs: a required-check aggregator. Itneedsevery other job and asserts they all succeeded:
all-jobs:
if: always() # Otherwise this job is skipped if the matrix job fails
needs:
- crate_metadata
- lint
- min_version
- license_checks
- test_with_new_syntaxes_and_themes
- test_with_system_config
- documentation
- cargo-audit
- build
steps:
- run: jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}'Branch protection needs to require only this one job. And bat closes the obvious failure mode
(someone adds a job and forgets to list it) with a meta-test:
extras/bat/tests/github-actions.rs parses CICD.yml with serde_yaml and asserts that
all-jobs.needs equals the full job list minus documented exceptions (all-jobs itself and
the release-only winget job). The CI config is under test by the test suite it runs.
-
crate_metadata: extracts name, version, maintainer, homepage, and MSRV fromcargo metadata --no-deps --format-version 1piped through jq into$GITHUB_OUTPUT. Every downstream job (MSRV toolchain selection, artifact naming, Debian control files) consumes these outputs, so Cargo.toml is the single source of truth. -
min_version: installs the exact MSRV toolchain withdtolnay/rust-toolchain@masterandtoolchain: ${{ needs.crate_metadata.outputs.msrv }}, then runs the test suite with a reduced feature set defined once at the top of the file:MSRV_FEATURES: --no-default-features --features minimal-application,bugreport,build-assets. -
lint,license_checks,documentation,cargo-audit: as described in section 5, pluscargo install cargo-audit --lockedand a step that renders the built man page withman $(find . -name bat.1)so a broken roff template fails CI visibly. -
test_with_new_syntaxes_and_themes: checks out withsubmodules: true,cargo installs bat, regenerates all binary assets from the 93 submodules viabash assets/create.sh, reinstalls, runs the normal suite plus the--ignoredasset tests plustests/syntax-tests/regression_test.sh. This catches breakage introduced by upstream syntax submodule updates before they ship. -
test_with_system_config: setsBAT_SYSTEM_CONFIG_PREFIXto a fixture directory and runs the two--ignoredtests in extras/bat/tests/system_wide_config.rs. -
build: a 13-target matrix withfail-fast: falsecovering x86_64/i686/aarch64/arm on gnu, musl, MSVC (including windows-11-arm), and both macOS architectures. ARM and AArch64 Linux targets build viacross, which is pinned to a commit:
- name: Install cross
if: matrix.job.use-cross
run: cargo install cross --git https://github.com/cross-rs/cross --rev 588b3c99db52b5a9c5906fab96cfadcf1bde7863Each matrix leg also runs the tests (reduced to --lib --bin bat on emulated ARM), smoke-runs
the real binary (bat --paging=never --color=always ... --diagnostic), and then cargo checks
five feature combinations (regex-onig, regex-onig,git, regex-onig,paging,
regex-onig,git,paging, minimal-application) so the optional-dependency matrix can never
silently rot on any platform.
The same job stages release artifacts inline: a tarball or zip containing the binary, README,
licenses, CHANGELOG, generated man page, and all four shell completions pulled out of the
build script's OUT_DIR; on Ubuntu legs it additionally assembles a full Debian package
(control file, gzipped changelog, copyright file) with fakeroot dpkg-deb. On tags matching
refs/tags/v[0-9].* the artifacts are attached to the GitHub release via
softprops/action-gh-release@v2.
-
winget: runs only on version tags and publishes the MSVC zip to Winget using a third-party action pinned by full commit SHA:vedantmgoyal9/winget-releaser@19e706d4c9121098010096f9c495a70a7518b30f.
Notable absences: there is no cargo build caching (correctness and reproducibility are preferred
over speed; every build is --locked from a committed Cargo.lock), and no merge queue. Action
pinning is pragmatic: first-party and dtolnay actions by major tag, third-party publishing
actions by SHA.
Runs on every PR (skipping dependabot), fetches the PR submitter from the GitHub API, diffs CHANGELOG.md against the base branch, and greps the added lines for the PR number and the submitter's handle:
run: |
ADDED=$(git diff -U0 "origin/${PR_BASE}" HEAD -- CHANGELOG.md | grep -P '^\+[^\+].+$')
grep "#${PR_NUMBER}\\b.*${PR_SUBMITTER}\\b" <<< "$ADDED"This mechanically enforces the changelog format documented in extras/bat/CONTRIBUTING.md
(- Short description of what has been changed, see #123 (@user)).
extras/bat/.github/dependabot.yml updates three ecosystems monthly on the same schedule: cargo, gitsubmodule (the 93 syntax/theme submodules), and github-actions. Dependabot PRs are auto-merged when CI passes, which is exactly why the changelog gate excludes them and the release checklist reminds maintainers to backfill their entries.
The test architecture is layered, all under extras/bat/tests:
- End-to-end CLI tests: extras/bat/tests/integration_tests.rs (4,644 lines, 273 tests) drives
the compiled binary with
assert_cmdandpredicates. Every test goes through a factory in extras/bat/tests/utils/command.rs that sanitizes the environment first:
pub fn bat_raw_command_with_config() -> Command {
let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("bat"));
cmd.current_dir("tests/examples");
cmd.env_remove("BAT_CACHE_PATH");
cmd.env_remove("BAT_CONFIG_PATH");
cmd.env_remove("BAT_PAGER");
cmd.env_remove("PAGER");
cmd.env_remove("NO_COLOR");
...
}Tests that must mutate process-global state (PATH, env vars) are marked #[serial] from the
serial_test crate; extras/bat/tests/utils/mocked_pagers.rs temporarily prepends
tests/mocked-pagers to PATH, verifies the fakes respond ("I am most"), runs the test closure,
and restores PATH.
-
Real-terminal tests: on Unix, integration_tests.rs opens a genuine PTY with
nix::pty::openpty(see theunixmodule at the top of the file, withCHILD_WAIT_TIMEOUT: Duration = Duration::from_secs(15)andwait_timeoutguarding hangs) to test interactive-output behavior that cannot be observed through pipes. -
Snapshot tests: extras/bat/tests/snapshot_tests.rs generates 26 tests from a declarative macro, one per
--stylecomponent combination:
snapshot_tests! {
changes: "changes",
grid: "grid",
...
changes_grid_header_numbers_rule: "changes,grid,header,numbers,rule",
full: "full",
plain: "plain",
}The harness in extras/bat/tests/tester/mod.rs builds a real temporary git repository
programmatically with gix (writes a blob, a tree, a commit, then modifies the working copy)
so the "changes" gutter markers are exercised against genuine git state, then compares stdout
to committed files under tests/snapshots/output/.
-
Golden-file help tests: the
-hand--helpoutputs are snapshotted withexpect-testagainst extras/bat/doc/short-help.txt and extras/bat/doc/long-help.txt (expect_test::expect_file![expect_file].assert_eq(...)in integration_tests.rs around line 726). Any flag change shows up as a reviewable diff to documentation files. -
Invariant and meta tests: no_duplicate_extensions.rs and github-actions.rs (sections 5 and 6), plus extras/bat/tests/assets.rs, an
#[ignore]d test listing all 26 themes that must be present, run in CI only after assets are rebuilt. -
Syntax regression corpus: extras/bat/tests/syntax-tests holds a source/ directory with one sample file per language and a highlighted/ directory with the expected ANSI output; regression_test.sh regenerates and diffs them via two Python scripts. update.sh re-blesses.
-
Unit tests live inline in src modules under
#[cfg(test)](for example the detector stubs in extras/bat/src/theme.rs, section 8, and the parser tests at the bottom of extras/bat/src/less.rs). -
Benchmarks: extras/bat/tests/benchmarks/run-benchmarks.sh uses hyperfine (startup time, many-small-files, highlighting throughput), unsets the same env vars as the test factory, and writes a markdown report. Performance is measured out-of-band rather than gating CI.
There is no fuzzing or property testing in-repo; the syntax corpus plus the --ignored
asset-rebuild jobs fill that role for bat's actual risk surface (upstream syntax updates).
Errors: one public thiserror enum in extras/bat/src/error.rs, marked #[non_exhaustive] so
new variants are not semver breaks, with #[error(transparent)] #[from] wrappers for foreign
errors and feature-gated variants that only exist when the corresponding subsystem is compiled:
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Io(#[from] ::std::io::Error),
...
#[cfg(feature = "paging")]
#[error(transparent)]
MinusError(#[from] ::minus::MinusError),
}
pub type Result<T> = std::result::Result<T, Error>;From<&'static str> and From<String> fold ad-hoc messages into Error::Msg, so internal code
can write .ok_or("Empty line range")? (extras/bat/src/line_range.rs). The build script, which
is not public API, uses anyhow instead; the boundary between thiserror (library) and anyhow
(application-ish code) is drawn exactly where the textbooks say.
Exit codes and panic policy: the binary's main in extras/bat/src/bin/bat/main.rs returns
Result<bool> from run() and maps it explicitly: error prints via default_error_handler
then process::exit(1), Ok(false) (some input failed) exits 1, Ok(true) exits 0. The
error handler special-cases the one error a well-behaved CLI must swallow:
Error::Io(ref io_error) if io_error.kind() == ::std::io::ErrorKind::BrokenPipe => {
::std::process::exit(0);
}so bat file | head never reports a spurious failure.
API design:
- Builder with
&mut Selfchaining: extras/bat/src/pretty_printer.rs exposesPrettyPrinterwhose setters (input_file,language,term_width, ...) return&mut Self, with generic ergonomic bounds likepub fn input_files<I, P>(&mut self, paths: I) where I: IntoIterator<Item = P>, P: AsRef<Path>. -
#[non_exhaustive]on public data types (Syntaxin pretty_printer.rs) reserves the right to add fields. - Visibility discipline: extras/bat/src/lib.rs re-exports a curated surface
(
pub use pretty_printer::{Input, PrettyPrinter, Syntax}) while whole modules staypub(crate)(printer,syntax_mapping,wrapping,nonprintable_notation), and the crate doc explicitly warns that the deepercontrollerAPI "is much more likely to change". - Testable seams via traits: extras/bat/src/theme.rs defines
ColorSchemeDetector, implemented byTerminalColorSchemeDetectorin production (with a long comment explaining the OSC 10/11 race with pagers) and byDetectorStub/ConstantDetectorin the inline tests,DetectorStubusingCell<bool>to record invocation. The publictheme()function is a thin wrapper overtheme_impl(options, &TerminalColorSchemeDetector).
-
Build-time code generation with the proc-macro toolchain outside a proc macro. extras/bat/build/syntax_mapping.rs deserializes the builtins TOML files, then implements
quote::ToTokensfor its domain types and emits a static table, pretty-printed withprettypleaseand included viainclude!(concat!(env!("OUT_DIR"), "/codegen_static_syntax_mappings.rs"))in extras/bat/src/syntax_mapping/builtin.rs:let t = quote! { /// Generated by build script from /src/syntax_mapping/builtins/. pub(crate) static BUILTIN_MAPPINGS: [(Lazy<Option<GlobMatcher>>, MappingTarget); #len] = [#(#array_items),*]; };
-
Lazy statics as a startup-latency strategy. The generated table stores
Lazy<Option<GlobMatcher>>so glob compilation happens on first match, and builtin.rs contains a 30-line comment explaining why a cleaner-lookingBuiltinMatcherenum was tried and rejected ("Because there was. I tried it and threw it out."), a model of documenting negative design results where the temptation will recur. -
Interior mutability chosen precisely. extras/bat/src/assets.rs caches the deserialized
SyntaxSetinonce_cell::unsync::OnceCell(no threading, no atomic cost), while extras/bat/src/assets/lazy_theme_set.rs pairs serde with lazy init:struct LazyTheme { serialized: Vec<u8>, #[serde(skip, default = "OnceCell::new")] deserialized: OnceCell<syntect::highlighting::Theme>, }
and loads via
lazy_theme.deserialized.get_or_try_init(|| lazy_theme.deserialize()). -
Embedded compressed assets with documented tradeoffs. extras/bat/src/assets.rs embeds syntaxes and themes with
include_bytes!("../assets/syntaxes.bin")behindpub(crate) const COMPRESS_LAZY_THEMES: bool = true;style constants, each carrying a measured justification ("Compress for size of ~40 kB instead of ~200 kB without much difference in performance due to lazy-loading"). -
Trait objects with lifetimes for input polymorphism. extras/bat/src/input.rs models sources as an enum embedding a borrowed reader:
pub(crate) enum InputKind<'a> { OrdinaryFile(PathBuf), StdIn, CustomReader(Box<dyn Read + 'a>), }
letting
PrettyPrinter<'a>accept byte slices, files, and arbitrary readers uniformly. -
Small strategy traits instead of match trees. extras/bat/src/decorations.rs defines
pub(crate) trait Decoration { fn generate(...); fn width(...); }withLineNumberDecoration,LineChangesDecoration, andGridBorderDecorationimpls (LineNumberDecoration caches its wrapped-line filler and invalidates atcached_wrap_invalid_at: 10000); extras/bat/src/printer.rs hastrait PrinterwithSimplePrinterandInteractivePrinterimplementations selected by config. -
Conversion traits as API glue. extras/bat/src/assets/lazy_theme_set.rs implements
TryFrom<LazyThemeSet> for ThemeSetandTryFrom<ThemeSet> for LazyThemeSetso users can add custom themes to the lazily-loaded set; extras/bat/build/syntax_mapping.rs implementsFromStrwithtype Err = Infalliblewhere parsing cannot fail, and derives deserialization from it viaserde_with::DeserializeFromStr. -
Platform handling in three tiers. Target-conditional dependencies in Cargo.toml (plist on macOS, nix on Unix); 128
#[cfg(...)]attributes in src including whole-file gates like#![cfg(feature = "git")]at the top of extras/bat/src/diff.rs; and data-level platform splits, where extras/bat/build/syntax_mapping.rs selects builtins subdirectories with inline cfg on array elements (#[cfg(target_family = "unix")] "unix-family",). Divergent behavior gets paired cfg functions:color_scheme_from_system()in extras/bat/src/theme.rs has a macOS implementation reading.GlobalPreferences.plistand a non-macOS one that warns. -
Declarative macros for both product and tests. extras/bat/src/macros.rs exports
bat_warning!to standardize the yellow "[bat warning]" prefix; thesnapshot_tests!macro in extras/bat/tests/snapshot_tests.rs stamps out one named#[test]per style permutation so failures name the exact combination. -
Iterator pipelines over fallible data. extras/bat/build/syntax_mapping.rs walks TOML files with
WalkDirand itertools'filter_map_ok(...).collect::<Result<Vec<_>, _>>()?, propagating IO errors through the pipeline instead of unwrapping; extras/bat/src/preprocessor.rs decodes UTF-8 incrementally with anOptioncombinator chain (input.get(0..1).and_then(str_from_utf8).map(|c| (c, 1)).or_else(...)) andexpand_tabscopies escape sequences by byte-range slicing (&line[seq.index_of_start().. seq.index_past_end()]) rather than re-parsing, with a capacity hint (String::with_capacity(line.len() * 2)).
Two bonus idioms: wild::args_os() is used throughout extras/bat/src/bin/bat/app.rs so glob
patterns expand on Windows exactly as a Unix shell would, and the thread-based builtin pager in
extras/bat/src/output.rs holds handle: Option<JoinHandle<Result<()>>> so the pager thread's
error is joined and propagated rather than dropped.
- The crate doc in extras/bat/src/lib.rs opens with a runnable doctest ("Hello world" through
PrettyPrinter) and an honest stability statement about the internal modules. Public items in extras/bat/src/theme.rs show the house rustdoc style: intra-doc links ([crate::theme::ThemeOptions::theme]), doctested constructors, and apub mod envthat documents environment variable names as constants. - extras/bat/doc is a real documentation directory: assets.md (how the syntax/theme pipeline works, including how to write syntax tests), alternatives.md, release-checklist.md, and four translated READMEs (ja, ko, ru, zh). long-help.txt and short-help.txt are not prose, they are test fixtures asserted by expect-test, so the docs cannot drift from the binary.
- extras/bat/CONTRIBUTING.md is operational, not ceremonial: it specifies the exact changelog entry format that CI greps for, says when an entry is not needed, and states "You are strongly encouraged to add regression tests" with a pointer to integration_tests.rs.
- Data formats are documented next to the data: extras/bat/src/syntax_mapping/builtins/README.md explains the TOML rule schema, file organization, and dynamic env-var replacement.
- extras/bat/.github/ISSUE_TEMPLATE has four templates (bug_report, feature_request, question, syntax_request); the bug template preempts the most-reported known issue inline. SECURITY.md gives a private disclosure contact. There is no PR template and no ARCHITECTURE.md; the module doc in lib.rs and doc/assets.md carry that weight.
- Developer environment is reproducible: extras/bat/flake.nix defines dev shells for four
systems and extras/bat/.envrc (
use flake) wires it to direnv.
- Versioning: semver in Cargo.toml, released as git tags
vX.Y.Z. Pushing the tag is the release trigger; extras/bat/.github/workflows/CICD.yml detects$GITHUB_REF =~ ^refs/tags/v[0-9].*and uploads all 13 targets' archives plus Debian packages to the GitHub release. - The process is codified in extras/bat/doc/release-checklist.md as literal checkboxes: bump
version, re-derive MSRV via
cargo metadata | jq, reconcile CHANGELOG.md against auto-generated release notes (dependabot PRs are auto-merged and therefore missing), rebuild binary assets with assets/create.sh, review -h/--help/man,cargo publish --dry-run, tag, create the GitHub release from the changelog section, verify artifacts,cargo publishfrom a clean clone, then reset the "unreleased" changelog skeleton (Features / Bugfixes / Other / Syntaxes / Themes / "bat as a library"). - Changelog discipline is enforced by machine on the way in (the changelog workflow, section 6) and consumed on the way out (release notes are copied from CHANGELOG.md).
- Man page and completions are build outputs, not hand-maintained artifacts:
extras/bat/build/application.rs renders extras/bat/assets/manual/bat.1.in and four completion
templates (bash, fish, zsh, PowerShell) with a tiny variable-substitution engine
(
PROJECT_NAME,PROJECT_EXECUTABLE,PROJECT_VERSION), honoringBAT_ASSETS_GEN_DIRso packagers can redirect output. The generated files are gitignored (extras/bat/.gitignore lists/assets/manual/bat.1and the completion outputs) and packaged from OUT_DIR by CI into both tarballs and .deb layouts (usr/share/bash-completion/completions/bat,usr/share/man/man1/bat.1.gz). - Distribution breadth: GitHub release archives for every target, self-built Debian packages
with correct Provides/Conflicts between
batandbat-musl, Winget publishing, crates.io for the library, plus static CRT linking on Windows and musl builds on Linux so binaries run anywhere.
quinjet already exceeds bat on static analysis (clippy wall, cargo-deny, taplo, typos, miri, mutants, coverage floor). What bat adds is CI architecture, end-to-end CLI testing, and release mechanics. Concrete adoptions:
- Add an
all-jobsaggregator job thatneedsevery other job withif: always()and thejq --exit-status 'all(.result == "success")'step from extras/bat/.github/workflows/CICD.yml, then make it the only required branch-protection check. - Copy the meta-test pattern from extras/bat/tests/github-actions.rs: a
#[test]that parses the workflow YAML withserde_yaml(dev-dependency) and asserts the aggregator'sneedslist matches the set of defined jobs, with an explicit exceptions array. - Add a
crate_metadataCI job that extractsrust-versionviacargo metadata --no-deps --format-version 1 | jq -r '.packages[0].rust_version'and feed it to an MSRV job usingdtolnay/rust-toolchain@masterwithtoolchain: ${{ outputs.msrv }}, so the MSRV lives only in Cargo.toml. - Snapshot
quinjet --helpand every subcommand's--helpinto committeddoc/*.txtfiles using theexpect-testcrate'sexpect_file!(bless withUPDATE_EXPECT=1), exactly as extras/bat/tests/integration_tests.rs does against doc/long-help.txt. CLI surface changes become reviewable diffs. - Build the CLI end-to-end suite on
assert_cmd+predicateswith a single command factory thatenv_removes every quinjet- and git-relevant variable (GIT_DIR,GIT_CONFIG_*,HOME-scoped config) per extras/bat/tests/utils/command.rs, and mark PATH/env-mutating tests#[serial]with theserial_testcrate. - For TUI behavior that depends on a real terminal, use
nix::pty::openptybehind[target.'cfg(unix)'.dev-dependencies]pluswait-timeoutfor hang protection, following theunixmodule at the top of extras/bat/tests/integration_tests.rs. - Steal the snapshot-permutation macro from extras/bat/tests/snapshot_tests.rs, and its harness
idea: construct a throwaway git repository programmatically in the test (quinjet can shell
out to
git initor usegixlike extras/bat/tests/tester/mod.rs) so every rendered view is tested against real repository state, not mocks. - Handle
ErrorKind::BrokenPipeby exiting 0 in the top-level error handler, per extras/bat/src/error.rsdefault_error_handler; a Git CLI whose output feedshead,fzf, or a pager must not report failure on early pipe close. - Generate the man page and bash/zsh/fish completions from
build.rs(quinjet can useclap_mangen/clap_completerather than bat's templates) and package them in release archives under anautocomplete/directory as CICD.yml's "Create tarball" step does. - Add a release build matrix in the same workflow as PR CI, gated on
refs/tags/v*: linux gnu+musl (viacrosspinned to a commit), macOS both arches, Windows MSVC withcrt-staticrustflags in.cargo/config.toml, uploading archives withsoftprops/action-gh-release@v2; pin third-party publishing actions by full SHA. - Enforce changelog entries mechanically with a 33-line workflow cloned from
extras/bat/.github/workflows/require-changelog-for-PRs.yml: diff CHANGELOG.md against the
base branch and grep added lines for
#<PR> ... <submitter>. - Gate rustdoc in CI with
RUSTDOCFLAGS: -D warningsandcargo doc --locked --no-deps --document-private-items --all-features(extras/bat/.github/workflows/CICD.yml documentation job); this catches broken intra-doc links that clippy does not. - Add invariant tests in the style of extras/bat/tests/no_duplicate_extensions.rs: assert no
duplicate clap subcommand names/aliases and no conflicting keybindings, each with a
documented
KNOWN_EXCEPTIONSlist if any. - Add a
hyperfine-based startup benchmark script like extras/bat/tests/benchmarks/run-benchmarks.sh; keyboard-first tools live and die on startup latency, and a markdown report per release makes regressions visible without gating CI. - Configure dependabot for
cargoandgithub-actionsecosystems on a monthly schedule (extras/bat/.github/dependabot.yml), and write the release process as a checkbox filedoc/release-checklist.mdso releases are reproducible by any maintainer.
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.
Meilisearch is a search engine shipped as a single HTTP server binary. Industry uses it as a
self-hostable, typo-tolerant, millisecond-latency alternative to Elasticsearch for product and
site search, and increasingly for hybrid keyword-plus-vector search. The binary embeds an
actix-web HTTP layer, an LMDB-backed storage engine (milli), a task scheduler, an
authentication store, and a bundled web dashboard.
Scale indicators measured directly from the clone at extras/meilisearch:
- 707 Rust source files under
extras/meilisearch/cratesandextras/meilisearch/external-crates, totaling roughly 261,000 raw lines. - 23 workspace members: 21 first-party crates under
extras/meilisearch/cratesplus two vendored crates underextras/meilisearch/external-crates(async-openaiandasync-openai-macros, forked so they can depend on the in-treehttp-clientandroutescrates, as seen inextras/meilisearch/external-crates/async-openai/Cargo.toml). - Workspace version
1.53.1inextras/meilisearch/Cargo.toml, on edition 2021, with the toolchain pinned to Rust 1.91.1 inextras/meilisearch/rust-toolchain.toml. - 16 CI workflow files in
extras/meilisearch/.github/workflows.
extras/meilisearch/
|-- Cargo.toml workspace root: members, shared metadata, profiles
|-- rust-toolchain.toml pinned channel 1.91.1 + clippy component
|-- clippy.toml disallowed-methods configuration
|-- .rustfmt.toml four-line formatting policy
|-- .cargo/config.toml the `cargo xtask` alias
|-- config.toml annotated default runtime configuration for the server
|-- Dockerfile two-stage alpine build
|-- download-latest.sh curl-installable binary fetcher
|-- crates/ 21 first-party crates
|-- external-crates/ vendored forks (async-openai, reqwest-eventsource)
|-- workloads/ JSON benchmark workloads + workloads/tests declarative tests
|-- documentation/ internal process docs (release, versioning, prototypes)
|-- .github/ workflows, scripts, templates, dependabot
|-- BENCHMARKS.md, TESTING.md, PROFILING.md, CONTRIBUTING.md, SECURITY.md
The crate split under extras/meilisearch/crates maps cleanly to runtime layers:
crates/
|-- meilisearch the HTTP binary: routes, options, analytics, tests
|-- meilitool offline maintenance CLI (dump export, offline upgrade)
|-- meilisearch-types shared API types, error codes, settings DTOs
|-- meilisearch-auth API key store
|-- index-scheduler task queue, batching, scheduler state machine
|-- milli the core indexing and search engine (largest crate)
|-- filter-parser nom parser for the filter DSL
|-- flatten-serde-json JSON flattening (own README used as crate docs)
|-- json-depth-checker fast depth probing for JSON values
|-- permissive-json-pointer JSON pointer selection
|-- dump / file-store dump import-export and update file storage
|-- meili-snap in-house snapshot-testing layer over insta
|-- fuzzers long-running in-tree fuzzer binaries
|-- tracing-trace span-level profiling transport
|-- xtask workspace automation (bench, declarative tests, tags)
|-- build-info vergen-based git metadata as a library
|-- openapi-generator / routes / routes-macros / http-client
Why this split works: the boundary between milli (pure engine, no HTTP) and meilisearch
(HTTP surface) lets the engine be tested and benchmarked without a server, while small
leaf crates like filter-parser and flatten-serde-json get their own fuzz targets and
criterion benches. Test-only machinery (meili-snap), automation (xtask), and build
metadata (build-info) are real crates, not scripts, so they are compiled and type-checked
on every CI run.
extras/meilisearch/Cargo.toml uses [workspace.package] for shared metadata, and every
member inherits it:
[workspace.package]
version = "1.53.1"
authors = [
"Quentin de Quelen <quentin@dequelen.me>",
"Clément Renault <clement@meilisearch.com>",
]
description = "Meilisearch HTTP server"
edition = "2021"
license = "MIT"Member manifests such as extras/meilisearch/crates/meilisearch/Cargo.toml start with
publish = false and a block of key.workspace = true lines. A deliberate oddity: the
workspace centralizes almost no dependency versions. [workspace.dependencies] contains
exactly one entry, mimalloc, because the allocator must be byte-identical across crates;
everything else is declared per crate with explicit versions and pruned features
(default-features = false appears throughout, for example actix-web, rustls, sysinfo,
grenad, heed in the manifests above). Version drift is accepted in exchange for
per-crate independence.
Profiles in extras/meilisearch/Cargo.toml are tuned per package:
[profile.release]
codegen-units = 1
[profile.release-with-debug]
inherits = "release"
debug = true
# We now compile heed without the NDEBUG define for better performance.
# However, we still enable debug assertions for a better detection of
# disk corruption on the cloud or in OSS.
[profile.release.package.heed]
debug-assertions = true
[profile.dev.package.flate2]
opt-level = 3grenad, roaring, and gemm-f16 also get opt-level = 3 in dev so tests over compressed
and bitmap data stay fast. There is no rust-version key; the MSRV story is instead the hard
pin in extras/meilisearch/rust-toolchain.toml (channel = "1.91.1"), which every CI job
mirrors exactly.
Feature flags in extras/meilisearch/crates/meilisearch/Cargo.toml model product
dimensions: one feature per optional tokenizer language (chinese, japanese, hebrew,
swedish-recomposition, ...), each just forwarding to meilisearch-types/<lang>, plus
mini-dashboard (which gates eight optional build-dependencies), swagger, test-ollama
(a test-only feature), and enterprise. The dashboard assets are declared as data in the
manifest and verified in build.rs:
[package.metadata.mini-dashboard]
assets-url = "https://github.com/meilisearch/mini-dashboard/releases/download/v0.4.2/build.zip"
sha1 = "6a8a76d9ed79357959bc6d4e3816f753a605a27b"extras/meilisearch/crates/meilisearch/build.rs downloads that zip, checks the sha1, and
caches it under OUT_DIR. Another manifest detail worth copying: a pinned dev-dependency
with the reason attached, in the same file:
# fixed version due to format breakages in v1.40
insta = { version = "=1.39.0", features = ["redactions"] }No [lints] tables exist anywhere; lint policy lives in CI flags and crate attributes
(section 5). extras/meilisearch/crates/milli/Cargo.toml shows a migration trace:
edition = "2021" is set explicitly with # edition.workspace = true commented out.
extras/meilisearch/.rustfmt.toml is four lines:
unstable_features = true
use_small_heuristics = "max"
imports_granularity = "Module"
group_imports = "StdExternalCrate"-
use_small_heuristics = "max"makes rustfmt keep any construct on one line as long as it fits in the width limit, producing dense struct literals and match arms; you can see the effect in one-liners likeServer { service, _dir: Some(dir), _marker: PhantomData }inextras/meilisearch/crates/meilisearch/tests/common/server.rs. -
imports_granularity = "Module"merges imports per module path, oneuseper module. -
group_imports = "StdExternalCrate"enforces the visible three-block import order (std, external, crate) at the top of every file, for exampleextras/meilisearch/crates/milli/src/index.rs. -
unstable_features = trueopts into the two nightly-gated options above; the CIfmtjob inextras/meilisearch/.github/workflows/test-suite.ymlrunscargo fmt --all -- --checkon the pinned stable toolchain.
There is no .editorconfig and no formatter for YAML, TOML, or Markdown; only Rust is
machine-formatted. extras/meilisearch/.gitattributes marks Cargo.lock -linguist-generated
so lockfile churn collapses in review.
There is no [lints] table and no crate-wide #![deny] wall. The policy has three layers:
-
Warnings are errors globally in CI via an environment variable, not attributes.
extras/meilisearch/.github/workflows/test-suite.ymlsetsRUSTFLAGS: "-D warnings"for every job, so plaincargo buildandcargo testalso fail on warnings. -
Clippy runs at default lint levels, escalated on the command line:
- name: Run cargo clippy run: cargo clippy --all-targets ${{ matrix.features }} -- --deny warnings -D clippy::todo
-D clippy::todois the one targeted escalation:todo!()cannot reachmain. -
Targeted, machine-checked API bans in
extras/meilisearch/clippy.toml:disallowed-methods = [ { path = "tar::Archive::unpack", reason = "prefer using the ArchiveExt::safe_unpack function" } ]
The one sanctioned call site in
extras/meilisearch/crates/meilisearch-types/src/archive_ext.rscarries#[allow(clippy::disallowed_methods)]with the comment "This is the only place where we useunpackdirectly and we do the verification just after", and then checks that no unpacked symlink escapes the destination directory. This is lint configuration used as a security control: the safe wrapper is the only way to unpack a tarball.
Allows are scarce, top-of-crate, and always about accepted trade-offs rather than silencing:
#![allow(clippy::result_large_err)] in
extras/meilisearch/crates/meilisearch/src/lib.rs,
extras/meilisearch/crates/meilisearch-types/src/lib.rs,
extras/meilisearch/crates/index-scheduler/src/lib.rs, and
extras/meilisearch/crates/meilitool/src/main.rs (their error enums are deliberately rich),
and #![allow(clippy::type_complexity)] in extras/meilisearch/crates/milli/src/lib.rs.
The philosophy: keep the default lint set, make it blocking, and reserve custom machinery
for bans that encode a real invariant. Custom check infrastructure beyond clippy lives in
the openapi-generator crate, which CI runs with --check-summaries,
--check-descriptions, --check-paths, --check-docs, and --check-params
(extras/meilisearch/.github/workflows/check-openapi-file.yml): self-written consistency
lints for the documented API surface, plus third-party spectral linting against
crates/openapi-generator/.spectral.yaml.
All 16 workflows live in extras/meilisearch/.github/workflows. Cross-cutting habits:
- Every third-party action is pinned to a full commit SHA with a human-readable comment,
for example
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6anduses: dtolnay/rust-toolchain@38ae5351029910ad7674ccfad89c37cbd636f3c4 # 1.91.1throughouttest-suite.yml.extras/meilisearch/.github/dependabot.ymlkeeps only thegithub-actionsecosystem updated, monthly, with a 7-day cooldown andrebase-strategy: disabled. - Caching is
Swatinem/rust-cachekeyed by the feature matrix (key: ${{ matrix.features }}), and Linux jobs reclaim disk first by deleting the preinstalled GHC, dotnet, Android, and boost trees. - Workflows that only need to read set
permissions: contents: read(release assets, OpenAPI check) orpermissions: {}(docker build job).
test-suite.yml is the PR gate. Triggers are pull_request, merge_group (the repository
uses the GitHub merge queue; extras/meilisearch/README.md even carries a "Merge Queues
enabled" badge), a daily 5am cron, and workflow_dispatch. The job graph makes the expensive
tail conditional:
-
test-linux: matrix overubuntu-22.04andubuntu-22.04-arm, each with and without--features enterprise; builds--no-default-featuresfirst, then tests--locked --all. -
test-windows: runs on PRs butif: github.event_name != 'merge_group'. -
test-macosandtest-all-features: only on schedule or manual dispatch, so macOS cost and the near-full feature build (cargo xtask list-features --exclude-feature cuda,test-ollamafeedingcargo test --features "$(...)") never slow a PR. -
ollama-ubuntu: installs a real Ollama server, pulls two embedding models, and runs thetest-ollamafeature tests against it. -
test-legacy-indexer: the whole suite again underMEILI_EXPERIMENTAL_NO_EDITION_2024_FOR_SETTINGS: "true", exercising a compatibility code path. -
test-disabled-tokenization: asserts withcargo tree -f '{p} {f}' -e normal --no-default-features | grep -qz linderathat a heavy tokenizer dependency cannot leak into the default graph. Dependency-graph shape is treated as a testable invariant. -
declarative-tests:cargo xtask test workloads/tests/*.json(section 7). -
clippyandfmtjobs as described above, plus abuildjob compiling release mode.
Merge-quality workflows: db-change-missing.yml fails any PR that carries neither the
db change nor the no db change label, and db-change-comments.yml posts a canned
checklist (forward-compatibility proof, dumpless-upgrade declarative test) when db change
is applied. Benchmarks run from PR comments: bench-pr.yml triggers on
issue_comment bodies starting with /bench, and before running anything it verifies that
both the PR author and the comment author have push permission, that the PR is not from a
fork, and that the head commit was pushed before the comment was written (defeating a
push-after-approval race). Scheduled hygiene: flaky-tests.yml runs cargo flaky -i 100 --release nightly across four crates, fuzzer-indexing.yml runs the in-tree fuzzer for up
to 72 hours (timeout-minutes: 4320) on every push to main, sdks-tests.yml tests the
nightly Docker image against every official SDK daily, and dependency-issue.yml files an
"Upgrade dependencies" issue every six months from a template in
extras/meilisearch/.github/templates.
Four distinct test tiers exist, each with its own infrastructure.
Unit tests live next to code, and milli has an in-crate harness:
extras/meilisearch/crates/milli/src/test_index.rs defines pub(crate) struct TempIndex
wrapping a temporary LMDB environment with Deref to Index, and
extras/meilisearch/crates/milli/src/snapshot_tests.rs renders databases to text for
snapshotting. Committed snapshot directories sit beside the modules that own them, for
example extras/meilisearch/crates/milli/src/search/facet/snapshots and
extras/meilisearch/crates/index-scheduler/src/scheduler/snapshots.
Integration tests drive the real HTTP surface.
extras/meilisearch/crates/meilisearch/tests has one directory per API area (auth,
documents, search, settings, tasks, vector, ...) and a common module whose
Server type boots the actual setup_meilisearch entry point inside a TempDir. The
harness uses a typestate to distinguish throwaway servers from process-wide shared ones
(extras/meilisearch/crates/meilisearch/tests/common/server.rs):
pub struct Server<State = Owned> {
pub service: Service,
// hold ownership to the tempdir while we use the server instance.
_dir: Option<TempDir>,
_marker: PhantomData<State>,
}with pub enum Shared {} and pub enum Owned {} as uninhabited marker types in
extras/meilisearch/tests/common/mod.rs (path
extras/meilisearch/crates/meilisearch/tests/common/mod.rs); mutating helpers are only
implemented for Server<Owned>, so a test cannot corrupt the shared fixture server by
construction. The same file wraps serde_json::Value in a newtype with #[track_caller]
assertion helpers (succeeded(), batch_uid()) so failures point at the test line.
Snapshot testing is industrialized in the dedicated crate
extras/meilisearch/crates/meili-snap. Its snapshot! and snapshot_hash! macros wrap
insta: snapshot_hash! stores only an inline md5 hash in the source while writing the full
snapshot to disk when MEILI_TEST_FULL_SNAPS=true, keeping thousands of assertions cheap in
the repository. The helper derives the snapshot path from
std::panic::Location::caller() and the test function name (captured with the
type_name_of_val trick inside the macro), and installs dynamic redactions that rewrite
UUIDs in messages and JSON keys to [uuid] so snapshots are stable across runs
(extras/meilisearch/crates/meili-snap/src/lib.rs).
Declarative tests are the fourth tier, documented in extras/meilisearch/TESTING.md:
JSON files under extras/meilisearch/workloads/tests describe a binary to download
("source": "release", a version, an edition), a chain of HTTP commands, and expected
responses; cargo xtask test executes them, which is how dumpless upgrades from released
versions are verified against the working tree.
Fuzzing exists in two forms: classic cargo-fuzz targets in
extras/meilisearch/crates/filter-parser/fuzz, crates/milli/fuzz,
crates/flatten-serde-json/fuzz, and crates/json-depth-checker/fuzz (the filter-parser
target panics only on ErrorKind::InternalError, treating user-facing parse errors as
success), and the stateful extras/meilisearch/crates/fuzzers crate whose fuzz-indexing
binary CI runs for up to three days. Benchmarks: criterion harnesses in
extras/meilisearch/crates/flatten-serde-json/Cargo.toml ([[bench]] harness = false) and
crates/json-depth-checker, plus the workload-based end-to-end system described in
extras/meilisearch/BENCHMARKS.md, which measures tracing spans from a live server and
uploads results to a dashboard.
The library crates use thiserror 2.x exclusively (declared in seven manifests, for example
extras/meilisearch/crates/milli/Cargo.toml); anyhow appears only at binary and
automation boundaries (meilisearch's main, xtask, build scripts). milli's root error
in extras/meilisearch/crates/milli/src/error.rs splits by audience, not by module:
#[derive(Error, Debug)]
pub enum Error {
#[error("internal: {0}.")]
InternalError(#[from] InternalError),
#[error(transparent)]
IoError(#[from] io::Error),
#[error(transparent)]
UserError(#[from] UserError),
}InternalError variants indicate engine bugs; UserError variants are for humans. One
layer up, extras/meilisearch/crates/meilisearch-types/src/error.rs turns any error into a
stable HTTP contract: a make_error_codes! declarative macro generates the Code enum, an
HTTP status, a snake_case name, and a documentation URL per code, plus one marker unit type
per code so deserialization errors can be typed as DeserrJsonError<MyErrorCode>. A single
blanket impl bridges the two worlds:
impl<T> From<T> for ResponseError
where
T: std::error::Error + ErrorCode,
{
fn from(other: T) -> Self {
Self::from_msg(other.to_string(), other.error_code())
}
}Panic policy: the server installs a hook that routes panics into structured logs
(fn on_panic(info: &std::panic::PanicHookInfo) in
extras/meilisearch/crates/meilisearch/src/main.rs), and main delegates to
try_main(...).await.inspect_err(...), walking error.source() to log the full causal
chain before exiting nonzero through anyhow::Result. Inside the engine, panics in worker
threads are captured as values: InternalError::PanicInThreadPool(#[from] CaughtPanic)
backed by extras/meilisearch/crates/milli/src/thread_pool_no_abort.rs.
Configuration API design in extras/meilisearch/crates/meilisearch/src/option.rs is a
model for CLI servers: every flag is one struct field with doc comment (which becomes
--help text), a #[clap(long, env = MEILI_...)] attribute using a named constant for the
env var, and serde attributes for the TOML config file. Opt::try_build implements
precedence "toml < env vars < cli args" by parsing once, reading the config file, injecting
its values into the environment via export_to_env, and parsing again. Small string enums
get hand-written FromStr with error types that enumerate valid values
(LogModeError reports "Unsupported log mode level {0}. Supported values are HUMAN and
JSON."). Visibility discipline shows in extras/meilisearch/crates/milli/src/index.rs:
the LMDB env and untyped main database are pub(crate), while each typed database is
pub with a doc comment; the tri-state Setting<T> enum (Set, Reset, NotSet) in
extras/meilisearch/crates/milli/src/update/settings.rs distinguishes "reset to default"
from "leave untouched" across the settings API instead of overloading Option.
-
Typed key-value schema.
extras/meilisearch/crates/milli/src/index.rsgives every LMDB database a typed codec pair, so reads and writes are type-checked at compile time:/// A word and all the documents ids containing the word. pub word_docids: Database<Str, CboRoaringBitmapCodec>, /// Maps the proximity between a pair of words with all the docids where this relation appears. pub word_pair_proximity_docids: Database<U8StrStrCodec, CboRoaringBitmapCodec>,
-
Size-adaptive custom codecs.
extras/meilisearch/crates/milli/src/heed_codec/roaring_bitmap/cbo_roaring_bitmap_codec.rsencodes bitmaps of up toTHRESHOLD = 7integers as raw native-endianu32s and larger ones as serialized roaring bitmaps, choosing the decoder purely from byte length. The codec module distinguishes borrowed decoding (Cow<[u8]>, zero-copy from LMDB pages) from owned decoding via the separateBytesDecodeOwnedtrait. -
A documented unsafe marker trait.
extras/meilisearch/crates/milli/src/update/new/thread_local.rsdefinespub unsafe trait MostlySend {}for types that are!Sendonly because sending would allow concurrent access to!Syncdata, with a full safety contract in rustdoc, aFullySend<T>bridge (unsafe impl<T> MostlySend for FullySend<T> where T: Send {}), and structural impls forRefCell<T>andOption<T>. This is what lets the parallel indexer keep per-threadBumparenas withoutMutexes. -
Interior mutability tuned to the scheduler.
extras/meilisearch/crates/milli/src/update/new/ref_cell_ext.rsextendsRefCellwithborrow_mut_or_yield, which reacts to a failed dynamic borrow by callingrayon::yield_local()in a loop, cooperating with work stealing instead of panicking. -
Arena allocation for indexing. The new indexer threads
&'indexer Bumpallocators through the pipeline, collecting into arena-backed containers:hashbrown::HashSet<DocumentId, hashbrown::DefaultHashBuilder, &'extractor Bump>inextras/meilisearch/crates/milli/src/update/new/indexer/document_deletion.rs. -
Lazy streaming iterators over storage.
extras/meilisearch/crates/milli/src/search/facet/facet_sort_ascending.rsimplementsimpl<'t> Iterator for AscendingFacetSort<'t, '_>over an LMDB read transaction, so facet ordering never materializes intermediate collections; the same pattern appears infacet_sort_descending.rsanddocuments/sort.rs. -
Grammar-first parsing.
extras/meilisearch/crates/filter-parser/src/lib.rsopens with the complete BNF of the filter language as module docs (filter = expression EOF, ...), then implements it withnom+nom_locateso error spans point into user input, and dedicates parse rules to producing good errors for known mistakes (ageoPointused as a value). -
Exhaustiveness as a change detector.
extras/meilisearch/crates/index-scheduler/src/insta_snapshot.rsdestructures the wholeIndexScheduler { processing_tasks, env, version, queue, ..., features: _, webhooks: _, }struct field by field; adding a field breaks compilation of the snapshot function until the author decides whether it must be snapshotted or explicitly ignored. -
Deterministic concurrency testing with rendezvous channels.
extras/meilisearch/crates/index-scheduler/src/test_utils.rsdefines aBreakpointenum (Start,BatchCreated,ProcessBatchFailed, ...) and sends each breakpoint twice over a zero-capacity crossbeam channel, so the scheduler thread blocks until the test explicitly advances it; tests then calladvance_till([...])and snapshot the state. -
Proc macros for a self-documenting router.
extras/meilisearch/crates/routes-macros/src/lib.rsprovides#[routes::routes(...)], which registers actix handlers and simultaneously implementsutoipa::OpenApi, keeping the OpenAPI document and the real routing table generated from one declaration (checked in CI bycheck-openapi-file.yml). -
Platform cfg kept at the edges. The allocator swap is two lines in
extras/meilisearch/crates/meilisearch/src/main.rs(#[cfg(not(windows))] #[global_allocator] static ALLOC: mimalloc::MiMalloc), and the test harness setsTMPon Windows versusTMPDIRelsewhere (extras/meilisearch/crates/meilisearch/tests/common/server.rs). -
Build-time git metadata as a typed library.
extras/meilisearch/crates/build-info/src/lib.rsreadsoption_env!("VERGEN_GIT_*")(emitted byvergen-gitclinbuild.rs, overridable withMEILI_NO_VERGENto keep incremental builds warm) and parses the describe string into aDescribeResult::{Prototype, Release, Prerelease, NotATag}enum instead of exposing raw strings. -
Unsafe with receipts. Only 88
unsafeoccurrences exist across roughly 261,000 lines, and load-bearing ones carry// SAFETY:comments, for example// SAFETY: we are not keeping any reference to LMDB's datainextras/meilisearch/crates/milli/src/sharding/mod.rsand// SAFETY: precondition, the grenad value was saved from a stringinextras/meilisearch/crates/milli/src/update/index_documents/extract/extract_vector_points.rs.
Process documentation is versioned next to the code. extras/meilisearch/documentation
holds release.md (the weekly release checklist), versioning-policy.md,
experimental-features.md (what qualifies as experimental and how users opt in), and
prototypes.md (Docker-image prototypes named prototype-v<version>-<name>.<iteration>,
enforced by cargo xtask generate-prototype). Root-level guides split by task:
CONTRIBUTING.md (build, test, LINDERA_CACHE and MEILI_NO_VERGEN build accelerators,
snapshot workflow with cargo insta and MEILI_TEST_FULL_SNAPS), TESTING.md (the
declarative test format), BENCHMARKS.md (its opening states the design philosophy:
"integration benchmarks, in the sense that they spawn an actual Meilisearch server and
measure its performance end-to-end"), and PROFILING.md (Puffin-based span profiling).
Rustdoc conventions: small crates make their README the crate documentation
(#![doc = include_str!("../README.md")] in
extras/meilisearch/crates/permissive-json-pointer/src/lib.rs and
crates/flatten-serde-json/src/lib.rs), which keeps README examples compile-tested. Public
macros document argument lists and behavior with examples
(extras/meilisearch/crates/meili-snap/src/lib.rs), and every database field of the core
Index struct carries a one-line doc. The PR template
(extras/meilisearch/.github/pull_request_template.md) is a requirements checklist:
automated tests added, upgrade tested with --upgrade-db when the DB changed, search
availability during upgrade verified, docs and integrations ready. Issue templates live in
extras/meilisearch/.github/ISSUE_TEMPLATE with a config.yml routing questions elsewhere.
Versioning is workspace-wide semver (1.53.1 in extras/meilisearch/Cargo.toml) under the
policy in extras/meilisearch/documentation/versioning-policy.md. There is no CHANGELOG
file; release notes are GitHub Releases, with a skip changelog PR label for exclusions
(applied by the automation in update-cargo-toml-version.yml). The release chain is fully
scripted:
- Version bumps are themselves a workflow:
extras/meilisearch/.github/workflows/update-cargo-toml-version.ymlrewrites the workspace version withsd, rebuilds to refreshCargo.lock, and opens a PR. -
extras/meilisearch/.github/scripts/check-release.shgates every publish job by checking the git tag against bothCargo.tomlandCargo.lock(read viagrep -A 1 '^name = "meilisearch-auth"'), so a mismatched tag cannot ship. -
publish-release-assets.ymlbuilds binaries for a 6-target matrix (macOS Intel and ARM, Windows, Linux amd64/aarch64/riscv64, the latter viacross) times two editions (community, enterprise as a cargo feature), uploads them to the GitHub release, and also runs the whole matrix nightly as a dry run so release day cannot discover a broken build. -
publish-docker-images.ymlbuilds per-architecture images on native runners (ubuntu-24.04andubuntu-24.04-arm), pushes them by digest, then merges digests into a multi-arch manifest;latestandvX.Yfloating tags are only applied for stable releases, and anightlytag is rebuilt daily by cron. -
publish-apt-brew-pkg.ymlbuilds a Debian package withcargo-debinside anubuntu:22.04container (pinning glibc 2.35) and bumps the Homebrew formula. -
latest-git-tag.ymlforce-moves alatestgit tag on stable releases, which is whatextras/meilisearch/download-latest.sh, the curl-install script at the repository root, resolves.
The Dockerfile is a two-stage alpine build that injects VERGEN_GIT_* values as build args
(because the image builds outside a git checkout), ships both meilisearch and meilitool,
and runs under tini (extras/meilisearch/Dockerfile).
quinjet already has a stricter lint wall than Meilisearch, plus cargo-deny, taplo, typos, coverage, miri, and mutants. The practices still worth importing, with mechanisms:
- Hash-based snapshot testing for TUI frames and CLI output. Add
insta(featuresredactions) plus a smallsnapshot!/snapshot_hash!macro module modeled onextras/meilisearch/crates/meili-snap/src/lib.rs: md5 hash inline in the test, full snapshot written only when an env toggle likeQUINJET_TEST_FULL_SNAPS=trueis set, and dynamic redactions for volatile values (commit hashes, timestamps) the way meili-snap rewrites UUIDs. This keeps hundreds of rendered-frame assertions out of the diff. -
disallowed-methodsas an invariant enforcer. quinjet's clippy wall is level-based; Meilisearch shows the complementary tool: entries inclippy.tomlsuch as{ path = "std::process::exit", reason = "..." }or banning directcrossterm::terminal::disable_raw_modeoutside the terminal-guard module, with exactly one#[allow(clippy::disallowed_methods)]at the sanctioned call site, as inextras/meilisearch/crates/meilisearch-types/src/archive_ext.rs. - Pin every GitHub Action to a commit SHA with a version comment, and add a
.github/dependabot.ymlwithpackage-ecosystem: "github-actions", monthly interval, andcooldown.default-days: 7, copyingextras/meilisearch/.github/dependabot.yml. - Add
merge_group:to the CI trigger list and enable the GitHub merge queue, with the expensive jobs skipped inside the queue viaif: github.event_name != 'merge_group'as inextras/meilisearch/.github/workflows/test-suite.yml. - Declarative end-to-end tests of the CLI surface. Since every quinjet operation is a
subcommand, encode scenario files (JSON: fixture-repo setup, subcommand invocations,
expected output) executed by a test binary, mirroring
extras/meilisearch/workloads/testspluscargo xtask test. For a single crate this can be one integration test that walks atests/scenarios/*.jsonglob. - Typestate fixtures in integration tests. Use uninhabited marker enums and
PhantomData<State>(Server<Owned>versusServer<Shared>inextras/meilisearch/crates/meilisearch/tests/common/server.rs) for shared read-only fixture git repositories versus per-test mutable clones, so a test cannot mutate the shared fixture by construction. - Profile tuning in
Cargo.toml:codegen-units = 1under[profile.release], a[profile.release-with-debug]withinherits = "release"anddebug = truefor profiling sessions, and[profile.dev.package.<dep>] opt-level = 3for hot dependencies so debug-mode tests stay fast, followingextras/meilisearch/Cargo.toml. - A nightly flaky-test hunt: a scheduled workflow installing
cargo-flakyand runningcargo flaky -i 100 --release, as inextras/meilisearch/.github/workflows/flaky-tests.yml. TUI event-loop tests are prime flake candidates. - Release gate script: a
check-release.shthat verifies the pushed tag equals the version in bothCargo.tomlandCargo.lockbefore any artifact job runs, plus a scheduled dry run of the full binary build matrix so releases cannot fail on release day (extras/meilisearch/.github/workflows/publish-release-assets.yml). - Fuzz the parsers. Any quinjet input parser (refspec, filter, or keybinding syntax)
should get a committed
fuzz/directory with alibfuzzer-systarget that, likeextras/meilisearch/crates/filter-parser/fuzz/fuzz_targets/parse.rs, panics only on internal-error variants and treats user-facing parse errors as success. -
-D clippy::todoin the CI clippy invocation (cheap even on top of a strict wall, it also covers test and bench targets via--all-targets), andRUSTFLAGS: "-D warnings"at workflow env level so plain builds fail on warnings too. - Documented safe-wrapper pattern for the one dangerous call: when an operation is risky
(deleting refs, force pushes), expose it only through an extension trait like
ArchiveExt::safe_unpackand ban the raw method repo-wide viaclippy.toml. - Structured panic reporting: install a panic hook that logs
PanicHookInfothrough the tracing pipeline before the TUI teardown, and havemainwalk and log theError::source()chain on exit, as inextras/meilisearch/crates/meilisearch/src/main.rs. -
#![doc = include_str!("../README.md")]on the crate root so README examples are compile-tested, followingextras/meilisearch/crates/permissive-json-pointer/src/lib.rs.
Ruff is an extremely fast Python linter and code formatter written in Rust, and the same repository also hosts ty, Astral's Python type checker. The package description in extras/ruff/crates/ruff/Cargo.toml reads:
[package]
name = "ruff"
version = "0.16.3"
description = "An extremely fast Python linter and code formatter"Industry adopted Ruff because it replaces an entire stack of Python tools (Flake8 and its plugin ecosystem, isort, pyupgrade, Black-compatible formatting) with one native binary that is orders of magnitude faster, distributed on PyPI, and driven by a single configuration file. The repository is therefore a compiler-shaped codebase: a lexer, parser, AST, semantic model, several hundred lint rules, a formatter, an LSP server, and an incremental type checker all live here.
Measured directly from the clone:
- 51 workspace crates under extras/ruff/crates (the workspace is
members = ["crates/*"]in extras/ruff/Cargo.toml). - 1957 Rust source files, 766,844 lines of Rust in total; 766,361 of those lines are inside extras/ruff/crates.
- The two biggest crates are extras/ruff/crates/ruff_linter (199,648 lines) and extras/ruff/crates/ty_python_semantic (180,290 lines).
- 3,703 insta snapshot files (
*.snap) across 84snapshotsdirectories. - 6 libFuzzer targets in extras/ruff/fuzz/fuzz_targets.
- 20 GitHub workflow files totaling 4,393 lines in extras/ruff/.github/workflows.
extras/ruff/
|-- Cargo.toml workspace root: members, shared deps, lints, profiles
|-- Cargo.lock
|-- clippy.toml disallowed methods, doc-valid-idents
|-- rustfmt.toml edition pinning for the formatter
|-- rust-toolchain.toml pinned stable toolchain (1.97.1)
|-- _typos.toml spell-checker configuration
|-- dist-workspace.toml cargo-dist release configuration
|-- .config/nextest.toml test-runner profiles (ci profile, serial groups)
|-- .cargo/config.toml cargo aliases (cargo dev, cargo benchmark)
|-- .pre-commit-config.yaml prioritized hook pipeline
|-- crates/ 51 crates, ruff_* and ty_* prefixes
|-- fuzz/ separate cargo-fuzz workspace
|-- python/ py-fuzzer and ruff-ecosystem helper packages
|-- scripts/ release.sh, add_rule.py, PGO build, docs generators
|-- docs/ mkdocs source (linter.md, formatter.md, versioning.md)
|-- playground/ web playground built on the wasm crates
|-- changelogs/ archived changelog per minor series (0.1.x.md .. 0.15.x.md)
`-- .github/ workflows, CODEOWNERS, templates, renovate, zizmor config
The split works because every architectural layer is its own crate with an explicit
dependency direction: ruff_text_size and ruff_source_file at the bottom, then
ruff_python_ast, ruff_python_parser, ruff_python_semantic, then ruff_linter and
ruff_python_formatter, and finally the ruff CLI crate that only wires commands together.
The naming convention is documented in extras/ruff/AGENTS.md: ruff_* for linter code,
ty_* for type-checker code, with ty reusing the parser and AST crates. Crate boundaries
also drive CI: the determine_changes job in extras/ruff/.github/workflows/ci.yaml maps
directories to flags (parser, linter, formatter, ty, fuzz) and downstream jobs run only when
their layer changed.
Two details are worth copying. First, the fuzz targets live in a separate workspace
(extras/ruff/fuzz/Cargo.toml declares [workspace] members = ["."] with the comment
"Prevent this from interfering with workspaces") so nightly-only fuzz dependencies never
infect the main lockfile. Second, developer tooling is itself a crate:
extras/ruff/crates/ruff_dev is an internal CLI exposed through a cargo alias in
extras/ruff/.cargo/config.toml:
[alias]
dev = "run --package ruff_dev --bin ruff_dev"
benchmark = "bench -p ruff_benchmark --bench linter --bench formatter --"cargo dev generate-all regenerates the JSON schema, CLI help, options reference, and rules
table (see extras/ruff/crates/ruff_dev/src/generate_all.rs and its sibling modules), and CI
fails if the committed output drifts.
The root extras/ruff/Cargo.toml is the single source of truth for metadata, versions, and lints:
[workspace.package]
# Please update rustfmt.toml when bumping the Rust edition
edition = "2024"
rust-version = "1.95"
homepage = "https://docs.astral.sh/ruff"
license = "MIT"Notable practices:
- Every third-party dependency is declared once under
[workspace.dependencies]with an explicit version, and member crates only writeanyhow = { workspace = true }. Internal crates are also declared there with bothversionandpath, socargo publishworks for the whole graph. - 48 of the 51 crates end their manifest with
[lints] workspace = true(for example extras/ruff/crates/ruff/Cargo.toml), so lint policy lives in exactly one place. - MSRV is separated from the development toolchain:
rust-version = "1.95"in the workspace manifest, while extras/ruff/rust-toolchain.toml pinschannel = "1.97.1". CONTRIBUTING documents the policy as "latest minus two" (extras/ruff/CONTRIBUTING.md, "Upgrading Rust" section), and CI reads the MSRV out of the manifest with a TOML action rather than hardcoding it. - Feature flags gate integrations, not behavior: the linter exposes
clap,serde,schemars, and atest-rulesfeature that the CLI crate enables only in[dev-dependencies](extras/ruff/crates/ruff/Cargo.toml: "Enable test rules during development"). - Allocators are selected per platform with
[target.'cfg(...)'.dependencies]:tikv-jemallocatoron 64-bit Unix,mimallocon Windows (extras/ruff/crates/ruff/Cargo.toml). - Profiles are tuned deliberately.
releaseuseslto = "fat"withcodegen-units = 16, but hot crates get their own override:
[profile.release.package.ruff_python_parser]
codegen-units = 1There is a documented profiling profile (release minus fat LTO, with full debug info)
for benchmarks, a minimal-size profile (opt-level = "z"), a fast-test profile, and
[profile.dev.package.insta] bumps snapshot-diffing dependencies to opt-level = 3 so
tests stay fast in dev builds.
- Unused-dependency policy is machine-checked:
[workspace.metadata.cargo-shear]lists the few intentional exceptions, and CI runscargo shear --deny-warnings. - The CLI library sets
[lib] doctest = falseto keep the test matrix intentional.
extras/ruff/rustfmt.toml is deliberately tiny:
edition = "2024"
style_edition = "2024"The philosophy is default rustfmt, no bikeshedding; the only reason the file exists is to
pin the edition for editors that run rustfmt standalone, and the workspace manifest carries
a reminder comment to keep the two in sync. Formatting of everything else is layered in
extras/ruff/.pre-commit-config.yaml, which runs hooks in explicit priority order:
rustfmt for Rust, prettier for YAML, mdformat plus markdownlint-fix for Markdown
(priority 1 so it runs after mdformat), Ruff itself for the repository's own Python
(ruff-format, ruff-check --fix), and uv-lock to keep the Python lockfile fresh. Every
hook revision is pinned to a full commit SHA with a # frozen: vX.Y.Z comment.
extras/ruff/.editorconfig sets the baseline for all editors: UTF-8, LF, final newline, 2-space indent, with overrides:
[*.{rs,py,pyi,toml}]
indent_size = 4
[*.snap]
trim_trailing_whitespace = falseThe .snap override matters: snapshot files must be byte-exact, so editors must not "fix"
them. Spelling is enforced with typos via extras/ruff/_typos.toml, which shows how to make a
spell checker viable at scale: extend-exclude for vendored code and snapshots,
extend-words for legitimate oddities (arange = "arange" # e.g. numpy.arange), and a
regex line-escape (spellchecker:disable-line).
Clippy policy lives in [workspace.lints] in extras/ruff/Cargo.toml and is enforced in CI
as errors: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
(extras/ruff/.github/workflows/ci.yaml, plus a second wasm-target clippy run). The shape of
the policy:
[workspace.lints.rust]
unsafe_code = "warn"
unreachable_pub = "warn"
unexpected_cfgs = { level = "warn", check-cfg = [
"cfg(fuzzing)",
"cfg(codspeed)",
] }
[workspace.lints.clippy]
pedantic = { level = "warn", priority = -2 }Pedantic is on wholesale at low priority, then individual pedantic lints are allowed back
with one line each (too_many_lines, similar_names, module_name_repetitions, and so
on), several with a rationale comment, for example:
needless_continue = "allow" # An explicit continue can be more readable, especially if the alternative is an empty block.On top of that, a curated set of restriction and nursery lints is opted in:
iter_over_hash_type, print_stdout, print_stderr, dbg_macro, exit, get_unwrap,
rc_buffer, rc_mutex, rest_pat_in_fully_bound_structs, redundant_clone,
debug_assert_with_mut_call, unused_peekable. Because print_stdout is warned
workspace-wide, the crates that legitimately print (the CLIs) opt out at the crate root:
extras/ruff/crates/ruff/src/lib.rs opens with #![allow(clippy::print_stdout)] and
extras/ruff/crates/ruff_dev/src/main.rs with
#![allow(clippy::print_stdout, clippy::print_stderr)]. Everywhere else, printing is a
lint error, which forces output through the Printer abstraction.
extras/ruff/clippy.toml carries the semantic configuration: doc-valid-idents so rustdoc
prose can say "NumPy" without a lint, ignore-interior-mutability with per-type
justification comments, and, most interestingly, disallowed-methods used as an
architectural fence:
disallowed-methods = [
{ path = "std::env::var", reason = "Use System::env_var instead in ty crates" },
{ path = "std::fs::read_to_string", reason = "Use System::read_to_string instead in ty crates" },
{ path = "std::path::Path::exists", reason = "Use System::path_exists instead in ty crates" },
]This bans direct filesystem and environment access so all IO goes through the System
abstraction that makes ty testable against an in-memory filesystem. The workspace table
sets disallowed_methods = "allow" with the comment "Enabled at the crate level", so only
the crates that opted in pay the cost. Suppressions prefer #[expect] with reasons, for
example extras/ruff/crates/ruff_python_parser/src/parser/mod.rs:
#[expect(clippy::inline_always, reason = "reduces list-parser branch misses")]There are 355 #[expect(...)] attributes in the tree, each self-expiring if the lint stops
firing. Custom check infrastructure goes beyond clippy: cargo shear for unused deps,
shellcheck over all *.sh in CI, actionlint plus zizmor for the workflows themselves, and
the scripts CI job runs the code generators and fails on git status --porcelain drift.
extras/ruff/.github/workflows/ci.yaml (1,392 lines) is the core pipeline. Structure:
- Top of file:
permissions: {}(zero default token permissions; jobs opt in, for example the CodSpeed jobs requestid-token: writefor OIDC), a concurrency group that cancels superseded runs, anddefaults: run: shell: bash. -
determine_changescomputes a merge base, then runs a series ofgit diff --quietchecks that emit boolean outputs (parser,linter,formatter,ty,fuzz,playground,benchmarks,release,code). Nearly every later job is gated on one of these flags, so a docs-only PR compiles nothing. - Test jobs:
cargo-test-linux(nextest pluscargo insta test --unreferenced reject, so orphaned snapshots fail CI),cargo-test-linux-releaseunder theprofilingprofile,cargo-test-otherwith a matrix over Windows and macOS runners,cargo-test-wasmviawasm-pack test --nodefor both wasm crates, andcargo-build-msrv, which readsworkspace.package.rust-versionfrom Cargo.toml withSebRollen/toml-actionand builds the test suite on that toolchain. - Docs discipline inside CI:
cargo doc --all --no-depswithRUSTDOCFLAGS: "-D warnings", plus a second--document-private-itemspass over an allowlist of already-clean crates "to prevent regression" (extras/ruff/.github/workflows/ci.yaml around line 400). - Behavioral regression jobs unique to this project:
ecosystembuilds the baseline and PR binaries and diffsruff check/ruff formatoutput across a corpus of real repositories, uploading a markdown report artifact;fuzz-tybuilds the merge-base and PRtybinaries and fuzzes for new panics only;check-formatter-instability-and-black-similarityruns scripts/formatter_ecosystem_checks.sh;check-ruff-lspruns the downstream ruff-lsp test suite against the PR binary. - Benchmarks run on every relevant PR through CodSpeed (instrumented and walltime modes), with build and run split into separate jobs that pass the benchmark binary as an artifact.
- Caching is
Swatinem/rust-cacheeverywhere withsave-if: ${{ github.ref == 'refs/heads/main' }}, so PRs read the cache but only main writes it, plusshared-key: ruff-linux-debugso sibling jobs share one cache. - Every third-party action is pinned to a full commit SHA with a version comment, every
checkout sets
persist-credentials: false, and jobs carrytimeout-minutes. - The required-checks pattern: a final
required-checks-passedjob withif: always()needs the core jobs and fails if any dependency result is neither success nor skipped, so branch protection points at one check while path-filtered jobs stay skippable.
Security hardening is itself linted: zizmor runs as a pre-commit hook with exceptions
tracked in extras/ruff/.github/zizmor.yml, actionlint runs with shellcheck integration
(extras/ruff/.github/actionlint.yaml whitelists the custom Depot and Namespace runner
labels), and check-jsonschema validates workflow syntax. Renovate
(extras/ruff/.github/renovate.json5) updates actions, cargo, pre-commit hooks, npm, and
Python deps on a weekly schedule. Scheduled workflows do the long-tail work:
daily_fuzz.yaml fuzzes the parser with 1,000 random seeds every night and auto-files an
issue on failure; sync_typeshed.yaml vendors typeshed weekly; typing_conformance.yaml and
the ty-ecosystem workflows track type-checker behavior; memory_report.yaml posts memory
profiles on PRs touching ty internals.
The test strategy is snapshot-first, at three levels:
-
Rule and unit tests live inside each crate (
#[cfg(test)] mod tests), and lint rules assert their diagnostics with insta snapshots; the 3,703.snapfiles undersnapshots/directories sit next to the code they verify, for example extras/ruff/crates/ruff_linter/src/rules/*/snapshots. -
CLI integration tests in extras/ruff/crates/ruff/tests use
insta_cmdto snapshot the full process contract. From extras/ruff/crates/ruff/tests/cli/lint.rs:assert_cmd_snapshot!(test.check_command() .arg("--config") .arg("ruff.toml") .args(["--stdin-filename", "test.py"]) .arg("-") .pass_stdin(r#"a = "abcba".strip("aba")"#), @" success: false exit_code: 1 ----- stdout ----- test.py:1:5: Q000 [*] Double quotes found but single quotes preferred
One assertion pins exit code, stdout, and stderr at once. The shared fixture in extras/ruff/crates/ruff/tests/cli/main.rs (
CliTest) creates a temp project dir, canonicalizes it (withdunceto avoid Windows UNC paths), and installs insta filters that rewrite the temp path to[TMP]/so snapshots are cross-platform stable. -
ty's type-inference tests are Markdown files: any fenced
pyblock with# revealed: ...comments is executed as a test by the framework in extras/ruff/crates/ty_test (documented in extras/ruff/crates/ty_test/README.md, "Any Markdown file can be a test suite"). Tests are literate specifications, which is why thousands of behaviors are covered without Rust boilerplate.
Supporting infrastructure: extras/ruff/.config/nextest.toml defines a ci profile
(failure-output = "immediate-final", fail-fast = false, a 60-second
terminate-after as a deadlock stopgap) and a serial test group pinning the file-watcher
tests to one thread. Property-style testing exists via quickcheck (declared in the
workspace deps) and six libFuzzer targets in extras/ruff/fuzz/fuzz_targets
(ruff_parse_idempotency.rs, ruff_formatter_validity.rs, ty_check_invalid_syntax.rs,
and friends), plus the Python-based differential fuzzer in python/py-fuzzer that CI runs on
parser changes. Benchmarks are a dedicated crate, extras/ruff/crates/ruff_benchmark, with
criterion/divan benches per subsystem (benches/linter.rs, parser.rs, formatter.rs,
ty.rs) wired to CodSpeed for continuous regression tracking. Test-only rules ship behind
the linter's test-rules cargo feature so the CLI test suite can trigger every fix
pathway.
The pattern is thiserror (or hand-written std::error::Error impls) in library crates,
anyhow only at the binary boundary. extras/ruff/crates/ruff_python_parser/src/error.rs
defines a structured ParseError { error: ParseErrorType, location: TextRange } with
Deref to its kind and a manual Display; a dozen crates such as
extras/ruff/crates/ty_project/src/metadata/options.rs use thiserror::Error derives.
The CLI's process contract is a dedicated enum in extras/ruff/crates/ruff/src/lib.rs:
#[derive(Copy, Clone)]
pub enum ExitStatus {
/// Linting was successful and there were no linting errors.
Success,
/// Linting was successful but there were linting errors.
Failure,
/// Linting failed.
Error,
}
impl From<ExitStatus> for ExitCode {
fn from(status: ExitStatus) -> Self {
match status {
ExitStatus::Success => ExitCode::from(0),
ExitStatus::Failure => ExitCode::from(1),
ExitStatus::Error => ExitCode::from(2),
}
}
}main (extras/ruff/crates/ruff/src/main.rs) returns ExitCode, never calls
process::exit, and its report_error handler exits 0 on BrokenPipe (crediting
ripgrep), writes ruff failed in red bold to a locked stderr with writeln!(...).ok() so
a broken stderr cannot panic, and prints the full err.chain() of causes. Panic policy is
cultural and enforced in review: extras/ruff/AGENTS.md instructs "Try hard to avoid
patterns that require panic!, unreachable!, .unwrap() or .expect(). Instead, try to
encode those constraints in the type system." Visibility discipline is mechanical:
unreachable_pub = "warn" workspace-wide plus the documented preference for narrow
visibility, with pub(crate) used pervasively (see the module list in
extras/ruff/crates/ruff/src/lib.rs where only args and resolve are pub). API design
favors small vocabulary types over primitives: TextSize/TextRange newtypes
(extras/ruff/crates/ruff_text_size), typed indexes via IndexVec (extras/ruff/crates/
ruff_index), and the Violation trait family in
extras/ruff/crates/ruff_linter/src/violation.rs, where each rule is a struct with
message(), optional fix_title(), and a FIX_AVAILABILITY associated const, letting the
framework derive docs, codes, and fix metadata per rule.
- Trait-per-rule design:
Violation: ViolationMetadata + Sizedwith an associatedconst FIX_AVAILABILITY: FixAvailabilityand a defaultinto_diagnosticimplementation (extras/ruff/crates/ruff_linter/src/violation.rs). Hundreds of rule structs implement one narrow trait, and a derive macro (ViolationMetadatain extras/ruff/crates/ruff_macros/src/violation_metadata.rs) extracts each rule's rustdoc as its user-facing explanation, so docs and behavior cannot drift apart. - Lifetime-parameterized visitors:
pub trait Visitor<'a>withvisit_stmt(&mut self, stmt: &'a Stmt)and freewalk_*functions (extras/ruff/crates/ruff_python_ast/src/ visitor.rs). Borrowing the AST for'alets rule state hold references into the tree with zero copies. - Newtypes with proc-macro leverage:
#[newtype_index](extras/ruff/crates/ruff_macros/ src/newtype_index.rs) generates dense u32-backed ID types consumed throughIndexVec/IndexSlice(extras/ruff/crates/ruff_index/src/lib.rs, "Inspired by rustc_index"), giving array indexing that is type-checked per arena. - Zero-copy string handling:
Cow<'_, str>returns from trivia utilities such aspub fn dedent(text: &str) -> Cow<'_, str>andexpand_tabs(extras/ruff/crates/ruff_python_trivia/src/textwrap.rs, whitespace.rs); 192Cow<occurrences across the crates, allocating only when a transformation actually changes the text. - Lazy interior mutability chosen per need:
Locatorwraps the source withindex: OnceCell<LineIndex>so the line index is computed only if a diagnostic needs it (extras/ruff/crates/ruff_linter/src/locator.rs), and even marks the expensive path#[deprecated(note = "This is expensive, avoid using outside of the diagnostic phase...")]so misuse is a compile-time warning. 99LazyLockuses cover static regexes and tables. - Data parallelism at the file level:
paths.par_iter().filter_map(|resolved_file| ...)in extras/ruff/crates/ruff/src/commands/check.rs runs the whole linter per file on rayon, with the cache layer usinginto_par_iterfor persistence (extras/ruff/crates/ruff/src/cache.rs); ty instead builds on salsa queries (#[salsa::tracked]throughout extras/ruff/crates/ty_python_semantic) for incremental, demand-driven computation. - Memory layout as a tested invariant:
assert_eq_size!(FormatElement, [u8; 16])and friends in extras/ruff/crates/ruff_formatter/src/format_element.rs pin the size of hot enums, so an accidental variant growth fails the build rather than slowing the printer. - Linear-type emulation with
drop_bomb::DebugDropBombin the formatter printer, the parser scratch buffer, and ty's diagnostic context (extras/ruff/crates/ruff_formatter/ src/printer/mod.rs, extras/ruff/crates/ruff_python_parser/src/parser/scratch_buffer.rs, extras/ruff/crates/ty_python_semantic/src/types/context.rs): a guard that panics in debug builds if dropped without being defused, encoding "you must finish this" in the API. - Unsafe as an audited exception:
unsafe_code = "warn"workspace-wide, upgraded to#![forbid(unsafe_code)]in leaf crates like extras/ruff/crates/ruff_text_size/src/ lib.rs, and the rare use sites carry both an#[expect]and a SAFETY comment:#[expect(unsafe_code, reason = "reconstructs a type-erased AST reference")]above a// SAFETY: The caller guarantees that pointer is readable...block in extras/ruff/crates/ruff_python_ast/src/generated.rs. - Platform cfg handled once, at the allocator and linker level: the cascading
#[cfg(all(not(target_os = "windows"), ..., any(target_arch = "x86_64", ...)))]global-allocator selection in extras/ruff/crates/ruff/src/main.rs, plus static CRT linking for MSVC viarustflags = ["-C", "target-feature=+crt-static"]in extras/ruff/.cargo/config.toml with an issue link explaining why. - Bitflags for option sets crossing function boundaries:
PrinterFlagswith documented bits (extras/ruff/crates/ruff/src/printer.rs), and serde-aware view structs likeExpandedStatistics<'a>borrowing&'a strfields to serialize without cloning. - Codegen where Rust macros would obscure: the entire AST (
generated.rs) is produced by extras/ruff/crates/ruff_python_ast/generate.py from a declarative extras/ruff/crates/ruff_python_ast/ast.toml, and CI regenerates it and diffs (test -z "$(git status --porcelain)"in thescriptsjob of ci.yaml), keeping the generator honest.
- Crate-level
//!docs state intent and stability up front: extras/ruff/crates/ruff_linter/src/lib.rs opens with "This is the library for the [Ruff] Python linter. The API is currently completely unstable". extras/ruff/crates/ruff_text_size/src/lib.rs even documents when not to use the crate. - Rule docs are the user docs: each rule struct's rustdoc ("What it does / Why is this
bad?" sections, visible throughout extras/ruff/crates/ruff_linter/src/rules) is
extracted by the
ViolationMetadataderive and rendered into the docs site by extras/ruff/crates/ruff_dev/src/generate_docs.rs. One source, two audiences. - The user site is mkdocs (extras/ruff/mkdocs.yml plus extras/ruff/docs), built with
mkdocs build --strictin CI; generated pages come fromcargo devgenerators and scripts/generate_mkdocs.py, and scripts/check_docs_formatted.py lints the code blocks in the docs themselves. - extras/ruff/CONTRIBUTING.md is 1,128 lines and unusually operational: project layout, example rule-addition walkthroughs, the full release checklist, MSRV policy, and a long "Benchmarking and Profiling" chapter.
- Doc quality is CI-enforced (
RUSTDOCFLAGS: "-D warnings"oncargo doc, per section 6), so broken intra-doc links cannot land. - Issue templates are structured YAML forms (extras/ruff/.github/ISSUE_TEMPLATE/
1_bug_report.yaml, 2_rule_request.yaml, 3_question.yaml), and the PR template asks for a
Summary and a Test Plan (extras/ruff/.github/PULL_REQUEST_TEMPLATE.md). CODEOWNERS routes
crates to maintainers (
/crates/ruff_python_formatter/ @MichaReiserand team-based*_notifiedgroups for ty crates). - extras/ruff/.git-blame-ignore-revs keeps mass reformatting commits out of blame.
Versioning is documented in extras/ruff/docs/versioning.md: pre-1.0 semver where minor
means breaking and patch means fixes, with an explicit list of what counts as breaking for
the linter, formatter, and server. Internal crates are published as 0.0.x with "no
stability guarantees" (visible in the workspace dependency table: ruff_cache = { version = "0.0.9", ... } next to ruff = { version = "0.16.3", ... }).
Changelog discipline: a curated extras/ruff/CHANGELOG.md for the current series, archived
per-minor files in extras/ruff/changelogs (0.1.x.md through 0.15.x.md), and breaking
changes duplicated into extras/ruff/BREAKING_CHANGES.md. The release itself is
scripts/release.sh plus the rooster changelog generator, then human editorializing
(extras/ruff/CONTRIBUTING.md, "Release Process").
Distribution is cargo-dist, configured in extras/ruff/dist-workspace.toml: 18 prebuilt
targets (including musl, armv7, s390x, riscv64), shell and PowerShell installers,
dispatch-releases = true (releases are triggered by workflow dispatch, and the git tag is
created only after wheels are on PyPI, per the CONTRIBUTING checklist),
github-attestations = true for artifact provenance, and even the actions used inside the
generated workflow pinned by commit under [dist.github-action-commits]. The generated
extras/ruff/.github/workflows/release.yml adds a human gate: a release-gate job bound to
a GitHub environment that "requires a 2-factor approval, i.e., the workflow must be
approved by another team member". Local artifact jobs are delegated to
build-binaries.yml (maturin wheels for every platform, with a PGO pass on x86_64 via
scripts/build_ruff_pgo.py and -Cprofile-use flags), build-docker.yml, and
build-wasm.yml; publish jobs push to PyPI via uv publish under an environment with
id-token: write (trusted publishing, no long-lived secrets,
extras/ruff/.github/workflows/publish-pypi.yml), to crates.io, npm, and a release mirror.
As a CLI, ruff ships shell completions through a subcommand rather than packaged files:
GenerateShellCompletion { shell: clap_complete_command::Shell } in
extras/ruff/crates/ruff/src/args.rs.
quinjet already has the strict-clippy, rustfmt, cargo-deny, taplo, typos, coverage, miri, and mutants story. What ruff adds on top, with mechanisms:
- Snapshot-test the whole CLI contract. Add
instaandinsta-cmdas dev-dependencies and writeassert_cmd_snapshot!tests that pin exit code, stdout, and stderr per subcommand, with aCliTest-style fixture (tempdir plussettings.add_filter(tempdir_regex, "[TMP]/")) exactly as in extras/ruff/crates/ruff/tests/cli/main.rs; for a Git TUI, the fixture would alsogit initand seed commits. Runcargo insta test --unreferenced rejectin CI so stale snapshots fail. - Make the exit-code contract a type. quinjet's clap subcommands should return an
ExitStatusenum withimpl From<ExitStatus> for ExitCode(pattern from extras/ruff/crates/ruff/src/lib.rs), andmainshould adopt ruff'sreport_error: exit 0 onErrorKind::BrokenPipe, print theanyhowchain to a locked stderr withwriteln!(...).ok(). - Adopt zizmor and actionlint for the workflows. Both run as pre-commit hooks in
extras/ruff/.pre-commit-config.yaml with pinned SHAs; quinjet can run them in the
existing Makefile lint target (
zizmor .github/workflows,actionlint) and set workflow-levelpermissions: {}pluspersist-credentials: falseon every checkout. - Pin every GitHub action to a full commit SHA with a
# vX.Y.Zcomment and let Renovate bump them (extras/ruff/.github/renovate.json5,enabledManagersincludinggithub-actions); this is strictly stronger than tag pinning. - Add the
required-checks-passedaggregation job (if: always()plus a jq check overtoJSON(needs), extras/ruff/.github/workflows/ci.yaml lines 1368-1392) so branch protection needs exactly one context even as jobs are added or skipped. - Verify MSRV mechanically: keep
rust-versionin Cargo.toml, read it in CI withSebRollen/toml-actiononworkspace.package.rust-version(single-crate:package. rust-version), and runcargo +$MSRV test --no-runas ruff'scargo-build-msrvjob does. - Use
Swatinem/rust-cachewithsave-if: github.ref == 'refs/heads/main'and ashared-keyper platform-profile pair, so PR runs never poison the cache. - Add
cargo-shear(cargo shear --deny-warnings, exceptions under[workspace.metadata.cargo-shear]) to catch unused dependencies; it complements cargo-deny, which does not check usage. - Turn architectural rules into
disallowed-methodsentries in clippy.toml withreasonstrings, as ruff does for itsSystemabstraction. For quinjet: banstd::process::exitoutside main, or ban rawcrossterm::execute!outside the terminal module, so the TUI/CLI layering is machine-enforced. - Keep docs from rotting with
cargo doc --no-depsunderRUSTDOCFLAGS="-D warnings", plus a--document-private-itemspass once the crate is clean (ci.yaml around line 400); add both as Makefile targets and CI steps. - Adopt nextest with a
ciprofile in.config/nextest.toml:fail-fast = false,failure-output = "immediate-final",slow-timeout = { period = "1s", terminate-after = 60 }to convert deadlocks into failures, and aserialtest group for tests that touch a shared Git repo or the terminal. - Ship with cargo-dist: a
dist-workspace.tomlgives quinjet multi-target archives, shell/PowerShell installers, GitHub attestations, and a generated release.yml;dispatch-releases = trueplus an approval-gatedrelease-gateenvironment copies ruff's two-person release control. - Expose completions as a subcommand via the
clap_complete_commandcrate (GenerateShellCompletion { shell: clap_complete_command::Shell }in extras/ruff/crates/ruff/src/args.rs), which quinjet's command-layer design can add as one more subcommand. - Consider a tiny differential-fuzz loop for the CLI surface: ruff's daily_fuzz.yaml
pattern (scheduled workflow, random seeds, auto-file an issue on failure) applied to
quinjet could run random command sequences against a scratch repo nightly and compare
--porcelain-style output between the PR and main binaries, like thefuzz-tyjob. - Add size regression guards for hot types with
static_assertions::assert_eq_size!in a#[cfg(test)] mod sizes, as extras/ruff/crates/ruff_formatter/src/format_element.rs does; for a TUI, event and draw-command enums are the candidates.
Bevy is a data-driven game engine and application framework built around an
archetypal entity component system (ECS). The root manifest describes it
plainly in extras/bevy/Cargo.toml:
[package]
name = "bevy"
version = "0.20.0-dev"
edition = "2024"
description = "A refreshingly simple data-driven game engine and app framework"
rust-version = "1.96.0"Industry and hobbyists use it because the ECS core (bevy_ecs) is usable as a
standalone library, the engine is fully modular (every subsystem is a plugin),
and the project maintains one of the most disciplined open-source Rust
workflows in existence. It is a library, not a CLI, so its "public surface" is
an enormous API plus 430 runnable examples.
Measurable scale from the clone:
- 59 published crates under
extras/bevy/crates/(verified withls crates | wc -l). - 1846
.rsfiles totaling roughly 625,700 lines; thecrates/tree alone is roughly 513,900 lines. - 430
[[example]]entries declared inextras/bevy/Cargo.toml. - Workspace members beyond
crates/*:benches,tools/*,errors, threecompile_failcrates, and several example sub-workspaces (mobile,no_std, large scenes), all listed in the[workspace] membersarray ofextras/bevy/Cargo.toml.
Top level of extras/bevy/:
bevy/
|-- Cargo.toml root package "bevy" + workspace definition (5673 lines)
|-- clippy.toml clippy configuration shared by every crate
|-- rustfmt.toml formatting policy
|-- deny.toml cargo-deny: advisories, licenses, bans, sources
|-- typos.toml spell-check configuration
|-- src/lib.rs thin facade re-exporting bevy_internal
|-- crates/ 59 bevy_* crates, each independently publishable
|-- examples/ 430 examples, organized by topic (2d, 3d, ecs, ui, ...)
|-- benches/ criterion benchmarks as a dedicated workspace member
|-- tests/ cross-crate integration tests against the `bevy` facade
|-- tests-integration/ consumer-style crates excluded from the workspace
|-- tools/ internal tooling: ci runner, compile_fail_utils, ...
|-- errors/ a crate whose docs are the runtime error code catalog
|-- docs/ contributor docs: linters.md, profiling.md, debugging.md
|-- docs-rs/ rustdoc HTML extensions (trait tags on docs.rs)
|-- docs-template/ templates for generated docs pages
|-- _release-content/ draft migration guides and release notes for next release
`-- .github/ 13 workflows, composite actions, templates, linter config
Why the split works: every subsystem is a crate with its own feature set and
MSRV, so downstream users can depend on bevy_ecs alone, while the root
bevy package is a pure facade. The facade is even split once more:
extras/bevy/src/lib.rs re-exports crates/bevy_internal, which exists, per
its own docs, "to enable simple dynamic linking for Bevy"
(extras/bevy/crates/bevy_internal/src/lib.rs). Tooling lives in-workspace
(tools/ci) so it is versioned, reviewed, and compiled by the same toolchain
as the engine.
The root extras/bevy/Cargo.toml is 5673 lines and is a study in itself.
Workspace definition uses resolver 3 and globs plus explicit exceptions:
[workspace]
resolver = "3"
members = [
# All of Bevy's official crates are within the `crates` folder!
"crates/*",
"crates/bevy_derive/compile_fail",
...
"benches",
# Internal tools that are not published.
"tools/*",
"errors",
]
exclude = [
# Integration tests are not part of the workspace
"tests-integration",
]Notable, and unusual, choices:
- There is no
[workspace.dependencies]table at all (grep -c "workspace.dependencies" Cargo.tomlreturns 0). Every crate declares its own versioned dependencies, because each crate is published independently and must stand alone on crates.io. - There is a
[workspace.lints]table, and each member opts in with[lints] workspace = true(for exampleextras/bevy/crates/bevy_ecs/Cargo.tomlline 154). The root package then duplicates the whole lint table because cargo cannot override workspace lints per package. The manifest documents this honestly:
# Unfortunately, cargo does not currently support overriding workspace lints
# inside a particular crate. See https://github.com/rust-lang/cargo/issues/13157
#
# We require an override for cases like `std_instead_of_core`, which are intended
# for the library contributors and not for how users should consume Bevy.- MSRV is set per crate: the root declares
rust-version = "1.96.0"whileextras/bevy/crates/bevy_ecs/Cargo.tomldeclaresrust-version = "1.95.0", so the standalone ECS supports an older compiler than the full engine. - Feature flags are a designed vocabulary, not an accident. Features in the
root manifest carry structured comment prefixes (
# PROFILE:and# COLLECTION:) that a tool parses into documentation:
# PROFILE: The default 2D Bevy experience. This includes the core Bevy framework, 2D functionality, scenes and picking.
2d = ["default_app", "default_platform", "2d_bevy_render", "scene", "picking"]In extras/bevy/crates/bevy_ecs/Cargo.toml, features use ## doc comments
and dep: syntax (serialize = ["dep:serde", "bevy_platform/serialize", "indexmap/serde"]).
- Custom profiles exist for real use cases in
extras/bevy/Cargo.toml:
[profile.wasm-release]
inherits = "release"
opt-level = "z"
lto = "fat"
codegen-units = 1
[profile.stress-test]
inherits = "release"
lto = "fat"
panic = "abort"- Each of the 430 examples has a
[package.metadata.example.<name>]block with name, description, and category; CI fails if an example lacks metadata (section 6). -
extras/bevy/benches/Cargo.tomlsetsautobenches = falseand registers each benchmark target manually, so benchmark discovery is explicit.
extras/bevy/rustfmt.toml is deliberately small:
use_field_init_shorthand = true
newline_style = "Unix"
style_edition = "2021"
# The following lines may be uncommented on nightly Rust.
# Once these features have stabilized, they should be added to the always-enabled options above.
# unstable_features = true
# imports_granularity = "Crate"
# normalize_comments = trueSetting by setting: use_field_init_shorthand rewrites Foo { x: x } to
Foo { x }; newline_style = "Unix" pins LF endings across Windows
contributors; style_edition = "2021" pins formatting behavior independently
of the crate edition (the code is edition 2024) so a toolchain bump cannot
reformat the tree. The commented block is a parked wishlist of nightly-only
options, with an explicit note that two options ("wrap_comments",
"comment_width") are avoided because they "seem poorly implemented and cause
churn". There is no .editorconfig in the repository root.
Non-Rust formatting is enforced in CI rather than by local config: TOML by
taplo (taplo fmt --check --diff in the toml job of
extras/bevy/.github/workflows/ci.yml), Markdown by super-linter's
markdownlint with config at extras/bevy/.github/linters/.markdown-lint.yml
(line length rule MD013 disabled, details/summary HTML allowed), and
spelling by typos configured in extras/bevy/typos.toml, which shows how to
keep a spell checker useful in a technical codebase:
[default.extend-words]
LOD = "LOD" # Level of detail
mis = "mis" # mis - multiple importance samplingLint policy lives in three layers.
Layer 1: [workspace.lints] in extras/bevy/Cargo.toml. The philosophy is a
curated warn-list rather than blanket pedantic, combined with -D warnings
in CI so every warn is effectively deny:
[workspace.lints.clippy]
doc_markdown = "warn"
undocumented_unsafe_blocks = "warn"
print_stdout = "warn"
print_stderr = "warn"
ptr_as_ptr = "warn"
alloc_instead_of_core = "warn"
allow_attributes = "warn"
allow_attributes_without_reason = "warn"
[workspace.lints.rust]
missing_docs = "warn"
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "warn"
unused_qualifications = "warn"Two rules stand out. unsafe_code = "deny" at the workspace level forces any
crate that genuinely needs unsafe to opt back in loudly at the crate root, for
example extras/bevy/crates/bevy_ecs/src/lib.rs:
#![expect(unsafe_code, reason = "Unsafe code is used to improve performance.")]And allow_attributes_without_reason = "warn" means every #[allow] or
#[expect] in half a million lines must carry a written justification.
Layer 2: extras/bevy/clippy.toml configures lint behavior. It enables doc
linting of private items (check-private-items = true), teaches doc_markdown
project vocabulary (doc-valid-idents = ["glTF", "VSync", ...]), enforces
brace style for a specific macro (standard-macro-braces = [{ name = "children", brace = "[" }]), and, most distinctively, uses
disallowed-methods to ban the entire f32 transcendental surface so that
math is deterministic across platforms:
disallowed-methods = [
{ path = "f32::powi", reason = "use bevy_math::ops::FloatPow::squared, bevy_math::ops::FloatPow::cubed, or bevy_math::ops::powf instead for libm determinism" },
{ path = "f32::sin", reason = "use bevy_math::ops::sin instead for libm determinism" },
...
]This is clippy configuration used as API governance: the lint config funnels every contributor to the project's own wrapper module.
Layer 3: custom check infrastructure. extras/bevy/tools/ci is a workspace
crate (argh + xshell) that encodes every CI command in Rust;
extras/bevy/tools/ci/src/commands/clippy.rs runs:
cmd!(sh, "cargo clippy --workspace --all-targets --all-features {jobs...} -- -Dwarnings")extras/bevy/deny.toml extends linting into the dependency graph: a license
allowlist with per-crate exceptions (all symphonia crates for MPL-2.0),
wildcards = "deny", unknown-registry = "deny", pinned single-version
requirements for high-blast-radius crates (ahash, glam,
raw-window-handle), and even a per-feature ban:
# thiserror is the preferred way to derive error types
[[bans.features]]
crate = "derive_more"
deny = ["error"]There are 13 workflows in extras/bevy/.github/workflows/, 2247 lines of YAML
total. Highlights per file:
-
ci.yml(600 lines, 18 jobs): triggers onmerge_group,pull_request, and pushes torelease-*branches, meaning the project uses the GitHub merge queue as the gate to main. Global hardening at the top:
permissions:
contents: read
env:
CARGO_INCREMENTAL: 0
CARGO_PROFILE_TEST_DEBUG: 0
CARGO_PROFILE_DEV_DEBUG: 0
RUSTFLAGS: "-D warnings"
concurrency:
group: ${{github.workflow}}-${{github.ref}}
cancel-in-progress: ${{github.event_name == 'pull_request'}}Jobs: build (tests on a 3-OS matrix: windows, ubuntu, macos), ci
(fmt + clippy via cargo run -p ci -- lints), miri (cargo miri test -p bevy_ecs with RUSTFLAGS: -Zrandomize-layout and
MIRIFLAGS: -Zmiri-disable-isolation), four check-compiles* jobs covering
no_std and portable-atomic targets, build-wasm and build-wasm-atomics,
markdownlint, toml (taplo), typos, check-doc, two
check-missing-*-in-docs jobs that regenerate templated docs and fail on
git diff --quiet, msrv (extracts the MSRV from cargo metadata with jq,
installs exactly that toolchain, runs cargo check),
check-bevy-internal-imports (a bash loop failing if any example imports a
bevy_* internal crate directly), and check-release-content.
- Every job sets
timeout-minutes, every checkout setspersist-credentials: false, and every third-party action is pinned to a full commit SHA with a version comment, for example:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0- Caching is asymmetric and clever: PR jobs use
actions/cache/restoreonly (read-only), whileupdate-caches.ymlrebuilds caches on pushes to main and on a nightly cron for a matrix of OS x toolchain (stable, nightly, MSRV) x target (including wasm). PRs therefore never pollute or thrash the cache. -
dependencies.ymlruns the fourcargo deny checksubcommands, path filtered to**/Cargo.tomlanddeny.tomlchanges. -
security-static-analysis.ymlruns CodeQL for bothrustandactionslanguages, plus zizmor (a GitHub Actions security scanner) uploading SARIF. -
example-run.ymlruns real examples on macOS Metal, Linux (viaxvfb-run), and Windows DX12, driven by RON config files inextras/bevy/.github/example-run/, taking screenshots and uploading Chrome trace artifacts.send-screenshots-to-pixeleagle.ymlpushes those screenshots to a visual regression service. - Fork safety pattern: workflows that need write permissions
(
ci-comment-failures.yml,welcome.yml,action-on-PR-labeled.yml) start with the comment "This workflow has write permissions on the repo. It must not checkout a PR and run untrusted code!" and consume artifacts from the untrustedCIrun viaworkflow_runinstead of executing PR code. -
action-on-PR-labeled.ymldiffs_release-content/migration-guideswhen a maintainer applies theM-Migration-Guidelabel and posts an instructional comment if the PR did not add a guide, automating changelog discipline. -
extras/bevy/.github/dependabot.ymlgroups related ecosystems (wgpuandnagaupdate together,accesskit*together), applies acooldown: default-days: 7, and labels PRsC-Dependencies.
Testing is layered by purpose:
- Unit tests live inline in each crate (
#[cfg(test)]modules acrossextras/bevy/crates/*/src). The main CI test command inextras/bevy/tools/ci/src/commands/test.rsrunscargo test --workspace --lib --bins --tests --features bevy_ecs/track_locationand a second pass with--benches"in order to verify that they behave correctly and do not panic". - Facade-level integration tests live in
extras/bevy/tests/, and two of them are executable documentation:tests/how_to_test_apps.rsandtests/how_to_test_systems.rsdemonstrate headless testing by swappingDefaultPluginsforMinimalPluginsand injecting fake input resources (app.insert_resource(ButtonInput::<KeyCode>::default())). - Consumer tests live outside the workspace:
extras/bevy/tests-integration/is explicitly excluded from[workspace]so its crates resolvebevythe way a real user would.tests-integration/simple-ecs-test/Cargo.tomleven explains why it depends on bevy twice: "We depend on bevy in both normal and dev dependencies to verify that the proc macros still work." - Compile-fail (UI) tests:
crates/bevy_derive/compile_fail,crates/bevy_ecs/compile_fail, andcrates/bevy_reflect/compile_failare dedicated crates withharness = falsetest targets, built on the shared helperextras/bevy/tools/compile_fail_utils/src/lib.rs, which wraps theui_testcrate and supports snapshot blessing via aBLESSenvironment variable. This pins diagnostic quality: an error message regression fails CI. - Miri: the
mirijob inci.ymlruns the wholebevy_ecstest suite under the interpreter with randomized layout, which is how a codebase with 1766// SAFETY:comments inbevy_ecsalone keeps its unsafe honest. - Benchmarks:
extras/bevy/benches/is a criterion workspace member with abench!macro inbenches/src/lib.rsthat derives benchmark names frommodule_path!()so names never drift from file locations. - End-to-end: since the "product" is a rendering engine, e2e testing is the
example-run.ymlworkflow plus thebevy_ci_testingcargo feature. CI setsCI_TESTING_CONFIG=$examplepointing at a RON file from.github/example-run/(for exampletestbed_2d.ron), runs the example for a fixed number of frames, captures screenshots, and compares them via the Pixel Eagle visual regression service. Application-level snapshot testing, implemented as a first-class engine feature.
- Library errors are
thiserrorenums throughout (thiserror = { version = "2", default-features = false }inextras/bevy/crates/bevy_ecs/Cargo.toml), anddeny.tomlstructurally bans the competingderive_moreerrorfeature so the choice cannot erode. - The catch-all type is
BevyErrorinextras/bevy/crates/bevy_ecs/src/error/bevy_error.rs: aBox<InnerBevyError>(one pointer wide on the happy path) with a blanketFrom<E: Error>, opt-in backtrace capture behind abacktracefeature, aSeverityadvisory level, and acontext()extension in the anyhow style. Fallible systems returnResult<(), BevyError>and a configurableFallbackErrorHandlerresource decides whether to log or panic. - Runtime panics have a documented catalog:
extras/bevy/errors/src/lib.rsdeclares one unit struct per error code and attaches the prose with#[doc = include_str!("../B0001.md")], and the manifest comment in the workspace explains why it is a crate: "This is a crate so we can automatically check all of the code blocks." - Panic policy is tiered: public APIs return
Result; internal invariants usedebug_assert-style checking via theDebugCheckedUnwraptrait (extras/bevy/crates/bevy_ecs/src/query/mod.rs), which panics in debug builds and compiles tounwrap_uncheckedin release builds. - Builder patterns are runtime complements to type-level APIs:
extras/bevy/crates/bevy_ecs/src/query/builder.rsdefinesQueryBuilder<'w, D: QueryData, F: QueryFilter>with chained.with::<A>().without::<C>().build(). - Visibility discipline: the facade chain (
bevyre-exportsbevy_internal, which gates eachpub use bevy_x as x;behind its feature flag inextras/bevy/crates/bevy_internal/src/lib.rs) plus a CI job that rejects any example importingbevy_*crates directly keeps the public surface to exactly one crate.
- Newtype with niche optimization:
extras/bevy/crates/bevy_ecs/src/entity/mod.rsdefinespub struct EntityIndex(NonMaxU32);soOption<Entity>costs no extra space, with a transmute justified inline:// SAFETY: NonMax is repr transparent. - Marker-type generics instead of runtime flags:
extras/bevy/crates/bevy_ptr/src/lib.rsdefines emptyAlignedandUnalignedstructs used as type parameters ofPtr,PtrMut, andOwningPtr, moving an alignment invariant into the type system. - Interior mutability as an architectural layer:
extras/bevy/crates/bevy_ecs/src/world/unsafe_world_cell.rsbuildsUnsafeWorldCell, a documentedUnsafeCell-style escape hatch that lets safe APIs hand out disjoint mutable access to the world; its module doc explains the rationale against&mut Worldaliasing in depth. - Audited unsafe with mandatory prose:
undocumented_unsafe_blocks = "warn"plus-D warningsyields 1766// SAFETY:comments inbevy_ecsalone; unsafe functions inextras/bevy/crates/bevy_ptr/src/lib.rscarry/// # Safetysections on every method. - Debug-checked unsafe unwrapping: the
DebugCheckedUnwraptrait inextras/bevy/crates/bevy_ecs/src/query/mod.rsis#[inline(always)] #[track_caller]and splits debug and release impls "to ensure that the unreachable! macro does not cause inlining to fail";bevy_ecshas 215#[track_caller]annotations for caller-accurate panics. - Variadic trait impls by macro:
extras/bevy/crates/bevy_ecs/src/system/system_param.rsusesvariadics_please::{all_tuples, all_tuples_enumerated}to implementSystemParamfor tuples (all_tuples_enumerated!(impl_param_set, 1, 8, P, p);), the mechanism behind Bevy's magic multi-parameter system functions. - Platform cfg as a DSL:
extras/bevy/crates/bevy_platform/src/cfg.rsdefinesswitch!,define_alias!,enabled!, anddisabled!macros so crates writecfg::std! { ... }instead of raw#[cfg(...)]; aliases are "evaluated in the context of the defining crate, not the consumer", which makes feature detection composable across the workspace. -
no_stdfirst:extras/bevy/crates/bevy_ecs/src/lib.rsopens with#![no_std], conditionally re-addsextern crate std;behind a feature, and guards portability with#[cfg(target_pointer_width = "16")] compile_error!(...). - Zero-copy string handling:
extras/bevy/crates/bevy_ecs/src/name.rsstores entity names asHashedStr(Hashed<Cow<'static, str>>)and acceptsimpl Into<Cow<'static, str>>, so string literals never allocate;BevyErrorcontext usesVec<Cow<'static, str>>the same way. - Full iterator trait ladders:
extras/bevy/crates/bevy_ecs/src/query/access.rsimplementsIterator,DoubleEndedIterator, andFusedIteratorforComponentIdIter<I>generically over the wrapped iterator, plusIntoIteratorfor both owned and borrowedComponentIdSet. - Structured concurrency:
extras/bevy/crates/bevy_tasks/src/task_pool.rsexposespub fn scope<'env, F, T>(&self, f: F) -> Vec<T>, a scoped task-spawning API where lifetimes prove that borrowed data outlives the spawned tasks, and atomics come frombevy_platform::syncso the same code compiles onno_stdtargets. - Self-referential proc-macro support:
extras/bevy/crates/bevy_ecs/src/lib.rscontainsextern crate self as bevy_ecs;with the comment "Required to make proc macros work in bevy itself", letting derive output paths resolve both inside and outside the defining crate.
- Every crate begins with
#, so the crates.io page, the rustdoc front page, and the GitHub README are one file and its examples are doctested. -
missing_docs = "warn"at workspace level plus-D warningsin CI means documentation is compiler-enforced, including on private items viacheck-private-items = trueinextras/bevy/clippy.toml. - Docs.rs output is themed:
extras/bevy/docs-rs/trait-tags.htmlinjects HTML badges for core ECS traits via--html-after-content, gated by a customdocsrs_depcfg registered inunexpected_cfgscheck-cfg. - Generated docs are checked, not trusted:
extras/bevy/docs/cargo_features.mdis produced bycargo run -p build-templated-pages -- update featuresfromextras/bevy/docs-template/features.md.tpl, and CI regenerates it and fails on any diff. - Contributor docs live in
extras/bevy/docs/(linters.md,profiling.md,debugging.md,linux_dependencies.md);CONTRIBUTING.mditself is four lines that link to the website's maintained guide. -
extras/bevy/.github/pull_request_template.mdstructures every PR as Objective, Solution, Testing, plus an optional Showcase section that asks for screenshots or before/after comparisons.extras/bevy/.github/ISSUE_TEMPLATE/has four forms including a dedicatedperformance_regression.md.
- Versioning: the whole workspace sits at
0.20.0-devbetween releases; CI runs againstrelease-*branches (trigger list inextras/bevy/.github/workflows/ci.yml). - Changelog discipline is front-loaded into PRs: breaking PRs must add a file
to
extras/bevy/_release-content/migration-guides/followingmigration_guides_template.md;extras/bevy/_release-content/migration_guides.mddocuments the process ("Bevy asks authors (and reviewers) to write a draft migration guide as part of the pull requests that make breaking changes") and label automation nags authors who skip it. Release notes are drafted the same way inrelease-notes/, and thecheck-release-contentCI job validates the directory withcargo run --package export-content -- --check. - Version bumping is automated:
extras/bevy/.github/workflows/post-release.ymlis aworkflow_dispatchjob that sanity-checks the current version with a regex, computes the next minor, runscargo release "${next_version}" --workspace --no-publish --execute --no-tag ...excluding unpublished crates, and opens the bump PR viapeter-evans/create-pull-request. - Distribution is crates.io only (59 crates); there are no binaries, shell
completions, or man pages to ship. Nightly rustdoc for main is deployed to
GitHub Pages by
extras/bevy/.github/workflows/docs.yml, which swaps the logo and injects<meta name="robots" content="noindex">so the dev docs never outrank docs.rs.
quinjet already has a strict clippy wall, rustfmt, cargo-deny, taplo, typos, a coverage floor, miri, and mutants. The practices below are the ones Bevy has that quinjet still lacks, each with its mechanism:
- Steer APIs with
disallowed-methodsinclippy.toml. Bevy bans all off32's transcendental methods with areasonstring pointing atbevy_math::ops. quinjet can banstd::process::exitoutsidemain,std::env::varoutside its config module, and rawcrossterm::execute!outside the terminal layer, each with a reason that names the sanctioned wrapper. Also setcheck-private-items = trueto lint private docs. - Require reasons on every suppression: add
allow_attributes = "warn"andallow_attributes_without_reason = "warn"under[lints.clippy], then use#[expect(lint, reason = "...")]instead ofallow, as inextras/bevy/Cargo.tomlandextras/bevy/crates/bevy_ecs/src/lib.rs. - Harden workflows the Bevy way: top-level
permissions: contents: read,persist-credentials: falseon everyactions/checkout, every action pinned to a full commit SHA with a version comment,timeout-minuteson every job, and aconcurrencygroup withcancel-in-progress: ${{github.event_name == 'pull_request'}}. Then add zizmor (zizmorcore/zizmor-action) and CodeQL with theactionslanguage fromextras/bevy/.github/workflows/security-static-analysis.ymlto lint the workflows themselves. - Adopt the merge queue: add
merge_group:to the CIon:block as inextras/bevy/.github/workflows/ci.ymland enable the queue on the repo, so main is only ever updated with a green combined state. - Split cache writing from cache reading: PR jobs use
actions/cache/restoreonly, and a separateupdate-caches.ymlonpush: mainplus a nightly cron rebuilds caches per toolchain, followingextras/bevy/.github/workflows/update-caches.yml. SetCARGO_INCREMENTAL: 0andCARGO_PROFILE_TEST_DEBUG: 0in CI env to keep those caches small. - Test the real MSRV: declare
rust-versioninCargo.toml, then add a CI job that extracts it (cargo metadata --no-deps --format-version 1 | jq --raw-output '.packages[] | select(.name=="quinjet") | .rust_version'), installs exactly that toolchain, and runscargo check, copying themsrvjob inextras/bevy/.github/workflows/ci.yml. - Script-driven end-to-end TUI runs, modeled on
bevy_ci_testing: add a cargo feature that makes the TUI read a scenario file (path from an env var like Bevy'sCI_TESTING_CONFIG), feed synthetic key events, render to a ratatuiTestBackend, and compare the terminal buffer against committed snapshots. Keep one scenario file per flow in a.github/example-run/style directory, as Bevy does with its RON configs. - Consumer-style integration crate: create a
tests-integration/directory excluded from the workspace (Bevy's[workspace] excludeplusextras/bevy/tests-integration/simple-ecs-test/Cargo.toml) that depends on quinjet by path and exercises the CLI as a black box, so packaging or feature-unification breakage surfaces before publishing. - Generated docs with a drift check: quinjet's CLI reference should be
generated from the clap definitions by a small tool, and CI should rerun
the generator and fail on
git diff --quiet HEAD --, exactly as thecheck-missing-examples-in-docsjob does inextras/bevy/.github/workflows/ci.yml. - An error-code catalog that cannot rot: give quinjet's user-facing failure
modes stable codes documented in per-code Markdown files, compiled into a
module with
#[doc = include_str!(...)]likeextras/bevy/errors/src/lib.rs, so every code block in the catalog is doctested. - Dependency-graph governance beyond
cargo deny check: copy Bevy'sdeny.tomlpatterns ofwildcards = "deny",unknown-registry = "deny", per-cratedeny-multiple-versionsfor heavy deps (for quinjet:ratatui,crossterm,clap), documentedignoreentries with links for every advisory exception, and[[bans.features]]to ban unwanted features of dependencies. - Dependabot with grouping and cooldown:
extras/bevy/.github/dependabot.ymlgroups coupled crates so they update atomically and setscooldown: default-days: 7; quinjet should groupratatui/crosstermthe same way. - Front-load the changelog: keep a
_release-content/directory with a template, require an entry in any behavior-changing PR, and check it in CI (extras/bevy/.github/workflows/ci.ymljobcheck-release-content); automate version bumps withcargo releasein aworkflow_dispatchworkflow modeled onextras/bevy/.github/workflows/post-release.yml. - Pin formatting semantics: add
style_editionandnewline_style = "Unix"torustfmt.tomlas Bevy does, so a rustfmt upgrade cannot cause a tree-wide diff, and keep a commented block of desired nightly options as the upgrade plan.
Helix is a modal terminal text editor in the Kakoune selection-first tradition: selections are
the primary editing primitive, every cursor is a one-range selection, and language intelligence
(tree-sitter syntax trees, LSP, DAP) is built in rather than bolted on through plugins. The
binary is hx, defined in extras/helix/helix-term/Cargo.toml:
[[bin]]
name = "hx"
path = "src/main.rs"Industry treats Helix as a reference for two things: how to structure a large interactive
terminal application in Rust, and how to run a high-velocity open source project with a small
core team. The changelog for the 25.07 release records the scale of participation
(extras/helix/CHANGELOG.md): "This release saw changes from 195 contributors."
Scale indicators measured directly from the clone (revision 079a789):
- 14 workspace members, 13 library or binary crates plus an
xtaskrunner (extras/helix/Cargo.toml). - 251 Rust source files totaling 107,479 lines of Rust outside
runtime/. - Per-crate line counts: helix-term 38,696; helix-core 20,086; helix-view 15,657; helix-lsp-types 9,906; helix-tui 7,623; helix-lsp 4,240; helix-stdx 2,652; helix-loader 2,087; helix-vcs 1,379; helix-dap 1,190; helix-dap-types 1,107; helix-event 1,094; xtask 850; helix-parsec 574.
- A 5,657 line
extras/helix/languages.tomldescribing every supported language, 220 bundled themes inextras/helix/runtime/themes, and 341 tree-sitter query directories inextras/helix/runtime/queries.
extras/helix/
|-- Cargo.toml workspace root, profiles, shared deps
|-- Cargo.lock committed, releases build with --locked
|-- rust-toolchain.toml pins channel 1.90.0 plus components
|-- rustfmt.toml empty file: rustfmt defaults, on purpose
|-- languages.toml language and grammar registry (5657 lines)
|-- theme.toml default theme
|-- book/ mdBook user manual (docs.helix-editor.com)
|-- docs/ contributor docs: CONTRIBUTING, architecture, releases, vision
|-- contrib/ packaging assets: completions, .desktop, icons, appdata
|-- runtime/ grammars, queries, themes, tutor: shipped next to the binary
|-- tests/ cross-crate corpus data (indent/, query/)
|-- xtask/ ad-hoc task runner crate (docgen, query-check, ...)
|-- helix-core/ functional editing primitives
|-- helix-view/ editor state model (documents, views, registers)
|-- helix-term/ the hx binary: event loop, compositor, commands, UI
|-- helix-tui/ TUI widget/backend layer, forked from tui-rs
|-- helix-event/ hook/event system, debouncing, redraw control
|-- helix-lsp/ helix-lsp-types/ LSP client and protocol types
|-- helix-dap/ helix-dap-types/ DAP client and protocol types
|-- helix-loader/ config/grammar loading, build metadata
|-- helix-vcs/ diff providers (git via gix, feature-gated)
|-- helix-parsec/ zero-dependency parser combinators
|-- helix-stdx/ std extensions (paths, env, rope utils, faccess)
`-- .github/ workflows, composite action, templates, dependabot
The split is explained in extras/helix/docs/architecture.md, which states the design intent
crate by crate, for example:
| helix-core | Core editing primitives, functional. |
| helix-view | UI abstractions for use in backends, imperative shell. |
| helix-term | Terminal UI |
Why this split works: helix-core is a pure functional layer (ropes, selections,
transactions) that can be tested without a terminal; helix-view is the imperative shell
holding editor state; helix-term is the only crate that knows about a real terminal. Protocol
types (helix-lsp-types, helix-dap-types) are separated from their clients so the huge,
mostly generated type definitions compile independently and can enforce stricter rules
(extras/helix/helix-lsp-types/src/lib.rs carries #![forbid(unsafe_code)]). Tiny leaf
crates like helix-parsec (574 lines, zero dependencies) keep compile graphs shallow.
The helix-stdx crate copies the rust-analyzer pattern of a project-local std extension,
which extras/helix/docs/architecture.md cites explicitly.
The root extras/helix/Cargo.toml uses resolver 2, a default-members entry so a bare
cargo build builds only the editor binary, and a [workspace.package] table that every
member inherits:
[workspace.package]
version = "25.7.1"
edition = "2021"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
license = "MPL-2.0"
rust-version = "1.90"Member manifests then contain only version.workspace = true, edition.workspace = true
and so on (see extras/helix/helix-core/Cargo.toml). Cross-crate dependency versions are
centralized in [workspace.dependencies] with a labeled dev-dependency section:
# dev dependencies
criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] }
quickcheck = { version = "1", default-features = false }Custom profiles are the standout practice. Release artifacts use an opt profile, and
integration tests get their own profile that optimizes only the hot crates so the suite runs
fast without paying full release compile times:
[profile.opt]
inherits = "release"
lto = "fat"
codegen-units = 1
strip = true
opt-level = 3
[profile.integration]
inherits = "test"
package.helix-core.opt-level = 2
package.helix-tui.opt-level = 2
package.helix-term.opt-level = 2Feature flags gate real cost: extras/helix/helix-term/Cargo.toml has
default = ["git"], git = ["helix-vcs/git"] (which turns on the heavy gix dependency in
extras/helix/helix-vcs/Cargo.toml: git = ["gix"] with optional = true), and
integration = ["helix-event/integration_test"] so test-only machinery never ships.
Platform-specific dependency tables replace runtime checks:
[target.'cfg(windows)'.dependencies]
crossterm = { version = "0.28", features = ["event-stream"] }
[target.'cfg(not(windows))'.dependencies] # https://github.com/vorner/signal-hook/issues/100
signal-hook-tokio = { version = "0.4", features = ["futures-v0_3"] }Unusual details worth copying: an exact-pin with a written justification in
extras/helix/helix-core/Cargo.toml (unicode-width = "=0.1.12" under a comment explaining
rendering breakage when installing without --locked); Debian packaging metadata inline as
[package.metadata.deb] in extras/helix/helix-term/Cargo.toml; bench = false on the
helix-view lib target so criterion owns benchmarking
(extras/helix/helix-view/Cargo.toml); and cargo aliases in
extras/helix/.cargo/config.toml:
[alias]
xtask = "run --package xtask --"
integration-test = "test --features integration --profile integration --workspace --test integration"The same file passes --cfg tokio_unstable through [target."cfg(all())"] rustflags with a
nine-line comment explaining why build.rustflags would be silently overwritten by user
config; the flag unlocks runtime::Handle::id so parallel integration tests can keep
per-runtime globals separate. There are no [lints] tables anywhere in the workspace.
extras/helix/rustfmt.toml is a zero-byte file. That is a deliberate statement: the presence
of the file pins the project to rustfmt defaults and prevents any parent directory or editor
override from changing them, while adding no unstable options that would require nightly.
extras/helix/rust-toolchain.toml guarantees every contributor formats with the same rustfmt:
[toolchain]
channel = "1.90.0"
components = ["rustfmt", "rust-src", "clippy"]There is no .editorconfig. Non-Rust hygiene is handled by extras/helix/.gitattributes,
which normalizes line endings and assigns diff drivers per file type:
* text=auto
*.rs text diff=rust
*.toml text diff=toml
*.scm text diff=scheme
The same file also curates GitHub language statistics
(runtime/queries/**/*.scm linguist-language=Tree-sitter-Query,
tests/indent/** linguist-documentation). TOML, markdown and query files have no dedicated
formatter; their consistency is maintained by review and by the generated-docs check
described in section 6.
Helix has no clippy.toml and no [lints] tables; the entire policy lives in one CI flag in
extras/helix/.github/workflows/build.yml:
- name: Run cargo clippy
run: cargo clippy --workspace --all-targets -- -D warningsThe philosophy is: default clippy level, zero tolerance. Everything clippy warns about by
default is a build failure across all targets (including tests and benches), and exceptions
are granted locally, never globally. The clone contains only 51 clippy:: attribute
mentions across 107k lines, dominated by narrowly scoped allows:
13x clippy::too_many_arguments, 5x clippy::type_complexity,
4x clippy::should_implement_trait, each attached to a single item, for example
#[allow(clippy::too_many_lines)] directly on Args::parse_args in
extras/helix/helix-term/src/args.rs. Rustdoc is linted with the same severity in the same
job:
- name: Run cargo doc
run: cargo doc --no-deps --workspace --document-private-items
env:
RUSTDOCFLAGS: -D warningsThe custom check infrastructure is where Helix invests instead: the xtask crate
(extras/helix/xtask/src/main.rs) implements project-specific lints that no generic tool
could provide. querycheck compiles every tree-sitter query for every language against its
grammar, indentcheck runs the indent engine over a corpus in extras/helix/tests/indent/,
theme-check validates all 220 themes, and docgen regenerates command and language tables.
These run as first-class CI jobs (section 6), which is the real lesson: lint the artifacts
your project actually ships, not only the Rust.
Four workflows live in extras/helix/.github/workflows: build.yml, release.yml,
gh-pages.yml, cachix.yml, plus dependabot.yml and a composite action.
build.yml triggers on pull_request, pushes to master, merge_group (GitHub merge queue
is in active use), and a nightly cron (00 01 * * *). Concurrency cancels superseded PR runs
but never master runs:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}Every workflow sets permissions: contents: read at the top and escalates per job only where
needed (release.yml grants contents: write, id-token: write, attestations: write only
to the publish job). Every job carries
if: github.repository == 'helix-editor/helix' || github.event_name != 'schedule' so forks
do not burn cron minutes. The test job has timeout-minutes: 30 and a five-way OS matrix:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest, ubuntu-24.04-arm, windows-11-arm]Toolchain and caching are factored into a composite action,
extras/helix/.github/actions/rust-setup/action.yml, so all jobs share one definition. It
pins third-party actions by full commit SHA with a human-readable comment, uses
Swatinem/rust-cache with a shared-key, and adds a second cache layer for built
tree-sitter grammars keyed on the language registry, with a manual bust knob
(GRAMMAR_CACHE_VERSION env in build.yml):
- uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
with:
shared-key: ${{ inputs.cache-key }}
- if: inputs.cache-grammars == 'true'
uses: actions/cache@v5
with:
path: runtime/grammars
key: ${{ runner.os }}-${{ runner.arch }}-stable-v${{ inputs.grammar-cache-version }}-tree-sitter-grammars-${{ hashFiles('languages.toml') }}MSRV is enforced, not aspirational: env: MSRV: "1.90" at the top of build.yml and every
job installs exactly that toolchain. The docs job runs all xtask validators with
if: always() so one failure does not mask the others, then fails the build if generated
documentation is stale:
- name: Check uncommitted documentation changes
if: always()
run: |
git diff
git diff-files --quiet \
|| (echo "Run 'cargo xtask docgen', commit the changes and push again" \
&& exit 1)gh-pages.yml builds the mdBook and deploys versioned directories per tag plus a rolling
master build. cachix.yml publishes the Nix flake outputs on ubuntu and macos.
extras/helix/.github/dependabot.yml runs weekly for both cargo and github-actions
ecosystems, grouping minor and patch Rust bumps into one PR to cut review noise.
The layers, from smallest to largest:
- Unit tests inline in
#[cfg(test)] mod teststhroughout the crates, run bycargo test --workspaceon all five CI OSes. - Property tests via quickcheck where an invariant exists, for example the diff round-trip in
extras/helix/helix-core/src/diff.rs:
quickcheck::quickcheck! {
fn test_compare_ropes(a: String, b: String) -> bool {
let mut old = Rope::from(a);
let new = Rope::from(b);
compare_ropes(&old, &new).apply(&mut old);
old == new
}
}- Corpus tests:
extras/helix/helix-core/tests/indent.rsreplays real source files fromextras/helix/tests/indent/through the indent engine; the same corpus feedscargo xtask indent-check. - Criterion benchmarks:
extras/helix/helix-view/benches/word_index.rs, wired withharness = falseandrequired-features = ["bench"], where thebenchfeature exposes internals only for measurement (extras/helix/helix-view/Cargo.toml: "Exposes internals. Should not be enabled except for benchmarking.").
The crown jewel is end-to-end testing of the full TUI through the real event loop.
extras/helix/helix-term/tests/integration.rs gates everything behind
#[cfg(feature = "integration")], and a smoke test reads like a spec:
#[tokio::test(flavor = "multi_thread")]
async fn hello_world() -> anyhow::Result<()> {
test(("#[\n|]#", "ihello world<esc>", "hello world#[|\n]#")).await?;
Ok(())
}Three pieces make that one-liner possible. First, a selection-annotation DSL in
extras/helix/helix-core/src/test.rs: test::print parses strings where #[...|]# marks
the primary selection, converting fixtures into (String, Selection) pairs; the editor's own
key-macro parser (parse_macro) turns "ihello world<esc>" into key events. Second, the
harness in extras/helix/helix-term/tests/test/helpers.rs constructs a real Application,
feeds events through a channel into app.event_loop_until_idle(&mut rx_stream).await, and
asserts on resulting document state; it includes a LineFeedHandling enum so the same
fixtures pass on Windows CRLF, and an AppBuilder builder for per-test config. Third,
test-only cheap infrastructure: the integration_test feature swaps the runtime_local!
macro in extras/helix/helix-event/src/runtime.rs from a plain static to a
per-tokio-runtime map keyed by tokio::runtime::Id, so parallel tests each get isolated
"globals". The suite runs under its own optimized profile via the
cargo integration-test alias, as a separate CI step on every OS in the matrix.
The pattern is textbook two-tier: anyhow at the application boundary, thiserror enums at
library boundaries. extras/helix/helix-lsp/src/lib.rs defines a crate Result alias and a
public error enum with #[from] conversions:
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Error, Debug)]
pub enum Error {
Rpc(#[from] jsonrpc::Error),
Parse(Box<dyn std::error::Error + Send + Sync>),
#[error("IO Error: {0}")]
IO(#[from] std::io::Error),
...
Other(#[from] anyhow::Error),
}Similar enums exist in extras/helix/helix-dap/src/lib.rs,
extras/helix/helix-view/src/document.rs (DocumentOpenError), and
extras/helix/helix-view/src/clipboard.rs. The binary entry point
(extras/helix/helix-term/src/main.rs) shows disciplined exit-code handling: main is a
thin wrapper so the process can exit with a real code after destructors run:
fn main() -> Result<()> {
let exit_code = main_impl()?;
std::process::exit(exit_code);
}Failures are graded, not uniform: unparsable CLI args are a hard error with
.context("could not parse arguments"); a missing config file silently falls back to
defaults via a targeted match arm
(Err(ConfigLoadError::Error(err)) if err.kind() == std::io::ErrorKind::NotFound); a
malformed config prints the error and waits for Enter before continuing with defaults; a
BrokenPipe from --health piped into head is deliberately swallowed. Panics are reserved
for unrecoverable states, and even then retried first:
extras/helix/helix-term/src/application.rs only panics on
"Failed to claim terminal" after 10 retries.
API-design details: newtypes with niche optimization in extras/helix/helix-view/src/lib.rs
(pub struct DocumentId(NonZeroUsize); under the comment "uses NonZeroUsize so
Option<DocumentId> use a byte rather than two"), with the extra constructor confined to
#[cfg(test)] and pub(crate); slotmap new_key_type! for view keys; builder pattern in
the test harness (AppBuilder in extras/helix/helix-term/tests/test/helpers.rs); and
visibility used as documentation (#[doc(hidden)] pub mod runtime in
extras/helix/helix-event/src/lib.rs for macro plumbing that must be pub but is not API).
- Trait plus blanket impl for composability:
extras/helix/helix-parsec/src/lib.rsdefinestrait Parser<'a> { type Output; fn parse(&self, input: &'a str) -> ParseResult<'a, Self::Output>; }and a blanketimpl<'a, F, T> Parser<'a> for F where F: Fn(&'a str) -> ParseResult<'a, T>, so every closure is a parser and combinators are ordinary higher-order functions. - Iterator-generic rendering API: the backend abstraction in
extras/helix/helix-tui/src/backend/mod.rstakes cells as a generic iterator,fn draw<'a, I>(&mut self, content: I) where I: Iterator<Item = (u16, u16, &'a Cell)>, letting the terminal, crossterm, and test backends share one streaming protocol with no intermediate buffer allocation. - Precise lifetime bounds on zero-copy accessors:
extras/helix/helix-core/src/selection.rshaspub fn fragment<'a, 'b: 'a>(&'a self, text: RopeSlice<'b>) -> Cow<'b, str>, tying the returnedCowto the text's lifetime rather than the selection's, andfragmentsreturnsimpl DoubleEndedIterator<Item = Cow<'a, str>> + ExactSizeIterator. - Hand-rolled compressed Cow when profiling justifies it:
GraphemeStr<'a>inextras/helix/helix-core/src/graphemes.rspacks a borrowed-or-owned string intoptr: NonNull<u8>, len: u32with the ownership bit stored asconst MASK_OWNED: u32 = 1 << 31, withunsafeconfined toDerefandDrop. - Lock-free config reloading:
extras/helix/helix-view/src/editor.rsstores the syntax loader aspub syn_loader: Arc<ArcSwap<syntax::Loader>>and builds registers overarc_swap::access::Map, so readers on the render path never take a lock while:config-reloadswaps the whole config atomically. - Declarative macros to express partial borrows:
extras/helix/helix-view/src/macros.rsdefinescurrent!,doc_mut!,view_mut!because, per its module doc, functions taking&mut selfwould borrow the wholeEditor; the macros expand to direct field accesses so the borrow checker sees disjoint borrows. - A typed event bus with an explicit soundness contract:
extras/helix/helix-event/src/registry.rskeys hooks byTypeIdand marksregister_hookasunsafewith a written invariant ("hookmust be totally generic over all lifetime parameters ofE"), then wraps it in a saferegister_hook!macro; the crate-level doc inextras/helix/helix-event/src/lib.rsexplains the sync-hook versusAsyncHooksplit, debouncing, and frame locking. - Feature-swapped globals for test isolation:
runtime_local!inextras/helix/helix-event/src/runtime.rscompiles to a plain static normally and, underintegration_test, to aparking_lot::RwLock<HashMap<tokio::runtime::Id, &'static T, ...>>so concurrent integration tests cannot share state. - Platform handling through cfg-swapped imports rather than scattered branches:
extras/helix/helix-term/tests/test/helpers.rsselects the whole event source per OS,#[cfg(windows)] use crossterm::event::{Event, KeyEvent};versus#[cfg(not(windows))] use termina::event::{...}, mirroring the per-target dependency tables inextras/helix/helix-term/Cargo.toml;extras/helix/helix-stdx/src/faccess.rsconfines all Windows ACLunsafebehind amod impper platform. - Extension traits over foreign types:
RopeSliceExt<'a>inextras/helix/helix-stdx/src/rope.rsaddsregex_input,starts_with, grapheme-boundary helpers to ropey'sRopeSlice, marking non-consuming builders with#[must_use], so downstream code reads as if ropey natively supported cursor-based regex. - Persistent, invertible edits as an OT-style algebra:
extras/helix/helix-core/src/transaction.rsmodels all edits asenum Operation { Retain(usize), Delete(usize), Insert(Tendril) }inside aChangeSetthat can be composed, inverted for undo, and mapped over positions with a six-variantAssocpolicy; this single abstraction powers undo, LSP edits, and multi-cursor changes. - Compile-time command registry:
static_commands!inextras/helix/helix-term/src/commands.rsdeclares each editor command once ($name, $doc,) and generates both theconstitems andpub const STATIC_COMMAND_LIST: &'static [Self], which keymaps, the fuzzy palette, andxtask docgenall consume, so a command can never exist without a name and doc string.
Documentation is split by audience. Users get an mdBook in extras/helix/book/ deployed to
docs.helix-editor.com by gh-pages.yml, with edit-url-template in
extras/helix/book/book.toml linking every page to its source. Three pages under
extras/helix/book/src/generated/ (typable-cmd.md, static-cmd.md, lang-support.md)
are machine-written by cargo xtask docgen from the command registry itself
(extras/helix/xtask/src/docgen.rs imports helix_term::commands::TYPABLE_COMMAND_LIST),
and CI fails if they drift from the code.
Contributors get extras/helix/docs/: CONTRIBUTING.md covers log-based debugging,
integration-test workflow, and a written MSRV policy ("We follow Firefox's MSRV policy"
listing the three places to update); architecture.md is a genuine orientation document
mapping crates to responsibilities and naming the core abstractions (Rope, Selection,
Transaction, Syntax); releases.md is a step-by-step release runbook; vision.md states
scope. Rustdoc is held to -D warnings including private items (section 6), and module-level
docs carry design rationale rather than restating signatures; the eleven-line doc comment on
test::print in extras/helix/helix-core/src/test.rs documents the selection DSL grammar
with examples and panics sections. Issue intake is structured:
extras/helix/.github/ISSUE_TEMPLATE/bug_report.yaml is a GitHub form with required
reproduction fields and a pre-formatted log section, labeled C-bug automatically, while
enhancement.md redirects feature ideas to Discussions.
Versioning is CalVer, YY.0M(.MICRO), encoded as SemVer for Cargo (25.07.1 becomes
version = "25.7.1" in extras/helix/Cargo.toml); extras/helix/helix-loader/build.rs
converts it back for display and embeds the git hash
(cargo:rustc-env=VERSION_AND_GIT_HASH=...), with a Nix fallback via
HELIX_NIX_BUILD_REV. The changelog is hand-curated per
extras/helix/docs/releases.md, and extras/helix/CHANGELOG.md opens with a comment
template listing the standing section order (Breaking changes, Features, Commands, ...).
extras/helix/.github/workflows/release.yml triggers on version tags, on
patch/ci-release-* branches, and on PRs touching itself; a preview env publishes
artifacts instead of a release when not on a real tag, so the pipeline is testable without
tagging. The fetch-grammars job downloads all tree-sitter grammars once and shares the
tarball with a six-target matrix (x86_64 and aarch64 for Linux, macOS, Windows) that builds
with cargo build --profile opt --locked. Linux intentionally builds on ubuntu-22.04 with a
comment warning that a newer image would raise the GLIBC floor. Outputs: tar.xz and zip
archives bundling the runtime and completions, an AppImage with zsync update metadata, and a
.deb produced by cargo-deb from the metadata in extras/helix/helix-term/Cargo.toml. The
publish job signs provenance with actions/attest-build-provenance before uploading.
Shell completions for bash, elvish, fish, nushell, and zsh are hand-maintained in
extras/helix/contrib/completion/ (the CLI parser is also hand-rolled in
extras/helix/helix-term/src/args.rs, a plain while let Some(arg) = argv.next() loop over
a #[derive(Default)] pub struct Args), and the .deb installs them into the distribution's
completion directories. Tags are GPG-signed (git tag -s in the runbook), and Nix users get
cached builds through cachix.yml.
quinjet already exceeds Helix on lint strictness, deny/typos/taplo, coverage, miri, and mutants. What Helix still teaches:
- Adopt the integration profile trick: add
[profile.integration]withinherits = "test"and per-packagepackage.quinjet.opt-level = 2in Cargo.toml, plus an aliasintegration-test = "test --features integration --profile integration --test integration"in.cargo/config.toml, mirroringextras/helix/Cargo.tomlandextras/helix/.cargo/config.toml; TUI-driving tests are slow at opt-level 0. - Build a key-sequence harness for the TUI: an
AppBuilder, a channel of synthetic crossterm events, anevent_loop_until_idleseam in the app, and fixture syntax for before/after state, modeled onextras/helix/helix-term/tests/test/helpers.rs; drive it from a singletests/integration.rsbehind anintegrationcargo feature so release binaries carry no test hooks. - Generate reference docs from the command table and gate drift in CI: a small xtask (or a
docssubcommand) that renders subcommand tables to markdown, then a workflow step that runs it and fails ongit diff-files --quiet, exactly as in thedocsjob ofextras/helix/.github/workflows/build.yml. - Split the OS matrix wide and cheap:
ubuntu-latest, macos-latest, windows-latest, ubuntu-24.04-arm, windows-11-armwithtimeout-minuteson the job, perextras/helix/.github/workflows/build.yml; a Git TUI has exactly the same terminal-and-filesystem portability risks as an editor. - Factor CI setup into a repo-local composite action
(
.github/actions/rust-setup/action.yml) withSwatinem/rust-cacheshared-keyinputs, and pin third-party actions by commit SHA with a version comment, asextras/helix/.github/actions/rust-setup/action.ymldoes. - Add
merge_group:to the CI trigger list and turn on the GitHub merge queue; Helix pairs it with aconcurrencygroup that cancels only PR runs (extras/helix/.github/workflows/build.yml). - Set default
permissions: contents: readin every workflow and escalate per job; sign release artifacts withactions/attest-build-provenance@v4in the publish job, perextras/helix/.github/workflows/release.yml. - Test the release pipeline without tagging: a
previewenv expression (!startsWith(github.ref, 'refs/tags/')) that uploads artifacts instead of creating a release, plus apull_request: paths: ['.github/workflows/release.yml']trigger, fromextras/helix/.github/workflows/release.yml. - Encode grades of failure at startup: match on
io::ErrorKind::NotFoundfor a missing config versus a hard error for a bad one, tolerateBrokenPipeon informational output, and keepfn maina thinstd::process::exit(main_impl()?)wrapper, perextras/helix/helix-term/src/main.rs. - Use quickcheck (already a dev-dependency pattern worth copying from
extras/helix/Cargo.toml) for round-trip invariants quinjet has in abundance: diff apply/revert, hunk splitting, ref name parsing, followingextras/helix/helix-core/src/diff.rs. - Ship packaging from the manifest:
[package.metadata.deb]pluscargo-deb --no-buildin the release workflow, installing completions into/usr/share/bash-completion/completionsand friends, perextras/helix/helix-term/Cargo.toml. - Add
.gitattributeswith* text=autoand per-extension diff drivers (*.rs diff=rust,*.toml diff=toml) as inextras/helix/.gitattributes; it is the cheapest cross-platform CRLF insurance a TUI repo can buy. - Group dependabot minor/patch cargo updates
(
groups: rust-dependencies: update-types: [minor, patch]) and watchgithub-actionsweekly, perextras/helix/.github/dependabot.yml. - When quinjet grows internal IDs, copy the
NonZeroUsizenewtype with the one-line rationale comment fromextras/helix/helix-view/src/lib.rs, and keep test-only constructors#[cfg(test)] pub(crate).
fd is a user-friendly, parallel replacement for the Unix find command. Its manifest describes it plainly (extras/fd/Cargo.toml):
[package]
name = "fd-find"
description = "fd is a simple, fast and user-friendly alternative to find."
version = "10.4.2"
edition= "2024"
rust-version = "1.90.0"Industry uses fd because it is dramatically faster than find (the README at extras/fd/README.md documents a hyperfine benchmark where fd is roughly 23 times faster than find -iregex on a 4-million-file home directory), because it respects .gitignore by default, and because it composes well with xargs, fzf, and editor tooling. It is packaged in essentially every Linux distribution, Homebrew, Scoop, and winget.
Measured scale indicators from the clone:
- Single crate, single binary. There is no workspace;
[[bin]] name = "fd"points atsrc/main.rs(extras/fd/Cargo.toml). - 5,059 lines of Rust in
src/across 22 files, plus 3,222 lines of test code (extras/fd/tests/tests.rs is 2,878 lines, extras/fd/tests/testenv/mod.rs is 344 lines). Total: 8,281 lines of Rust. - 130 locked packages in extras/fd/Cargo.lock, from only about 20 direct dependencies.
- 101
#[test]functions in the integration suite alone, plus dozens of inline unit tests and macro-generated cases. - One CI workflow file (extras/fd/.github/workflows/CICD.yml) covering lint, format, MSRV, a 14-target build matrix, and release publishing.
The headline lesson of this chapter: a tool used by millions can be a small, single-crate codebase if the code is disciplined, the test harness exercises the real binary, and the release pipeline is fully automated.
The real top-level tree (from ls of extras/fd):
fd/
|-- .cargo/
| `-- config.toml target-specific rustflags (static CRT on MSVC)
|-- .github/
| |-- ISSUE_TEMPLATE/ bug_report.yaml, feature_request.md, question.md, config.yml
| |-- workflows/
| | `-- CICD.yml the single CI/CD pipeline
| |-- dependabot.yml
| `-- FUNDING.yml
|-- contrib/
| `-- completion/ hand-written zsh completion (_fd) and fdfind aliases
|-- doc/
| |-- fd.1 hand-maintained man page (587 lines of roff)
| |-- release-checklist.md
| |-- screencast.sh script that regenerates the README demo SVG
| `-- sponsors.md
|-- scripts/
| |-- create-deb.sh builds Debian packages in CI
| |-- update-help.awk syncs `fd -h` output into README.md
| `-- version-bump.sh automates the release version bump
|-- src/
| |-- main.rs entry point, config construction, module declarations
| |-- cli.rs clap derive definitions (971 lines)
| |-- walk.rs parallel traversal engine (744 lines)
| |-- exec/ --exec / --exec-batch subsystem (mod, command, job)
| |-- filter/ size, time, owner filters (mod, size, time, owner)
| |-- fmt/ --format template engine (mod, input)
| |-- config.rs, dir_entry.rs, output.rs, sanitize.rs, hyperlink.rs,
| |-- filesystem.rs, filetypes.rs, exit_codes.rs, error.rs, regex_helper.rs
|-- tests/
| |-- testenv/mod.rs reusable end-to-end harness
| `-- tests.rs 2,878 lines of black-box CLI tests
|-- Cargo.toml, Cargo.lock, Cross.toml, Makefile, rustfmt.toml
|-- CHANGELOG.md, CONTRIBUTING.md, SECURITY.md, README.md
`-- LICENSE-APACHE, LICENSE-MIT
Why this split works:
-
src/is flat where the domain is flat (one file per concern: output, sanitize, hyperlink) and nested only where a subsystem has real internal structure (exec/,filter/,fmt/). No file exceptcli.rsandwalk.rsexceeds 300 lines. - Everything that supports distribution but is not code lives in named top-level directories:
doc/for the man page and release docs,contrib/for shell-specific completion files that cannot be generated,scripts/for release mechanics. CI cancp doc/fd.1andbash scripts/create-deb.shwithout guessing. - The test harness lives in
tests/testenv/mod.rsnext to the single integration test binary, so the entire black-box surface is compiled once. A note in fd's history: keeping one integration test crate instead of many files avoids relinking the binary per test file.
extras/fd/Cargo.toml is a masterclass in single-crate manifest hygiene.
Dependency organization. Simple version requirements are one-liners; anything needing features gets its own table:
[dependencies.clap]
version = "4.6.1"
features = ["suggestions", "color", "wrap_help", "cargo", "derive"]
[dependencies.lscolors]
version = "0.21"
default-features = false
features = ["nu-ansi-term"]Platform-conditional dependencies keep Unix-only crates off Windows builds entirely:
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31.1", default-features = false, features = ["signal", "user", "hostname"] }The jemalloc dependency has the most elaborate cfg expression in the file, and its comment explains why and cross-references the code that must stay in sync:
# FIXME: Re-enable jemalloc on macOS
# jemalloc is currently disabled on macOS due to a bug in jemalloc in combination with macOS
# Catalina. See https://github.com/sharkdp/fd/issues/498 for details.
# This has to be kept in sync with src/main.rs where the allocator for
# the program is set.
[target.'cfg(all(not(windows), not(target_os = "android"), not(target_os = "macos"), ...))'.dependencies]
tikv-jemallocator = {version = "0.7.0", optional = true}Feature flags. Features are additive capability switches, not configuration:
[features]
use-jemalloc = ["tikv-jemallocator"]
completions = ["clap_complete"]
base = ["use-jemalloc"]
default = ["completions"]clap_complete is optional and only pulled in by the completions feature; src/main.rs guards the whole completion path with #[cfg(feature = "completions")].
Profiles. The dev profile is tuned for compile speed without losing backtraces, and dependencies skip debug info entirely:
[profile.dev]
debug = "line-tables-only"
[profile.dev.package."*"]
debug = false
[profile.debugging]
inherits = "dev"
debug = true
[profile.release]
lto = true
strip = true
codegen-units = 1The custom debugging profile is the escape hatch: full debug info on demand (cargo build --profile debugging) without slowing everyday builds.
MSRV and edition. rust-version = "1.90.0" and edition= "2024" sit in [package], and section 6 shows how CI reads the MSRV out of the manifest so it is declared exactly once.
Unusual extras. The manifest carries [package.metadata.binstall] so cargo binstall fd-find fetches the prebuilt release archive instead of compiling:
[package.metadata.binstall]
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-v{ version }-{ target }.{ archive-format }"
bin-dir = "{ bin }-v{ version }-{ target }/{ bin }{ binary-ext }"
pkg-fmt = "tgz"with per-target overrides switching Windows targets to zip. There is also exclude = ["/benchmarks/*"] to keep benchmark fixtures out of the published crate, and extras/fd/.cargo/config.toml statically links the MSVC C runtime so the Windows EXE has no DLL dependency:
# On Windows MSVC, statically link the C runtime so that the resulting EXE does
# not depend on the vcruntime DLL.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]Cross-compilation quirks live in extras/fd/Cross.toml, passing JEMALLOC_SYS_WITH_LG_PAGE=16 through to aarch64 containers to fix a page-size bug referenced by issue number.
extras/fd/rustfmt.toml is a single line:
# Defaults are usedThat one line is a deliberate practice, not an omission. The file exists so that editors and CI agree there is a rustfmt configuration, and its content documents the policy: stock rustfmt, no overrides, no style debates. CI enforces it with cargo fmt -- --check (the ensure_cargo_fmt job in extras/fd/.github/workflows/CICD.yml).
There is no .editorconfig and no formatter for YAML or Markdown; the non-Rust surface is small enough that review covers it. The only formatting-adjacent config for non-Rust files is extras/fd/doc/.gitattributes, which marks the generated screencast as vendored so it does not pollute language statistics:
* linguist-vendored
fd's linting setup is minimal and centralized in CI rather than in the manifest. There is no clippy.toml, no [lints] table, and no crate-level #![deny(...)] attributes. The wall is a single CI invocation (extras/fd/.github/workflows/CICD.yml):
lint_check:
name: Ensure 'cargo clippy' has no warnings
steps:
- run: cargo clippy --all-targets --all-features -- -Dwarningsand a second clippy run on the MSRV toolchain (see section 6), whose step name states the reason: "Run clippy (on minimum supported rust version to prevent warnings we can't fix)". Running clippy on both stable and the MSRV catches lints that only exist on one of them.
The philosophy is default-lint-set, zero-warnings, with allows applied surgically at the smallest scope and always justified. The entire src/ tree contains exactly one clippy allow (extras/fd/src/walk.rs):
/// The Worker threads can result in a valid entry having PathBuf or an error.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum WorkerResult {
// Errors should be rare, so it's probably better to allow large_enum_variant than
// to box the Entry variant
Entry(DirEntry),
Error(ignore::Error),
}The comment explains the performance reasoning behind overriding the lint. The tests have one more (#[allow(clippy::let_and_return)] in extras/fd/tests/tests.rs, where a cfg(windows) block mutates the binding in between). Conditional-compilation warts are handled with targeted cfg_attr, for example in extras/fd/src/main.rs:
#[cfg_attr(not(windows), allow(unused_mut))]
let mut should_warn = pattern.contains('/');and in extras/fd/src/config.rs a field used only on some platforms carries #[cfg_attr(not(unix), allow(unused))]. There is no custom lint infrastructure; the check surface is clippy plus cargo fmt --check plus the compiler under -Dwarnings.
There is exactly one workflow, extras/fd/.github/workflows/CICD.yml, which is both CI and CD. Triggers:
on:
workflow_dispatch:
pull_request:
push:
branches:
- master
tags:
- '*'Security hardening at the top level:
permissions:
contents: readEvery actions/checkout invocation adds persist-credentials: false, so the checked-out tree never retains a token. Only the build job escalates, and only for what it needs:
permissions:
id-token: write
contents: write
attestations: writeJobs:
-
crate_metadataextracts name, version, maintainer, homepage, and MSRV fromcargo metadata --no-deps --format-version 1 | jq ...and publishes them as job outputs. This makes Cargo.toml the single source of truth: the MSRV job and the packaging steps all read these outputs instead of duplicating constants. -
ensure_cargo_fmtrunscargo fmt -- --checkon stable. -
lint_checkrunscargo clippy --all-targets --all-features -- -Dwarnings. -
min_versioninstalls the exact MSRV toolchain viadtolnay/rust-toolchain@masterwithtoolchain: ${{ needs.crate_metadata.outputs.msrv }}and runs both clippy andcargo test --lockedon it. -
buildis a 14-entry matrix withfail-fast: falsecovering aarch64/arm/i686/x86_64 crossed with gnu/musl Linux (via cross), both macOS architectures, and three Windows toolchains includingwindows-11-arm:- { target: aarch64-unknown-linux-gnu , os: ubuntu-24.04, use-cross: true } - { target: x86_64-apple-darwin , os: macos-26-intel } - { target: aarch64-pc-windows-msvc , os: windows-11-arm }
The build command is selected with an expression,
BUILD_CMD: "${{ matrix.job.use-cross && 'cross' || 'cargo' }}", and every cargo invocation passes--locked. Tests run on every target; for emulated ARM targets a step narrows the scope to--bin=fdbecause full integration tests are impractical under qemu. The job then runsmake completions, assembles a tarball containing the binary, README, licenses, changelog, man page, and completions, and callsbash scripts/create-deb.shon Ubuntu runners to build Debian packages (which also installfdfindsymlinks for Debian's binary rename). -
wingetpublishes to the Windows package manager on version tags using a token-scoped community action.
Action pinning is tiered: first-party and toolchain actions are pinned by tag (actions/checkout@v7.0.1, dtolnay/rust-toolchain@stable), while every third-party action that touches artifacts or credentials is pinned by full commit SHA with a version comment:
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
uses: actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d # v4
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2Even the cross binary is pinned (cross_version: "v0.2.5") and downloaded with gh release download rather than installed from a floating source. Release artifacts are attested with actions/attest (build provenance) before upload, gated on a regex check of the ref:
unset IS_RELEASE ; if [[ $GITHUB_REF =~ ^refs/tags/v[0-9].* ]]; then IS_RELEASE='true' ; fiNotable absences, both deliberate: there is no cargo/sccache caching action anywhere in the workflow (the crate is small enough that clean builds are cheap and cache poisoning is not a risk worth taking on a release pipeline), and there is no merge queue configuration (merge_group trigger absent). Dependency freshness is handled by extras/fd/.github/dependabot.yml, which adds the newer cooldown setting so that just-released versions age for a week before being proposed:
- package-ecosystem: "cargo"
schedule:
interval: "monthly"
cooldown:
default-days: 7
- package-ecosystem: "github-actions"
schedule:
interval: "daily"
cooldown:
default-days: 7fd's testing story has two clean layers.
Unit tests live inline, in #[cfg(test)] mod tests blocks inside the file they test: parsing in extras/fd/src/filter/size.rs and extras/fd/src/filter/owner.rs, template parsing in extras/fd/src/fmt/mod.rs, path helpers in extras/fd/src/filesystem.rs, sanitization in extras/fd/src/sanitize.rs, exit-code merging in extras/fd/src/exit_codes.rs. Table-driven cases are generated with local macro_rules! so each row is an individually named, individually reportable test:
gen_size_filter_parse_test! {
byte_plus: ("+1b", SizeFilter::Min(1)),
kilo_plus: ("+1k", SizeFilter::Min(1000)),
kibi_plus: ("+1ki", SizeFilter::Min(1024)),
...
}(extras/fd/src/filter/size.rs; the same pattern appears as owner_tests! and func_tests! elsewhere). Time-dependent logic is made deterministic with a cfg(test)-only clock in extras/fd/src/filter/time.rs:
#[cfg(test)]
thread_local! {
static TESTTIME: std::cell::RefCell<Option<Zoned>> = None.into();
}
/// This allows us to set a specific time when running tests
#[cfg(test)]
fn now() -> Zoned {
TESTTIME.with_borrow(|reftime| reftime.as_ref().cloned().unwrap_or_else(Zoned::now))
}Integration tests are pure black-box: they run the compiled fd binary as a subprocess. The harness (extras/fd/tests/testenv/mod.rs) builds a TestEnv that creates a tempdir fixture with a fake .git directory (so gitignore semantics activate), .fdignore and .gitignore files, and platform-appropriate symlinks, then locates the binary through Cargo's own mechanism:
fn find_fd_exe() -> PathBuf {
// Read the location of the fd executable from the environment
PathBuf::from(env::var("CARGO_BIN_EXE_fd").unwrap_or(env!("CARGO_BIN_EXE_fd").to_string()))
}The harness isolates environment state per test (cmd.env("LS_COLORS", ""), and a temp XDG_CONFIG_HOME when a global ignore file is under test), normalizes output (sorting lines, mapping / to the platform separator, rendering \0 visibly as NULL), and produces readable failures by diffing expected against actual with the diff crate:
let diff_text = diff::lines(expected, actual)
.into_iter()
.map(|diff| match diff {
diff::Result::Left(l) => format!("-{l}"),
diff::Result::Both(l, _) => format!(" {l}"),
diff::Result::Right(r) => format!("+{r}"),
})On top of the harness, extras/fd/tests/tests.rs asserts stdout content, stderr content, and exit status for essentially every flag. Two patterns deserve special mention. First, test-case parameterization for the flag-override matrix, proving that each negating flag exactly cancels its counterpart:
#[test_case("--hidden", &["--no-hidden"] ; "hidden")]
#[test_case("--no-ignore", &["--ignore"] ; "no-ignore")]
#[test_case("-uu", &["--ignore", "--no-hidden"] ; "uu")]
fn test_opposing(flag: &str, opposing_flags: &[&str]) {Second, hostile-input coverage: test_invalid_utf8 creates a file with a raw \xFE byte in its name and asserts the lossy rendering, and test_hyperlink asserts the exact OSC 8 escape sequence including the hostname. Tests that depend on OS capabilities are guarded (#[cfg(unix)], #[cfg(target_os = "linux")]) and some even probe the environment at runtime, like test_file_system_boundaries skipping itself when /dev/null shares a device with /.
What fd does not have in-repo: no snapshot-testing crate (the normalize-and-diff harness fills that role), no fuzzing targets, no property testing, and no criterion benchmarks. Performance benchmarking lives in a separate repository (fd-benchmarks, linked from extras/fd/README.md) driven by hyperfine, and the manifest excludes /benchmarks/* from publication.
fd is a binary crate, so it standardizes on anyhow rather than structured error enums. run() returns anyhow::Result<ExitCode> and errors are built at the point of failure with actionable, user-facing text (extras/fd/src/main.rs):
env::set_current_dir(base_directory).with_context(|| {
format!(
"Could not set '{}' as the current working directory",
base_directory.to_string_lossy()
)
})?;Error messages teach: the regex build failure appends a note about --fixed-strings, --exact, and --glob; the path-separator diagnostic prints two copy-pastable alternative commands. Domain parsing failures happen at the clap boundary via value_parser = SizeFilter::from_string and value_parser = OwnerFilter::from_string (extras/fd/src/cli.rs), so invalid input never reaches program logic.
Exit codes are a first-class type (extras/fd/src/exit_codes.rs), not scattered integers:
pub enum ExitCode {
Success,
HasResults(bool),
GeneralError,
KilledBySigint,
}
impl From<ExitCode> for i32 {
fn from(code: ExitCode) -> Self {
match code {
ExitCode::Success => 0,
ExitCode::HasResults(has_results) => !has_results as i32,
ExitCode::GeneralError => 1,
ExitCode::KilledBySigint => 130,
}
}
}ExitCode::exit(self) -> ! also re-raises SIGINT after restoring the default handler so callers observe a genuine signal death, and merge_exitcodes(impl IntoIterator<Item = ExitCode>) folds the results of parallel --exec jobs. main() is a thin adapter: run, print {err:#} through the sanitizing print_error, exit with GeneralError.
Panic policy: unwrap() is confined to invariants (mutex poisoning, joins on scoped threads) and unreachable! carries an explanation of why the branch is impossible (extras/fd/src/walk.rs). debug_assert! documents parser postconditions in extras/fd/src/fmt/mod.rs.
API design within the crate is deliberate even without external consumers. Config (extras/fd/src/config.rs) is a plain struct with a doc comment on every field, constructed once in construct_config and passed by reference everywhere. Visibility is minimal: PathUrl is pub(crate) (extras/fd/src/hyperlink.rs), the Check<T> enum inside the owner filter is private, and CLI struct fields that exist only as override targets are private unit types. TestEnv uses consuming builder methods (normalize_line, global_ignore_file) with struct-update syntax. OwnerFilter::filter_ignore turns a no-op filter into None so downstream code can use plain Option combinators.
Ten-plus concrete idioms, each cited:
-
Lazy per-entry memoization with
OnceCell.DirEntrycaches metadata and color style so a syscall and a style lookup happen at most once per entry, withoutmutmethods (extras/fd/src/dir_entry.rs):pub struct DirEntry { inner: DirEntryInner, metadata: OnceCell<Option<Metadata>>, style: OnceCell<Option<Style>>, } ... pub fn metadata(&self) -> Option<&Metadata> { self.metadata .get_or_init(|| match &self.inner { ... }) .as_ref() }
-
OnceLockstatics for compile-once machinery: the size-filter regex (static SIZE_CAPTURES: OnceLock<Regex>in extras/fd/src/filter/size.rs), the aho-corasick placeholder automaton (static PLACEHOLDERS: OnceLock<AhoCorasick>in extras/fd/src/fmt/mod.rs), and the cached hostname in extras/fd/src/hyperlink.rs. -
Zero-copy with
Cowon the hot path. The per-entry match string borrows the filename and only allocates when--full-pathforces a join (extras/fd/src/walk.rs):fn search_str_for_entry<'a>( entry_path: &'a std::path::Path, full_path_base: Option<&std::path::Path>, ) -> Cow<'a, OsStr> {
The same pattern appears in
osstr_to_bytes(extras/fd/src/filesystem.rs),replace_separator(extras/fd/src/fmt/mod.rs), andsanitize_for_terminal(extras/fd/src/sanitize.rs), which returnsCow::Borrowedwhen nothing needs escaping. -
Structured concurrency with
thread::scope. Both the sender/receiver pair and the--execjob pool borrow&selfand&ConfigwithoutArc-wrapping the world (extras/fd/src/walk.rs):let exit_code = thread::scope(|scope| { // Spawn the receiver thread(s) let receiver = scope.spawn(|| self.receive(rx)); self.spawn_senders(walker, tx); receiver.join().unwrap() });
-
Backpressure-aware batched channels. Instead of one channel send per file, workers accumulate results in a
Batch(anArc<Mutex<Option<Vec<WorkerResult>>>>) and send the handle once per batch; the receiver drains it bytake()-ing the Vec throughIntoIterator. The channel itself isbounded(2 * config.threads), and the batch limit drops to 1 when results feed parallel--execreceivers, "to evenly distribute work" (extras/fd/src/walk.rs,BatchSender::sendandspawn_senders). -
Two-mode output buffering as a tiny state machine.
ReceiverBuffer<'a, W: Write>starts inBuffering(so fast searches print sorted) and flips toStreamingon a deadline viarx.recv_deadline(self.deadline); the mode enum plusstream()/stop()transitions make the policy explicit (extras/fd/src/walk.rs). Being generic overW: Writekeeps it unit-testable and lets production passBufWriter<StdoutLock>. -
Cooperative cancellation with atomics and a double Ctrl-C escape hatch (extras/fd/src/walk.rs):
ctrlc::set_handler(move || { quit_flag.store(true, Ordering::Relaxed); if interrupt_flag.fetch_or(true, Ordering::Relaxed) { // Ctrl-C has been pressed twice, exit NOW ExitCode::KilledBySigint.exit(); } })
Relaxed ordering is correct here because the flags are pure signals with no dependent data, and the code does not pretend otherwise.
-
The clap negating-flags pattern. Every boolean flag gets a hidden opposite whose field type is the unit type, so it occupies no state but participates in
overrides_withresolution; combined withargs_override_self = true, "last flag wins" works for scripts and aliases (extras/fd/src/cli.rs):/// Overrides --hidden #[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)] no_hidden: (),
The same file drops down from derive to the imperative API exactly where derive cannot express the requirement, implementing
clap::FromArgMatchesandclap::Argsby hand for the--execgroup because "there isn't a derive api for getting grouped values yet". -
Semantic analysis of user regexes via
regex-syntaxHIR. Smart-case does not naively scan the pattern string for uppercase; it parses the pattern and recursively walks the HIR so\Acargoandcarg\x6Fare correctly judged lowercase (extras/fd/src/regex_helper.rs):HirKind::Capture(Capture { sub, .. }) | HirKind::Repetition(Repetition { sub, .. }) => { hir_has_uppercase_char(sub) } HirKind::Concat(hirs) | HirKind::Alternation(hirs) => { hirs.iter().any(hir_has_uppercase_char) }
-
A one-unsafe-block policy. The only
unsafeinsrc/is the POSIX-mandated dance of restoring the default SIGINT handler and re-raising, in extras/fd/src/exit_codes.rs; everything else, including all path and byte handling, is safe code. -
Platform handling as paired total functions rather than scattered cfg blocks:
is_socket,is_pipe,is_block_device, andosstr_to_byteseach have a Unix and a Windows definition with identical signatures (extras/fd/src/filesystem.rs), so call sites contain zero conditional compilation. Where cfg must appear inline, it is expression-level and justified, like the jemalloc#[global_allocator]gate in extras/fd/src/main.rs that mirrors Cargo.toml. -
Edition 2024 let-chains used for flat control flow throughout, for example (extras/fd/src/walk.rs):
if let Some(max_results) = self.config.max_results && self.num_results >= max_results { return self.stop(); }
-
Micro-attention where it matters:
#[cold]on the completions printer (extras/fd/src/main.rs),#[inline]on comparison impls and tiny accessors (extras/fd/src/dir_entry.rs),NonZeroUsizefor the thread count withavailable_parallelism().min(64)capping startup overhead (extras/fd/src/cli.rs), and byte-regexes (regex::bytes) end to end so non-UTF-8 filenames are first-class. -
Security-minded output: extras/fd/src/sanitize.rs escapes C0/C1 controls, bidi overrides, and zero-width characters only when stdout is a TTY, with unit tests named after the attacks they block (
strips_osc52_clipboard_payload,strips_bidi_overrides_and_zero_width), while extras/fd/src/output.rs still writes raw bytes to pipes so downstream tools receive filenames intact.
- Rustdoc is used for maintainers, not for docs.rs (a binary crate has no API consumers): every
Configfield has a///line (extras/fd/src/config.rs), non-obvious functions carry doc comments that explain rationale and link issues (the 20-line comment onensure_search_pattern_is_not_a_pathin extras/fd/src/main.rs reads like a design note), and extras/fd/src/sanitize.rs opens with a//!module doc: "TTY-output sanitization to prevent terminal escape injection via filenames." - The user manual is the hand-maintained man page extras/fd/doc/fd.1 (587 lines of roff) plus a 800-line README with a troubleshooting section that the bug-report template points at. The README's help output is kept honest mechanically: extras/fd/scripts/update-help.awk re-runs
cargo run --release --quiet -- -hand splices the result into the README's fenced block. - extras/fd/CONTRIBUTING.md sets pull-request expectations, requires an entry in the "Upcoming release" section of the changelog with the exact format
- Short description of what has been changed, see #123 (@user), and asks contributors to open an issue before a PR. - extras/fd/SECURITY.md defines a private vulnerability-reporting path via GitHub advisories with explicit confidentiality expectations.
- Issue templates: extras/fd/.github/ISSUE_TEMPLATE/bug_report.yaml is a structured GitHub form with a required checkbox ("I have read the troubleshooting section and still think this is a bug"), a required version input, and a required OS textarea rendered as shell; feature requests and questions get lighter Markdown templates, and config.yml keeps blank issues enabled. There is no PR template; CONTRIBUTING carries that weight.
- There is no ARCHITECTURE.md; at 5k lines the module names and doc comments are the architecture document.
Versioning is semver on the crate (10.4.2 at extras/fd/Cargo.toml), tags are vX.Y.Z, and the changelog is the source of release notes. extras/fd/CHANGELOG.md keeps a permanent # Unreleased section with ## Features, ## Bugfixes, ## Changes, ## Other subsections; every entry credits the contributor and cites the issue or PR number. MSRV bumps are announced as changelog entries ("Minimum required rust version has been increased to 1.90.0").
The release process is a documented checklist plus scripts:
- extras/fd/doc/release-checklist.md is a copy-pasteable checklist covering version bump, README/MSRV sync,
cargo publish --dry-run, tagging, verifying binary deployment, and post-release changelog scaffolding. - extras/fd/scripts/version-bump.sh automates the mechanical part: creates a
release-$versionbranch, seds the version into Cargo.toml, updates the MSRV note in the README, and renames the changelog heading. - Pushing the tag triggers the CD half of extras/fd/.github/workflows/CICD.yml: 14 target archives (tar.gz/zip with binary, man page, completions, licenses, changelog inside), Debian packages from extras/fd/scripts/create-deb.sh (including musl variants with correct
Conflicts:metadata andfdfindalias symlinks for Debian), provenance attestation via actions/attest, upload to the GitHub release, and winget publication.
Completions and man page distribution is handled by the extras/fd/Makefile: generated completions come from the binary itself ($(EXE) --gen-completions bash > $@), the zsh completion is a hand-written file copied from extras/fd/contrib/completion/_fd, and make install places binary, completions for bash/fish/zsh, and the man page into FHS paths. Runtime generation is also a user feature: fd --gen-completions <shell> works on any installed binary because clap_complete ships in the default completions feature. Finally, the binstall metadata in Cargo.toml (section 3) makes cargo binstall a first-class install path.
quinjet already exceeds fd on lint strictness, cargo-deny, typos, coverage, miri, and mutants. What fd still teaches, with exact mechanisms:
- Declare and enforce an MSRV from one source of truth. Add
rust-version = "..."to Cargo.toml, then add a CI job pair modeled on fd's: acrate_metadatajob that runscargo metadata --no-deps --format-version 1 | jq -r '"msrv=" + .packages[0].rust_version'into$GITHUB_OUTPUT, and amin_versionjob usingdtolnay/rust-toolchain@masterwithtoolchain: ${{ needs.crate_metadata.outputs.msrv }}runningcargo clippy --locked --all-targetsandcargo test --locked(extras/fd/.github/workflows/CICD.yml). - Harden workflows the fd way: top-level
permissions: contents: read,persist-credentials: falseon everyactions/checkout, per-job permission escalation only where needed, and every third-party action pinned to a full commit SHA with a# vX.Y.Zcomment (extras/fd/.github/workflows/CICD.yml). - Add
cooldown: default-days: 7to dependabot for both thecargoandgithub-actionsecosystems so freshly published releases age before being proposed (extras/fd/.github/dependabot.yml). - Build a
TestEnv-style black-box harness for the CLI surface: locate the binary withenv!("CARGO_BIN_EXE_quinjet"), construct a real temporary Git repository fixture withtempfile::Builder::new().prefix(...), isolate environment variables per invocation, normalize output before comparing, and render failures as unified diffs with thediffcrate (extras/fd/tests/testenv/mod.rs). Since every quinjet operation is a subcommand, every operation can be asserted end to end on stdout, stderr, and exit status exactly as extras/fd/tests/tests.rs does. - Adopt the
test-casecrate for flag and alias matrices, especially an equivalent of fd'stest_opposingproving that each overriding option exactly cancels its counterpart (extras/fd/tests/tests.rs lines 2674 onward). - Model process exit as an enum with
impl From<ExitCode> for i32, amerge_exitcodesfold, and 130 for SIGINT death, instead of scattering integer literals (extras/fd/src/exit_codes.rs). For a Git tool, distinct documented codes for "conflict", "nothing to do", and "user abort" pay off in scripts. - Sanitize terminal-bound output. Git data (branch names, commit subjects, remote URLs) is attacker-influenced text; port the
needs_escape/maybe_sanitizeapproach that escapes controls, bidi overrides, and zero-width characters only when the stream is a TTY, with attack-named unit tests (extras/fd/src/sanitize.rs). This matters for quinjet's plain CLI output path even more than for the ratatui path. - Tune profiles for iteration speed:
[profile.dev] debug = "line-tables-only",[profile.dev.package."*"] debug = false, plus a[profile.debugging]that inherits dev with full debug info, and a release profile withlto = true,strip = true,codegen-units = 1(extras/fd/Cargo.toml). - Ship completions and a man page from the binary itself: put
clap_completebehind a defaultcompletionsfeature with a hidden--gen-completionsflag (extras/fd/src/cli.rs, extras/fd/src/main.rs), and add Makefile targets that generate and install them (extras/fd/Makefile). Considerclap_mangenfor the man page since quinjet has no hand-written roff to preserve. - Add
[package.metadata.binstall]with the pkg-url template matching the release artifact naming socargo binstall quinjetworks from day one (extras/fd/Cargo.toml). - Automate releases off tags: a matrix build job that packages binary plus completions plus docs per target, attests artifacts with
actions/attestunderid-token: writeandattestations: write, and uploads with a SHA-pinnedsoftprops/action-gh-release, all gated onrefs/tags/v[0-9](extras/fd/.github/workflows/CICD.yml). Keep adoc/release-checklist.mdand ascripts/version-bump.shfor the human steps. - Keep the changelog contributor-facing: a permanent Unreleased section with fixed subsections, entries of the form
- description, see #123 (@user), and a CONTRIBUTING.md that makes the entry part of the definition of done (extras/fd/CHANGELOG.md, extras/fd/CONTRIBUTING.md). - Convert bug reports into structured YAML issue forms with a required version field and a required "I read the troubleshooting docs" checkbox (extras/fd/.github/ISSUE_TEMPLATE/bug_report.yaml).
- Mechanically sync
--helpoutput into the README with a small script run at release time, as extras/fd/scripts/update-help.awk does, so documentation of the command surface can never drift from clap. - When an override of a strict lint is unavoidable, follow fd's one-allow discipline: smallest possible scope, always paired with a comment explaining the measured or reasoned tradeoff (extras/fd/src/walk.rs
WorkerResult).
Nushell is a cross-platform shell and programming language in which every pipeline carries
structured data (records, tables, streams) instead of raw text. Industry uses it as a daily
driver shell, as a scripting language for CI and data plumbing, and as an embeddable engine:
the workspace exposes the parser, evaluator, and value model as separately published crates
(nu-parser, nu-engine, nu-protocol), and a stable plugin protocol lets third parties
ship out-of-process commands. The root manifest states the intent plainly
(extras/nushell/Cargo.toml):
description = "A new type of shell"
documentation = "https://www.nushell.sh/book/"
name = "nu"Scale indicators measured directly from the clone (commit 3876934, 2026-08-15):
- 1,852
.rsfiles totaling about 418,000 lines of Rust text (wc -lover all sources). - 46 directories under extras/nushell/crates; 41 crates are explicit workspace members in
extras/nushell/Cargo.toml, and
nu-globandnu-pathjoin the workspace implicitly as path dependencies. - Two additional cargo-fuzz crates deliberately opt out of the workspace (extras/nushell/crates/nu-parser/fuzz, extras/nushell/crates/nu-path/fuzz).
- Three non-Rust reference plugins document the wire protocol in other languages (extras/nushell/crates/nu_plugin_python, nu_plugin_javascript, nu_plugin_nu_example).
- Workspace-wide version
0.115.0, edition 2024,rust-version = "1.95.0". - 304 Rust files under
crates/*/tests/, 256 of them innu-commandalone.
extras/nushell/
|-- Cargo.toml workspace root AND the `nu` binary package
|-- rust-toolchain.toml pinned channel with MSRV policy explained in comments
|-- rustfmt.toml one line: edition
|-- clippy.toml unwrap-in-tests + disallowed-types
|-- typos.toml spell-check config with TUI-artifact ignores
|-- sgconfig.yml ast-grep project file (custom structural lints)
|-- toolkit.nu entry point for the contributor toolkit
|-- toolkit/ fmt/clippy/test/coverage/package commands, git hooks
|-- ast-grep/ rules/, utils/, tests/ with __snapshots__
|-- benches/ tango-bench benchmark suite
|-- crates/ 41+ member crates: nu-* libraries, nu_plugin_* plugins
|-- devdocs/ rust_style.md, FAQ.md, HOWTOS.md, PLATFORM_SUPPORT.md
|-- docker/ Dockerfiles and a docker test script
|-- scripts/ build.rs, coverage, cross-build helpers, nix
|-- src/ the thin `nu` binary (main.rs, run.rs, signals.rs, ...)
|-- tests/ end-to-end suite for the `nu` binary
|-- wix/ Windows MSI packaging (WiX), terminal profile
|-- .githooks/ pre-commit (fmt), pre-push (fmt + clippy)
`-- .github/ workflows, dependabot, issue/PR templates, labeler
The split works because the root package is only glue: src/main.rs wires the crates
together and everything of substance lives in a purpose-scoped crate. The taxonomy is
written down in extras/nushell/crates/README.md:
Foundational libraries are split into two kinds of crates:
* Core crates - those crates that work together to build the Nushell language engine
* Support crates - a set of crates that support the engine with additional features
Naming carries meaning: nu-* (hyphen) is a library, nu_plugin_* (underscore) is an
executable plugin, and testbins holds tiny helper binaries used only by tests
(extras/nushell/crates/testbins/Cargo.toml sets publish = false).
The root extras/nushell/Cargo.toml is a model of workspace.package inheritance. Shared
fields are declared once and every crate pulls them:
[workspace.package]
authors = ["The Nushell Project Developers"]
edition = "2024"
rust-version = "1.95.0"
license = "MIT"
version = "0.115.0"Every member (see extras/nushell/crates/nu-protocol/Cargo.toml) repeats only
authors.workspace = true, edition.workspace = true, etc. All 34 library crates also
contain a two-line [lints] table pointing at the workspace definition.
Notable manifest practices, all in extras/nushell/Cargo.toml:
- Every internal crate appears in
[workspace.dependencies]withpath, an explicitversion = "0.115.0", anddefault-features = false, so crates compose features explicitly and publishing to crates.io works from the same manifest. - External dependencies are centralized and alphabetized; member manifests say only
thiserror = { workspace = true }. - Version pins carry rationale as comments. The TLS stack is held to a tilde range:
# We have to semi-fix rustls and ureq versions
# because we use unversioned api to allow users set up their own
# crypto providers (grep for "unversioned").
# Patch updates are allowed though.
rustls = { version = "~0.23.38", default-features = false, features = ["std", "tls12"] }and exact pins like trash = "=5.2.6" and fff-search = { version = "=0.10.3", ... }
mark crates where any drift is known to break behavior.
- Feature design is layered: a
defaultset, astable = ["default"]alias, and afullset documented as "Enable all features while still avoiding mutually exclusive features. Use this if--all-featuresfails." Thepluginfeature fans out withdep:syntax across nine crates, keeping optional dependencies invisible unless enabled. - Mutually exclusive TLS backends (
rustls-tlsvsnative-tls) are not just documented, they are machine-checked by cargo-hack in CI (section 6). - Profiles:
[profile.release]usesopt-level = "s",strip = "debuginfo", andlto = "thin"(a shell must start fast and stay small); aprofilingprofile inherits release withdebug = trueforperf; aciprofile inherits dev withdebug = falseto shrink test artifacts. -
autotests = falseplus an explicit[[test]] harness = falseblock routes all integration tests through one custom-harness binary (section 7). The lib and bin setbench = falsesocargo benchonly sees the tango harness. -
[package.metadata.binstall]teachescargo binstallthe release-asset URL scheme, and[package.metadata.winresource]embeds Windows file metadata. - An empty commented
[patch.crates-io]section is kept on purpose: "To use a development version of a dependency please use a global override here".
MSRV policy lives in extras/nushell/rust-toolchain.toml as prose next to the pin:
# The current plan is to be 2 releases behind the latest stable release.
channel = "1.95.0"and CI enforces that this file and workspace.package.rust-version never drift, using a
nushell script (extras/nushell/.github/workflows/check-msrv.nu) that opens both TOML files
and exits 1 on mismatch.
extras/nushell/rustfmt.toml is a single line:
edition = "2024"The project deliberately runs stock rustfmt with zero styling opinions, which removes all
formatting debate and guarantees any contributor's editor produces identical output. It is
enforced three times: locally via toolkit fmt, at commit time by
extras/nushell/.githooks/pre-commit (fmt --check --verbose), and in CI by
cargo fmt --all --check (extras/nushell/.github/workflows/ci.yml).
There is no .editorconfig in the repository (verified by listing the root). Non-Rust
hygiene is handled by typos instead of a formatter: extras/nushell/typos.toml excludes
fixture-heavy paths and uses regex ignores for strings that only look like typos, such as
box-drawing fragments from table output:
extend-ignore-re = [
"Plasticos Rival",
"│ in_custom_valu │",
"([0-9a-f][0-9a-f] ){4}",
]This is the correct tool split for a project whose test fixtures contain deliberately mangled text.
Lint policy lives in three cooperating places.
First, [workspace.lints] in extras/nushell/Cargo.toml, inherited by all 34 crates that
declare [lints] workspace = true:
[workspace.lints.clippy]
# Warning: workspace lints affect library code as well as tests, so don't enable lints that would be too noisy in tests like that.
format_push_string = "warn"
needless_raw_strings = "warn"
result_large_err = "allow"
unchecked_time_subtraction = "deny"
unwrap_used = "deny"
used_underscore_binding = "warn"The list is short and every deviation is annotated: collapsible_match is allowed with a
link to a rustc issue and a planned removal version, and filter_map_identity is allowed
with a performance rationale. unexpected_cfgs is configured with
check-cfg = ["cfg(ci)"] so the custom --cfg ci flag (section 6) stays legal.
Second, extras/nushell/clippy.toml softens the wall exactly where it should and hardens it where clippy cannot reach by default:
allow-unwrap-in-tests = true
[[disallowed-types]]
path = "std::time::Instant"
reason = "WASM panics if used, use instead"
replacement = "nu_utils::time::Instant"disallowed-types turns an architectural decision (WASM support) into a compiler error
with a suggested replacement. The one legitimate use site opts out with a reasoned allow
(extras/nushell/crates/nu-utils/src/time.rs):
#![allow(
clippy::disallowed_types,
reason = "only allow std::time::Instant here when it's not WASM"
)]Third, severity is escalated at invocation time rather than in the manifest. CI exports
CLIPPY_OPTIONS: "-D warnings" (extras/nushell/.github/workflows/ci.yml) and the local
aliases in extras/nushell/.cargo/config.toml mirror it, with a softer profile for tests:
nuclippy = "clippy --workspace --exclude nu_plugin_* --profile ci --all-targets -- -D warnings -D clippy::unwrap_used -D clippy::unchecked_time_subtraction"
# Clippy just for tests
nuclippy-tests = "clippy --workspace --tests --exclude nu_plugin_* --profile ci --all-targets -- -D warnings -D clippy::unchecked_time_subtraction"The philosophy behind the wall is written down in extras/nushell/devdocs/rust_style.md:
conservative reliance on clippy, an outright ban on .unwrap() outside tests, panics
disallowed for anything reachable from user input, nightly features prohibited, and custom
macros discouraged unless they beat functions on readability and compile time.
Beyond clippy, nushell maintains custom structural lints with ast-grep. extras/nushell/sgconfig.yml points at extras/nushell/ast-grep/rules, where each rule is a small YAML program with a severity, an explanation, and often an autofix. Example (extras/nushell/ast-grep/rules/internal_span.yml):
id: internal_span
severity: error
message: "Using `internal_span` directly is deprecated."
note: "You can get the span using the `Value::span()` method."The if-matches rule even rewrites if matches!(v, pat) into if let pat = v via
fix: "let $$$PAT = $VAL", and the rules themselves have snapshot tests under
extras/nushell/ast-grep/tests/__snapshots__. This is lint infrastructure as reviewable,
tested code.
All CI lives in extras/nushell/.github/workflows (12 files, 1,061 lines total).
ci.yml is the gate. Triggers: pull_request, pushes to main and patch-release-*,
plus pull_request_target on ready_for_review. Global permissions: contents: read
and a concurrency group with cancel-in-progress: true cap cost and token power. Draft
PRs and lower layers of stacked PRs are skipped with a job-level if on
github.event.pull_request.draft and pull_request.stack.position.
The heart is a two-dimensional matrix: targets (Ubuntu 22.04, Windows, macOS, and
wasm32-unknown-unknown) crossed with workspaces (the root plus both fuzz crates), where
each cell declares which steps apply:
- name: Ubuntu
host: ubuntu-22.04
target: x86_64-unknown-linux-gnu
options: MAIN_OPTIONS
steps: [fmt, clippy, build, test, doctest]
- name: WASM
host: ubuntu-22.04
target: wasm32-unknown-unknown
options: WASM_OPTIONS
steps: [build, check]Each step then guards itself with if: contains(matrix.target.steps, 'fmt') && ..., so one
job template serves every combination, including clippy on the fuzz crates that are outside
the workspace. Details worth stealing:
- Ubuntu is pinned to 22.04 with an inline comment explaining glibc compatibility for released binaries and a revisit date (22.04 EOL, June 2027).
- Caching is
Swatinem/rust-cachewithcache-all-crates: trueand per-workspaceworkspaces: path -> targetmapping. - Every third-party action is pinned to a full commit SHA with the human version in a
comment, e.g.
actions/checkout@3d3c42e5aac5... # v7.0.1, and extras/nushell/.github/dependabot.yml updates thegithub-actionsecosystem weekly so pins do not rot. - Tests run with
--cfg ciinjected throughcargo --config .cargo/ci.toml(extras/nushell/.cargo/ci.toml), letting tests detect CI without env-var sniffing whileunexpected_cfgskeeps the cfg namespace honest. - The final step of every job is an anti-drift check:
Assert Clean Reporunsgit diff --quiet && git diff --cached --quiet, failing if any build step mutated the tree.
A second job in ci.yml installs the freshly built nu, runs the standard-library test
framework written in nushell itself (`nu -c 'use crates/nu-std/testing.nu; .
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