nixpkgs mirror (for testing)
github.com/NixOS/nixpkgs
nix
1{
2 lib,
3 runCommand,
4 testers,
5 treefmt,
6 nixfmt,
7}:
8let
9 inherit (treefmt) buildConfig withConfig;
10
11 testEqualContents =
12 args:
13 testers.testEqualContents (
14 args
15 // lib.optionalAttrs (builtins.isString args.expected) {
16 expected = builtins.toFile "expected" args.expected;
17 }
18 );
19
20 nixfmtExampleConfig = {
21 on-unmatched = "info";
22 tree-root-file = ".git/index";
23
24 formatter.nixfmt = {
25 command = "nixfmt";
26 includes = [ "*.nix" ];
27 };
28 };
29
30 nixfmtExamplePackage = withConfig {
31 settings = nixfmtExampleConfig;
32 runtimeInputs = [ nixfmt ];
33 };
34in
35{
36 buildConfigEmpty = testEqualContents {
37 assertion = "`buildConfig { }` builds an empty config file";
38 actual = buildConfig { };
39 expected = "";
40 };
41
42 buildConfigExample = testEqualContents {
43 assertion = "`buildConfig` builds the example config";
44 actual = buildConfig nixfmtExampleConfig;
45 expected = ''
46 on-unmatched = "info"
47 tree-root-file = ".git/index"
48
49 [formatter.nixfmt]
50 command = "nixfmt"
51 includes = ["*.nix"]
52 '';
53 };
54
55 buildConfigModules = testEqualContents {
56 assertion = "`buildConfig` evaluates modules to build a config";
57 actual = buildConfig [
58 nixfmtExampleConfig
59 { tree-root-file = lib.mkForce "overridden"; }
60 ];
61 expected = ''
62 on-unmatched = "info"
63 tree-root-file = "overridden"
64
65 [formatter.nixfmt]
66 command = "nixfmt"
67 includes = ["*.nix"]
68 '';
69 };
70
71 runNixfmtExample =
72 runCommand "run-nixfmt-example"
73 {
74 nativeBuildInputs = [ nixfmtExamplePackage ];
75 passAsFile = [
76 "input"
77 "expected"
78 ];
79 input = ''
80 {
81 foo="bar";
82 attrs={};
83 list=[];
84 }
85 '';
86 expected = ''
87 {
88 foo = "bar";
89 attrs = { };
90 list = [ ];
91 }
92 '';
93 }
94 ''
95 export XDG_CACHE_HOME=$(mktemp -d)
96 # The example config assumes the tree root has a .git/index file
97 mkdir .git && touch .git/index
98
99 # Copy the input file, then format it using the wrapped treefmt
100 cp $inputPath input.nix
101 treefmt
102
103 # Assert that input.nix now matches expected
104 if diff -u $expectedPath input.nix; then
105 touch $out
106 else
107 echo
108 echo "treefmt did not format input.nix as expected"
109 exit 1
110 fi
111 '';
112}