-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflake.nix
More file actions
409 lines (372 loc) · 14.5 KB
/
Copy pathflake.nix
File metadata and controls
409 lines (372 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
pyproject-nix = {
url = "github:pyproject-nix/pyproject.nix";
inputs.nixpkgs.follows = "nixpkgs";
};
uv2nix = {
url = "github:pyproject-nix/uv2nix";
inputs.pyproject-nix.follows = "pyproject-nix";
inputs.nixpkgs.follows = "nixpkgs";
};
pyproject-build-systems = {
url = "github:pyproject-nix/build-system-pkgs";
inputs.pyproject-nix.follows = "pyproject-nix";
inputs.uv2nix.follows = "uv2nix";
inputs.nixpkgs.follows = "nixpkgs";
};
git-hooks = {
url = "github:cachix/git-hooks.nix";
inputs.nixpkgs.follows = "nixpkgs";
};
nix2container = {
url = "github:nlewo/nix2container";
inputs.nixpkgs.follows = "nixpkgs";
};
systems.url = "github:nix-systems/default";
};
outputs =
{
self,
nixpkgs,
uv2nix,
git-hooks,
pyproject-nix,
pyproject-build-systems,
nix2container,
systems,
...
}:
let
inherit (nixpkgs) lib;
workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; };
pyprojectToml = lib.importTOML ./pyproject.toml;
hasRootProject = pyprojectToml ? project.name;
projectName =
if hasRootProject then
pyprojectToml.project.name
else
lib.warn "No [project] section in pyproject.toml — using \"workspace\" as project name for venv naming." "workspace";
projectVersion =
if pyprojectToml ? project.version then
pyprojectToml.project.version
else
self.shortRev or self.dirtyShortRev or "unknown";
# Combine requires-python constraints from uv.lock and pyproject.toml so that
# interpreter selection stays correct even when uv.lock is stale.
# For workspace roots without a [project] section, only the uv.lock constraint applies.
effectiveRequiresPython =
workspace.requires-python
++ lib.optionals (pyprojectToml ? project.requires-python) (
pyproject-nix.lib.pep440.parseVersionConds pyprojectToml.project.requires-python
);
# Load Python dependencies from uv workspace into a package overlay.
overlay = workspace.mkPyprojectOverlay {
# By default, we set the preference to `wheel`, letting most packages "just work".
# If you want to build everything from source, use `sdist`, but you will likely need
# to implement dependency fixups below.
sourcePreference = "wheel";
};
perSystem =
system:
let
pkgs = nixpkgs.legacyPackages."${system}";
# Select the lowest Python interpreter version that satisfies the combined constraints.
matchingInterpreters = pyproject-nix.lib.util.filterPythonInterpreters {
requires-python = effectiveRequiresPython;
inherit (pkgs) pythonInterpreters;
};
python =
if matchingInterpreters != [ ] then
lib.head matchingInterpreters
else
let
uvLockConstraint = (lib.importTOML ./uv.lock)."requires-python" or "(not set)";
pyprojectConstraint = pyprojectToml.project.requires-python or "(not set)";
in
throw ''
No Python interpreter in the flake's nixpkgs satisfies the requires-python constraints.
pyproject.toml: ${pyprojectConstraint}
uv.lock: ${uvLockConstraint}
If these constraints conflict, run `uv lock` to update the lockfile.
If both look correct, try `nix flake update nixpkgs` to get newer Python versions.
If uv lock fails due to a stale dev shell, try `rm uv.lock && uv lock` as a last resort.
'';
# This contains any build fixups needed for Python packages.
dependencyFixups = (
_final: _prev: {
# Implement project-specific build fixups for dependencies here.
# See https://pyproject-nix.github.io/uv2nix/patterns/patching-deps.html for details.
# Note that uv2nix is _not_ using Nixpkgs buildPythonPackage.
# It's using https://pyproject-nix.github.io/pyproject.nix/build.html
# If you need to build everything from sdists, you should consider reusing existing
# build system fixups, like https://github.com/TyberiusPrime/uv2nix_hammer_overrides
}
);
# Constuct complete Python package set based on workspace and overrides.
pythonSet =
(pkgs.callPackage pyproject-nix.build.packages {
inherit python;
}).overrideScope
(
lib.composeManyExtensions [
pyproject-build-systems.overlays.default
overlay
dependencyFixups
]
);
# Override previous Python set with an overlay to make the current package editable.
editablePythonSet = pythonSet.overrideScope (
lib.composeManyExtensions [
# Create an overlay enabling editable mode for all local dependencies.
(workspace.mkEditablePyprojectOverlay {
# Use environment variable that gets expanded in the .pth handler;
# not during flake evaluation.
root = "$REPO_ROOT";
})
# Editable-mode build fixup for workspace packages:
# Build systems (e.g. `hatchling`) have a dependency on the `editables` package.
# Currently in uv2nix, build-system dependencies have to be explicitly modeled.
(
final: prev:
lib.mapAttrs (
name: _:
prev.${name}.overrideAttrs (old: {
nativeBuildInputs =
old.nativeBuildInputs
++ final.resolveBuildSystem {
editables = [ ];
};
})
) workspace.deps.default
)
]
);
# Apply any fixups that apply at the virtualenv level, not to specific packages.
applyVirtualenvFixups =
env:
lib.pipe env [
# Ignore a configured list of colliding files (semi-common in namespace packages)
(
env:
env.overrideAttrs (old: {
venvIgnoreCollisions = [ ];
})
)
# Add a metadata element so that things like `nix run` point at the main script
(env: lib.addMetaAttrs { mainProgram = projectName; } env)
];
# Build the "release" virtualenv, used for `nix run` or container builds.
venvRelease = applyVirtualenvFixups (
pythonSet.mkVirtualEnv "${projectName}-env" workspace.deps.default
);
# Build the "development" virtualenv, used for `nix develop` and `direnv`.
venvDevelopment = applyVirtualenvFixups (
editablePythonSet.mkVirtualEnv "${projectName}-dev-env" workspace.deps.all
);
# dprint config generated in the nix store, using nix-packaged WASM plugins.
dprintConfig = (pkgs.formats.json { }).generate "dprint.json" {
plugins = pkgs.dprint-plugins.getPluginList (
plugins: with plugins; [
dprint-plugin-json
dprint-plugin-markdown
g-plane-pretty_yaml
]
);
};
# Build Sphinx documentation as a Nix output.
venvDoc = pythonSet.mkVirtualEnv "${projectName}-doc-env" workspace.deps.all;
doc = pkgs.runCommand "${projectName}-doc" { nativeBuildInputs = [ venvDoc ]; } ''
cp -r ${./.} source
chmod -R u+w source
sphinx-build source/docs $out/share/doc/${projectName}/html
'';
# Build an "application" per workspace member that only exposes application binaries.
memberApplications = lib.mapAttrs (
name: _:
(pkgs.callPackages pyproject-nix.build.util { }).mkApplication {
venv = venvRelease;
package = pythonSet.${name};
}
) workspace.deps.default;
# Build a container image per workspace member.
makeContainerTag =
name: pkg:
let
parts = lib.splitString "-" (lib.last (lib.splitString "/" pkg.outPath));
hash = builtins.head parts;
in
"${name}-${projectVersion}-${hash}";
memberContainers = lib.mapAttrs (
name: app:
nix2container.packages.${system}.nix2container.buildImage {
inherit name;
tag = makeContainerTag name app;
config = {
workingDir = app;
entrypoint = [ (lib.getExe app) ];
};
# gives a fair amount for one-package-per-layer but leaves some headroom from max of 127
maxLayers = 100;
}
) memberApplications;
in
{
packages =
memberApplications
// lib.mapAttrs' (name: value: {
name = "${name}-container";
inherit value;
}) memberContainers
// lib.optionalAttrs hasRootProject {
default = memberApplications.${projectName};
container = memberContainers.${projectName};
inherit doc;
};
checks.git-hooks = git-hooks.lib.${system}.run {
src = ./.;
package = pkgs.prek;
hooks = {
shellcheck.enable = true;
nixfmt.enable = true;
dprint = {
enable = true;
name = "dprint";
package = pkgs.dprint;
entry = "${pkgs.dprint}/bin/dprint fmt --config ${dprintConfig}";
types_or = [
"markdown"
"json"
"yaml"
];
excludes = [ "^\\.template/" ];
};
mypy = {
enable = true;
package = venvDevelopment;
# Avoid parallel cache writes when prek splits files into batches.
require_serial = true;
};
ruff = {
enable = true;
package = venvDevelopment;
};
ruff-format = {
enable = true;
package = venvDevelopment;
};
pytest = rec {
enable = true;
name = "pytest";
package = venvDevelopment;
entry = "${pkgs.bash}/bin/bash -c 'REPO_ROOT=\"\${REPO_ROOT:=$PWD}\" ${package}/bin/pytest'";
pass_filenames = false;
files = "^(src|tests)/";
};
sphinx = rec {
enable = true;
name = "sphinx";
package = venvDevelopment;
entry = "${package}/bin/sphinx-build docs/ docs/generated/";
pass_filenames = false;
files = "^(src|docs)/";
};
# cruft produces these merge reject files when an automatic merge fails
check-no-merge-rejects = rec {
enable = true;
name = "check-no-merge-rejects";
package = (
pkgs.writeShellApplication {
name = "pre-commit-check-no-merge-rejects";
text = ''
for filename in "$@"; do
echo "Rejected merge file exists: $filename"
done
exit 1
'';
}
);
entry = "${package}/bin/${package.meta.mainProgram}";
files = "\\.rej$";
};
};
};
devShells.default = pkgs.mkShellNoCC {
packages = [
venvDevelopment
pkgs.uv
pkgs.act
]
++ self.checks.${system}.git-hooks.enabledPackages;
env = {
# Don't create venv using uv
UV_NO_SYNC = "1";
# Force uv to use Python interpreter from venv
UV_PYTHON = "${venvDevelopment}/bin/python";
# Prevent uv from downloading managed Python
UV_PYTHON_DOWNLOADS = "never";
};
shellHook = ''
# Undo nixpkgs default dependency propagation
unset PYTHONPATH
# Undo nixpkgs default of reproducible timestamps, affects Sphinx docs
unset SOURCE_DATE_EPOCH
# Get repository root using git. This is expanded at runtime by the editable `.pth` machinery.
export REPO_ROOT="$(git rev-parse --show-toplevel)"
# Install git hooks
${self.checks.${system}.git-hooks.shellHook}
'';
};
formatter = pkgs.nixfmt-tree.override {
runtimeInputs = [
venvDevelopment
pkgs.dprint
];
settings.formatter = {
ruff-format = {
command = "ruff";
options = [ "format" ];
includes = [
"*.py"
"*.pyi"
];
};
dprint = {
command = "dprint";
options = [
"fmt"
"--config"
(toString dprintConfig)
];
includes = [
"*.md"
"*.json"
"*.yaml"
"*.yml"
];
excludes = [ ".template/**" ];
};
};
};
};
eachSystem = lib.genAttrs (import systems);
applySystemToAttrs =
attrNames: lib.genAttrs attrNames (attrName: eachSystem (system: (perSystem system)."${attrName}"));
flakeOutput = applySystemToAttrs [
"packages"
"devShells"
"checks"
"formatter"
];
in
flakeOutput
// {
overlays.default =
let
fullOverlay = overlay;
memberNames = builtins.attrNames workspace.deps.default;
in
final: prev: lib.filterAttrs (name: _: builtins.elem name memberNames) (fullOverlay final prev);
};
}