nix-style
Nix code style, general and mechanical: a design and idiom checklist for new code, plus the rules enforced by astlog and lint (no with/rec/mkForce, derivation hygiene, typed options, fetchers, licenses). Use when writing or reviewing Nix, or fixing a lint failure.
- License 许可
- MIT
- 最近更新
- 2026-08-05
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- nix-style
- description
- Nix code style, general and mechanical: a design and idiom checklist for new code, plus the rules enforced by astlog and lint (no with/rec/mkForce, derivation hygiene, typed options, fetchers, licenses). Use when writing or reviewing Nix, or fixing a lint failure.
03 SKILL.md 正文
Adding a new Nix thing
Craft-standard governs ownership, DRY, layering, consumers, and not being defensive. The Nix-specific checks on top:
- Functional over imperative: index-driven iteration (
imap0,lib.range,elemAt) usually means a missingmap,genList, or higher-level combinator. - Reuse
builtinsandnixpkgs.libbefore hand-rolling; an experienced Nix reader should have no complaints on first read. - Reify latent structure, parse rather than validate, and leave room for future needs in the design without writing dead code.
Nix style (astlog enforced)
Run the repo's pinned lint before committing: nix run .#lint in index and
just lint in ix. It runs
alejandra, Statix, Deadnix, and the repo's astlog rules (astlog-rules/nix.astlog for Nix and
astlog-rules/rust.astlog for the corpus/search Rust crates, both gated with
astlog scan). The lint app is the mechanical source of truth. A legitimate exception to an astlog rule is suppressed in
place with an # astlog-ignore: <rule> comment on the finding's line or the
line above it, with a comment naming the reason. The common hard rules are:
Scope / access
- No
with pkgs;/with lib;/with builtins;. Useinherit (pkgs) ...orlib.foodirectly. - No
pkgs.lib.X. Bindlibin the function signature (orinherit (pkgs) lib;once at the top of alet) and uselib.fooeverywhere. - No
rec { }and nolet { ... }legacy form. Uselet ... inorfinalAttrs:for mkDerivation self-reference. - No
mkForceand nomkOverride <int>back-door. Fix the module boundary or composemkDefault/mkOptionDefault/mkBefore/mkAfter. - No
lib.recursiveUpdate. Build the attrset in one place or uselib.mkMerge. - No
{ } // X/X // { }attrset updates with an empty operand. - No
mkMerge [ x ]single-element wrappers; drop the wrapper. - No repeated parent keys in the same attrset. Group related assignments under one parent.
- Prefer
inherit (source) name;for direct same-name field copies.
Eval and source paths
- No
builtins.currentSystem,builtins.getEnv,<nixpkgs>, orpath:flake refs. Nobuiltins.getFlake (toString ./...). - No
(import ./foo.nix)insideimports = [ ... ]; NixOS auto-imports paths. - No
..paths insidemodules/; shared helpers come throughspecialArgs.ix. builtins.path { path = ./.; }must setname = "<stable>"so the store path is reproducible across clones.- Prefer
lib.fileset.toSourceoverlib.cleanSource/lib.sources.cleanSourceWith. - Do not interpolate a repository-root binding such as
root,workspaceRoot, orix.paths.root. Select the file or subtree with path concatenation before interpolation so derivations do not depend on the whole repository.
Migration / deprecated APIs
- No
lib.mdDoc/lib.options.mdDoc/ baremdDoc. Pass plain Markdown. - No
substituteAll/substituteAllFiles(removed from nixpkgs). Usepkgs.replaceVars/replaceVarsWith. - No
cargoSha256(usecargoHashorcargoLock), novendorSha256(usevendorHash), nonpmDepsSha256(usenpmDepsHash).pnpmDepsHashis the current name on the pnpm side and is not flagged. - No bare
buildRustPackage; usepkgs.rustPlatform.buildRustPackageorcrane.buildPackage. - No
flake-utils.lib.eachSystem; we hand-roll per-system inlib/per-system.nix.
Idioms (mechanical)
- Use
lib.importJSON path/lib.importTOML pathinstead ofbuiltins.fromJSON (builtins.readFile path). - Use
(pkgs.formats.json { }).generate "name" valueinstead ofpkgs.writeText "name" (builtins.toJSON value). - Use
lib.optional cond x(singular) when the conditional yields one element; reservelib.optionals cond xs(plural) for actual lists. - Use
lib.genAttrs keys finstead oflib.listToAttrs (map (n: { name = n; value = f n; }) keys). - Use
builtins.attrValues Xinstead oflib.mapAttrsToList (_: v: v) X. - Use
lib.genAttrs (lib.attrNames X) (_: v)instead oflib.mapAttrs (_: _: v) Xwhen both arguments are discarded. - Use
xs == [ ]/xs != [ ]instead ofbuiltins.length xs == 0/> 0. - No
!true/!falseliterals; write the inverse literal directly. - No
mkIf true x/lib.optional true x; constant conditions on these helpers are refactor leftovers. - No
name = "${pname}-${version}"restatement; stdenv constructsnamefrompname+version. (Usepname+versioninstead of a single dashednameso updaters andmetarendering can parse the version.) - Wrap dynamic attrpath antiquotes:
legacyPackages."${system}", notlegacyPackages.${system}.
Derivations / mkDerivation
- Set
strictDeps = trueon everymkDerivation. - No
fixupPhase = ...override; usepreFixup/postFixup. Same idea forbuildPhase/installPhase— do not restate the stdenv defaults. configureFlags/cmakeFlags/mesonFlags/makeFlags/ninjaFlagsare lists of strings; never one string with spaces.
Types and options
- No
types.attrs/lib.types.attrs/types.unspecifiedfor public options. Use a typedsubmodulewithfreeformType = (pkgs.formats.<x> {}).type, or an explicitoneOf/attrsOf <type>. mkOption.defaultshould be a self-contained expression. Conditional defaults that branch on sibling cfg belong inconfig = ...withmkDefault.
Hashes / licenses / fetchers
- Keep raw fetched data artifact URLs out of
flake.nix. - Use
pkgs.*fetchers instead ofbuiltins.fetch*. Put the hash in the SRIhashslot (hash = "sha256-...="), never a legacysha256 = ...attr. The fetchersha256ban and the removedcargoSha256/vendorSha256/npmDepsSha256builder attrs are one rule (prefer-sri-hash, error). The only exception is a hex digest that must round-trip verbatim (e.g. a Cargo.lock checksum fed back into.cargo-checksum.json, which cargo verifies as hex): keep it onsha256and add a# astlog-ignore: prefer-sri-hashcomment naming the reason. - Commit real hashes, never fake hash helpers or placeholders.
meta.licenseshould referencelib.licenses.<id>, never a raw SPDX string. The baregpl2/gpl3/lgpl2/lgpl3/agpl3aliases are banned by lint — pick the explicit*Only/*Plusflavor (agpl3Plus, notgpl3Plus, when the upstream is AGPL).
Errors and warnings
- No bare
assert cond;. Useassert lib.assertMsg cond "...";. - No
abort. Preferthrow "ix.<area>: ..."(catchable) orlib.assertMsgfor invariants.throw ""is the same shape as a bare assert and is rejected. - No leftover
builtins.trace/lib.traceVal/lib.traceSeqin tracked code.
Build / configuration outputs
- No
writeShellApplicationorwriteShellScriptBinfor user-facing commands. - No unused bindings. Use
_for intentionally unused lambda arguments. - Use
nixosModules.<name>for module exports. Avoid a flat top-levelmodulesoutput. - Keep image targets at
x86_64-linux. - Use structured config options for new modules instead of stringly config fragments.
04 同仓库更多 Skills
pdf-processing
Extract text and tables from PDF files
git-release
Create consistent releases and changelogs
data-analysis
Help analyze datasets and results
release-notes
Draft release notes from commits and merged pull requests.
data-analysis
Summarize structured outputs and highlight regressions.
skill-one
Example skill for tests.