Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Full treewide Nix format and enforcement [skip treewide] #380990

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,6 @@ adb9714bd909df283c66bbd641bd631ff50a4260

# tmuxPlugins sha-to-sri.py script
516b1e74c358a9c4b06e5591f8c1a2897aad0c33

# treewide format of all Nix files
c3824f43826f44817bc5178bd6780c1e0c49d096 # !autorebase nix-shell --run treefmt
82 changes: 13 additions & 69 deletions .github/workflows/check-nix-format.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# This file was copied mostly from check-maintainers-sorted.yaml.
# NOTE: Formatting with the RFC-style nixfmt command is not yet stable. See
# https://github.com/NixOS/rfcs/pull/166.
# Because of this, this action is not yet enabled for all files -- only for
# those who have opted in.
# NOTE: Formatting with the RFC-style nixfmt command is not yet stable.
# See https://github.com/NixOS/rfcs/pull/166.

name: Check that Nix files are formatted

Expand All @@ -20,80 +17,27 @@ jobs:
name: nixfmt-check
runs-on: ubuntu-24.04
needs: get-merge-commit
if: "needs.get-merge-commit.outputs.mergedSha && !contains(github.event.pull_request.title, '[skip treewide]')"
if: needs.get-merge-commit.outputs.mergedSha
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ needs.get-merge-commit.outputs.mergedSha }}
# Fetches the merge commit and its parents
fetch-depth: 2

- name: Checking out target branch
run: |
target=$(mktemp -d)
targetRev=$(git rev-parse HEAD^1)
git worktree add "$target" "$targetRev"
echo "targetRev=$targetRev" >> "$GITHUB_ENV"
echo "target=$target" >> "$GITHUB_ENV"

- name: Get Nixpkgs revision for nixfmt
run: |
# pin to a commit from nixpkgs-unstable to avoid e.g. building nixfmt
# from staging
# This should not be a URL, because it would allow PRs to run arbitrary code in CI!
rev=$(jq -r .rev ci/pinned-nixpkgs.json)
echo "url=https://github.com/NixOS/nixpkgs/archive/$rev.tar.gz" >> "$GITHUB_ENV"

- uses: cachix/install-nix-action@08dcb3a5e62fa31e2da3d490afc4176ef55ecd72 # v30
with:
extra_nix_config: sandbox = true
nix_path: nixpkgs=${{ env.url }}

- name: Install nixfmt
run: "nix-env -f '<nixpkgs>' -iAP nixfmt-rfc-style"

- name: Check that Nix files are formatted according to the RFC style
- name: Check that Nix files are formatted
run: |
unformattedFiles=()

# TODO: Make this more parallel

# Loop through all Nix files touched by the PR
while readarray -d '' -n 2 entry && (( ${#entry[@]} != 0 )); do
type=${entry[0]}
file=${entry[1]}
case $type in
A*)
source=""
dest=$file
;;
M*)
source=$file
dest=$file
;;
C*|R*)
source=$file
read -r -d '' dest
;;
*)
echo "Ignoring file $file with type $type"
continue
esac

# Ignore files that weren't already formatted
if [[ -n "$source" ]] && ! nixfmt --check ${{ env.target }}/"$source" 2>/dev/null; then
echo "Ignoring file $file because it's not formatted in the target commit"
elif ! nixfmt --check "$dest"; then
unformattedFiles+=("$dest")
fi
done < <(git diff -z --name-status ${{ env.targetRev }} -- '*.nix')

if (( "${#unformattedFiles[@]}" > 0 )); then
echo "Some new/changed Nix files are not properly formatted"
echo "Please format them using the Nixpkgs-specific \`nixfmt\` by going to the Nixpkgs root directory, running \`nix-shell\`, then:"
echo
echo "nixfmt ${unformattedFiles[*]@Q}"
echo
# Note that it's fine to run this on untrusted code because:
# - There's no secrets accessible here
# - The build is sandboxed
if ! nix-build ci -A fmt.check; then
echo "Some Nix files are not properly formatted"
echo "Please format them by going to the Nixpkgs root directory and running one of:"
echo " nix-shell --run treefmt"
echo " nix develop --command treefmt"
echo " nix fmt"
echo "Make sure your branch is up to date with master; rebase if not."
echo "If you're having trouble, please ping @NixOS/nix-formatting"
exit 1
Expand Down
21 changes: 19 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -531,14 +531,31 @@ If you removed packages or made some major NixOS changes, write about it in the

Names of files and directories should be in lowercase, with dashes between words — not in camel case. For instance, it should be `all-packages.nix`, not `allPackages.nix` or `AllPackages.nix`.

### Formatting

CI [enforces](./.github/workflows/check-nix-format.yml) all Nix files to be
formatted using the [official Nix formatter](https://github.com/NixOS/nixfmt).

You can ensure this locally using either of these commands:
```
nix-shell --run treefmt
nix develop --command treefmt
nix fmt
```

If you're starting your editor in `nix-shell` or `nix develop`,
you can also set it up to automatically format the file with `nixfmt` or `treefmt` on save.

If you have any problems with formatting, please ping the
[formatting team](https://nixos.org/community/teams/formatting/) via
[@NixOS/nix-formatting](https://github.com/orgs/NixOS/teams/nix-formatting).

### Syntax

- Set up [editorconfig](https://editorconfig.org/) for your editor, such that [the settings](./.editorconfig) are automatically applied.

- Use `lowerCamelCase` for variable names, not `UpperCamelCase`. Note, this rule does not apply to package attribute names, which instead follow the rules in [package naming](./pkgs/README.md#package-naming).

- New files must be formatted by entering the `nix-shell` from the repository root and running `nixfmt`.

- Functions should list their expected arguments as precisely as possible. That is, write

```nix
Expand Down
45 changes: 44 additions & 1 deletion ci/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,52 @@ let
config = { };
overlays = [ ];
};

fmt =
let
treefmtNixSrc = fetchTarball {
# Master at 2025-02-12
url = "https://github.com/numtide/treefmt-nix/archive/4f09b473c936d41582dd744e19f34ec27592c5fd.tar.gz";
sha256 = "051vh6raskrxw5k6jncm8zbk9fhbzgm1gxpq9gm5xw1b6wgbgcna";
};
treefmtEval = (import treefmtNixSrc).evalModule pkgs {
# Important: The auto-rebase script uses `git filter-branch --tree-filter`,
# which creates trees within the Git repository under `.git-rewrite/t`,
# notably without having a `.git` themselves.
# So if this projectRootFile were the default `.git/config`,
# having the auto-rebase script use treefmt on such a tree would make it
# format all files in the _parent_ Git tree as well.
projectRootFile = ".git-blame-ignore-revs";

# Be a bit more verbose by default, so we can see progress happening
settings.verbose = 1;

# By default it's info, which is too noisy since we have many unmatched files
settings.on-unmatched = "debug";

# This uses nixfmt-rfc-style underneath,
# the default formatter for Nix code.
# See https://github.com/NixOS/nixfmt
programs.nixfmt.enable = true;
};
fs = pkgs.lib.fileset;
nixFilesSrc = fs.toSource {
root = ../.;
fileset = fs.difference (fs.unions [
(fs.fileFilter (file: file.hasExt "nix") ../.)
../.git-blame-ignore-revs
]) (fs.maybeMissing ../.git);
};
in
{
shell = treefmtEval.config.build.devShell;
pkg = treefmtEval.config.build.wrapper;
check = treefmtEval.config.build.check nixFilesSrc;
};

in
{
inherit pkgs;
inherit pkgs fmt;
requestReviews = pkgs.callPackage ./request-reviews { };
codeownersValidator = pkgs.callPackage ./codeowners-validator { };
eval = pkgs.callPackage ./eval { };
Expand Down
Loading