Compare commits

...
Author SHA1 Message Date
Jade Lovelace dad8a30906 release: 2.95.0 "Kakigōri"
Release produced with releng/create_release.xsh

Change-Id: I9d78b7d65053fb1d4a00dfd0d7ce9c93eba68365
2026-03-13 09:06:49 -07:00
Jade Lovelace dc7d5c45a4 release: release notes for 2.95.0
Release created with releng/create_release.xsh

Change-Id: I4cb4c81a440787fe5417369e5a058c8bb51c0cb1
2026-03-13 09:06:04 -07:00
Jade Lovelace fc5ab134d9 2.95.0: release name
Change-Id: I20fe0119cb3f011c3ea2f8355a120a8c2fecb610
2026-03-13 09:02:05 -07:00
rootile a05dbd2d7f docs: fix typo in distributed builds
Change-Id: Ie0bf1e6f2cecade786647aab1030279b57b7efb7
2026-03-13 16:24:51 +01:00
Jade Lovelace fada71a749 Update nixpkgs and nix2container
Fixes: https://git.lix.systems/lix-project/lix/issues/1152

Change-Id: I29ccfe46d7de43f521b88beff73a782a1fdb8d8c
2026-03-11 11:21:11 +00:00
Raito Bezarius 7c53a2cf9c manual/rl-next/f1-lang: reduce CLs to 1 in the chain
This avoids a large list of CLs when a user can discover all the CLs by
browsing the chain.

Change-Id: I1890eb87e8bf6f930d3d00c3f7156690bb8de068
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-10 17:09:22 +00:00
Raito Bezarius 5789f4b0a9 manual/rl-next: fine-tune the release notes
Follow up of https://gerrit.lix.systems/c/lix/+/5346?tab=comments for
the obvious pieces.

Change-Id: If0f640f786b0778d016187cb24c0513a48b5a30b
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-10 17:09:22 +00:00
Qyriad ca40ce8671 repl: always reload, but restore on failure
This might do more copies than are necessary. I think that's fine.

Sorry, :reload not reloading has been bothering the shit out of us.

Fixes #1115.

Change-Id: I7f4caca3dad39696ce66ce57b1a520836a6a6964
2026-03-10 15:05:25 +00:00
Qyriad 7f9b734aa5 repl: refactor initEnv into init+swap
Change-Id: Ica451fd95f55fe7893579c09eeca77db6a6a6964
2026-03-10 15:05:25 +00:00
rootile 03edd9f75d release-notes: add horrors to deprecated features credits
Change-Id: I73ed3198cfdbab15edddc9393010cafdf5050176
2026-03-09 22:44:29 +00:00
rootile e00ee5954e maintainers: unify issue references
So far, we had both `fj#` and `lix#` issue references in our release
notes, due to supporting both in the md files.
This commit unifies those in order for all references to be consistent.

Change-Id: I67c75784b460bfe4ebf214c2f6ac105cc60a7bad
2026-03-09 22:16:50 +00:00
Qyriad 861e5a7471 add misc/upgrade-lix.sh wrapper script, for nix-daemon@.service checks
Change-Id: I073b753f24e24eefe9d8f68543c4d1be6a6a6964
2026-03-09 22:28:51 +01:00
eldritch horrors 8c03cc961f nix/daemon: fix more stdio forwarding errors
kj can and will throw exceptions immediately without wrapping them as
promise results, and we must take care of these as well to not crash.

fixes #1150

Change-Id: Ifa29d0f3da4a6490f3e45d4c04a8fa49eaa20f43
2026-03-09 14:41:56 +01:00
K900 35fbfea6f8 package.nix: fix build with latest nixpkgs
mdbook-linkcheck was dropped from nixpkgs and replaced with mdbook-linkcheck2,
which is not entirely a drop-in replacement, but drop-in enough for us.

Change-Id: Iab03efab89ebae70811e0de3ea7cf0a9a059a9e4
2026-03-08 13:35:28 +03:00
Alois Wohlschlager fb9a575766 libstore: fix builder launch failure on older kernels
Since commit ac64c727b5, during launch of the
builder it is attempted to raise all capabilities into the ambient set.
Specifically, what "all" means here is determined by the Linux API headers Lix
was built against.

Occasionally, new capabilities are added in the Linux kernel, leading to
PR_CAP_AMBIENT_RAISE failing with EINVAL on the newly added capabilities if the
API headers are from after the change but the running kernel is from before.
Similarly to how capset already silently ignores nonexistent capabilities, we
ignore this error so the builder doesn't fail to launch unnecessarily.

Unfortunately it is very hard to test for this situation currently, since the
last time a capability was added was CAP_CHECKPOINT_RESTORE in Linux 5.9, and
all kernel versions in nixpkgs are newer than that.

Change-Id: Ibeb2f0757729b877bd3ca9f02e1aa4536a6a6964
2026-03-07 12:02:41 +01:00
eldritch horrors c914b9fc53 nix/daemon: wrap kj stdio forwarding errors nicely
not doing this has lix crash if stdio forwarding fails for odd reasons,
such as ssh failing to set up a connection due to transient dns errors.

cf #1148

Change-Id: I543b7444236e69d3c13b47fb6c6eb37c65b96763
2026-03-05 21:43:52 +00:00
Katalin Rebhan 981dd6e9b2 Add missing <sys/time.h> include
This is necessary for utimes and lutimes.

Change-Id: I352784606768f2b8a7de3c652e2a197e6a6a6964
2026-03-05 19:11:45 +01:00
Raito Bezarius 31a4f4547a Revert "libexpr/primops: allow storePath in pure evaluation mode"
This reverts commit 37ccd28c3b.

Reason for revert: https://git.lix.systems/lix-project/lix/issues/1147
More impurities were introduced than we wanted.

Fixes #1147.

Change-Id: Iec3b1d0e9a77484a68c6d9307a7a527fda236ed2
2026-03-05 17:09:46 +00:00
b7cf773540 libexpr: warn when encountering IFD with warn-import-from-derivation
This is intended to be a softer version of
`allow-import-from-derivation`, allowing for users to only flag when IFD
is encountered rather than error out

Based-on: https://github.com/NixOS/nix/pull/13279
Co-authored-by: gustavderdrache <alex.ford@determinate.systems>
Co-authored-by: Eelco Dolstra <edolstra@gmail.com>
Change-Id: I879a444e3a24b4e82a8cea3a5a94834c78c3924a
2026-03-05 13:39:12 +00:00
Qyriad 6f25c5468d cli: factor out and cleanup hasContent() for flake-show
Change-Id: I15c2df9a207639e81ff9030b737268526a6a6964
2026-03-04 19:44:21 +00:00
skye 8b38edaf1e libexpr: Migrate emitTreeAttrs to return a Value
Part of #1136 and progress towards #744

Change-Id: Iaa011161b26bda237bcf4424bf8262726a6a6964
2026-03-04 11:53:34 -05:00
Raito Bezariusandeldritch horrors 37ccd28c3b libexpr/primops: allow storePath in pure evaluation mode
`builtins.storePath` allows you to use "external" knowledge of present
store paths in your store to be used in your expressions.

This is sometimes used to avoid double wrapping store paths, for example
when dealing with nixpkgs sources (`builtins.storePath pkgs.path` is a
frequent pattern).

Unfortunately, using your external knowledge of present store paths is
technically impure because Flakes is about not depending on the *STATE*
of your store, no matter what you know about it or what you do to ensure
that your knowledge is accurate.

That being said, `builtins.storePath` is already possible in the
fragment of "pure Nixlang" via a clever use of `builtins.appendContext`.

Precisely:

```
  storePath = path:
  let path' = builtins.unsafeDiscardStringContext path;
  in
  # NOTE: merging the context set in all generality is impossible
because getContext on a pure path doesn't work.
    builtins.appendContext path' { ${path'} = { path = true; }; };
```

works in pure contexts.

Because of this, we deem that storePath should be allowed in pure
contexts and users do not have to come up with a `storePath` polyfill.

Fixes #402.

Change-Id: I5fff750a4feed082745431835db451f945249cfb
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-04 11:33:30 +00:00
Raito Bezarius e8015836e3 libcmd/profiles: keep derivations if keep-env-derivations = true
nix3 CLI never honored that setting.

When we update a nix3 profile element with new built store paths for
which we know the deriver (the derivation path which built it), we add
the derivation paths to the profile element to prevent garbage
collection the same way the nix2 CLI logic does.

Fixes #1095.

Change-Id: Icc236d174c5ce5ffe042d1c8e1968f6cb5b50359
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-03 22:13:02 +00:00
isabelandRaito Bezarius fc649250ec libexpr/flake-config: collect untrusted settings into one prompt
Instead of showing untrusted configuration items one by one, collect all
of them into one batched ask with 4 options:

- apply the configuration wholesale **for now** (yes)
- apply the configuration wholesale and trust it permanently (allow
  permanently)
- selectively choose subset (no)
- rejecting the configuration wholesale (no to all)

Note that we do not offer options to reject permanently a configuration,
that's what `--no-accept-flake-config` is for.

Individual prompts gain a new option to distinguish "yes for now" and
"yes forever".

Fixes #682.

Change-Id: I2492717ac277af33ea4ac9b1a11bd7d6d1bfe0db
2026-03-03 21:57:03 +00:00
Raito Bezarius b28723c5b9 libexpr/eval: do not confuse path and string with contexts in messages
In messages printed by the evaluator, we use showType(.) to say things
like "expected X, got Y" where X, Y can be string, string with context,
etc.

After changes in the Lix data model (pointer tagging and friends), paths
got squished inside a internal string type.

We missed updating `showType` to take this fact into account which
caused an unfortunate:

`error: expected a string but found a string with context:
/nix/store/wjf8rdpp63rhyasbzc7zfms1agf7pwyd-source`

while using a path on `builtins.getContext`

A test is added.

Change-Id: Ifb0129ead2ea1973fc17dc0133f8a694995536b1
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-03 21:36:13 +00:00
Raito Bezarius da37164630 libutil/strings: add partitionString
This partitions a string into two parts based on the first occurrence of
the separator.

This function handles the case when the separator never occur in the
target string by returning an optional<T> in the second argument of the
pair.

Change-Id: I9ad44375dbaa137a4d21d2408bc2ffa34fab62a7
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-03 20:54:08 +00:00
Raito Bezarius 135c28be53 libcmd: introduce enum traits for CLI parsing
Parsing and completing enumerations on the CLI was usually done by hand.

With this enum trait, the parsing and completion is automated away.

Change-Id: Icd49729564355d4c79e2c8050ce7e8b9d8e7eda3
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-03 20:54:08 +00:00
Raito Bezarius a2f1369d18 libmain: drop categories for dry-run and json args
36c4d6f592 introduced it commented. Zero
explanation why.

horrors suggested to drop it entirely because it hide the options in
categories but they are pretty common and we should make as much visible
as possible.

Change-Id: I09894b5ba0f2b2cce5869136914289fed034fce3
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-03 20:54:08 +00:00
Raito Bezarius b55260ce4a package/devshell: add pkgs.tree
Fixes #823.

Required for releng scripts.

Change-Id: I876784ffc868541924c2bb957aec58b704fd7dd2
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-03 20:22:34 +00:00
eldritch horrors 7a0a85b543 libstore: recursively delete cgroups
fixes #1143

Change-Id: I9f5cf5c127ac23e60e3232d85f338e467ed4f170
2026-03-03 15:49:52 +01:00
Raito Bezarius 092064db4c libstore/build: allow preferLocalBuild = true to bypass max-jobs = 0
When `max-jobs = 0`, our async semaphores have null capacity and
therefore no slot token can be acquired.

In addition, a derivation with `preferLocalBuild = true` with `max-jobs
= 0` which is not a built-in derivation is not considered suitable for
being possible to build.

Our documentation in `max-jobs` writes:

> `0` is useful when using remote builders to prevent any local builds
(except for preferLocalBuild derivation attribute which executes locally
regardless).

A valid interpretation is that `preferLocalBuild` derivations (all of
them) will always execute even if `max-jobs = 0`.

This CL achieves this promise by enabling `preferLocalBuild = true`
derivations to draw in priority capacity from a `preferLocalBuild`-only
pool and then fall back to the build pool (`maxBuildJobs`).

If there's non-zero max-jobs, we make the `preferLocalBuild`-only pool
empty.

If there's zero max-jobs, we make the `preferLocalBuild`-only pool
non-empty (capacity: 1).

Remark 1: if `max-jobs = 0`, no non-`preferLocalBuild = true`
derivations can be built without a remote builder and `preferLocalBuild
= true` derivations can be built one at a time if `extra-local-jobs` is
not overridden.

Remark 2: if `max-jobs != 0`, no `preferLocalBuild = true` derivations
can bypass capacity limits, i.e. `max-jobs` unless `extra-local-jobs` is
overridden.

Fixes #855.

Change-Id: I00a0acac7375a881aec6281ebb13a4530b26e460
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-02 23:46:38 +01:00
Raito Bezarius bd108b7e61 libutil/config: support optional<uint32_t>
This is going to be used in the extra-local-job future setting.

Change-Id: Ied76f32b8fa97cb71691d76167103001aa14fa01
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-02 20:20:06 +01:00
Raito Bezarius ac6c9a9c0a libfetchers/github: distinguish ref/rev provenance
When ref/rev are very similar looking, e.g. a revision SHA1, the logic
to reconstruct whether we had a ref or rev initially cannot work.

This regression was introduced by
I2c72d5a32e406a7ca308e271730bd0af01c5d18b which passed the information
as an attribute field called `refOrRev`, instead, we pass `ref` or `rev`
but not `refOrRev`.

We apply the same post-processing logic to distinguish rev/ref in
path-style flake references: `github:owner/repo/$refOrRev`.

Fixes #520 #841.

Change-Id: I2b1985cd5f351f43fea84232c1972715e2408fb1
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-02 13:14:42 +00:00
eldritch horrors 6ddc59de47 launch-builder: don't limit sandbox setup data size
the channel we're using is fully trusted, we don't need the traversal limit.

fixes #1121

Change-Id: I2833a7459cec1e2392e8740d8cab213685d3e2b3
2026-03-02 12:10:12 +00:00
skye 9a408cbeb7 libexpr: Replace Value::mkPrimOp with constructor calls
Change-Id: I19b05e260945e237f7856b5d644a43076a6a6964
2026-03-01 18:02:58 -05:00
Raito Bezarius 74300fd0a7 libexpr/primops: reject __json in structured attrs derivations
In structured attrs derivations, __json is used to serialize the `env`
attribute into a JSON object.

If the derivation enables structured attributes AND specify its own
`__json`, one of the field will take precedence (the reader can have fun
by guessing which one).

To reduce underspecification, we disallow `__json` in structured
attributes derivations.

Fixes #380.

Change-Id: I51c3b2af1ff9449471ba81d4c72df6a7a263eef7
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-03-01 19:05:54 +00:00
skye 12cee5cb22 libcmd/repl: Migrate evalString to return a Value
Change-Id: I41cd79b71106474d048d447befac16676a6a6964
2026-03-01 01:01:47 -05:00
skye 8623dade34 libexpr: Migrate callFlake to return a Value
Change-Id: Ibdac6eb1c9dfda894d783a7b6e333f486a6a6964
2026-03-01 01:01:47 -05:00
skye 2be998eeb4 libexpr: Migrate Evaluator::evalLazily to return a Value
Change-Id: I9f778407d454e141cb9b7959bbc02ed26a6a6964
2026-03-01 01:01:47 -05:00
skye c6b4f30be9 libexpr: Migrate EvalState::autoCallFunction to return a Value
Change-Id: I426c3d413b18848090dd05674a08e5fb6a6a6964
2026-03-01 01:01:47 -05:00
skye 27bf276304 legacy/nix-env: Migrate loadSourceExpr to return a Value
Change-Id: Ia1e1ac6fe9fd00d7a2fa4a39a3ce21e86a6a6964
2026-03-01 00:04:28 -05:00
eldritch horrors 30e9387cf9 testing: migrate path-from-hash-part.sh
Change-Id: Ied00671595d82c6d446f117d6aa9c42a0c758cb6
2026-02-28 22:09:44 +00:00
eldritch horrors 8d389fcccf testing: migrate selfref-gc.sh
Change-Id: Ibead4030448fb9251be78b3c876c7f054154c83c
2026-02-28 22:09:44 +00:00
eldritch horrors f4c92f8872 testing: migrate function-trace.sh
Change-Id: I44bd28165070f55f21b052bc02ba6f2ea5787a1d
2026-02-28 22:09:44 +00:00
eldritch horrors fae0242f69 testing: migrate ssh-relay.sh
Change-Id: I520c8be1c30b4ee7660c8ceeba62a6d0757c337b
2026-02-28 22:09:44 +00:00
eldritch horrors e8cb30b11c testing: fix f2 NIX_BIN_DIR determination from meson
`nix.full_path()` is the *built* path, not the *installed* path. in the
sandbox this point to a location that contains *only* `nix`, not any of
the old-cli symlinks. any test that needs them in path would thus fail.

Change-Id: Ia651db8d1151a84f8d1b52e8993f6db61b0fe104
2026-02-28 22:09:44 +00:00
skye f856d4fd25 libexpr: Migrate EvalState::evalFile to return a Value
Change-Id: I19ce8623477dd96628476b3e3dd58cfd6a6a6964
2026-02-28 15:53:10 -05:00
skye debf5554e0 libexpr: Consolidate implementation between Value string constructors
Change-Id: I5bf8d58b534cd652d89f7b93019378b66a6a6964
2026-02-28 15:53:10 -05:00
skye be3a40e5dc libexpr: Replace Value::mkString with constructor calls
Change-Id: I55bba546eb090728a71734450a2a5f496a6a6964
2026-02-28 15:53:10 -05:00
Tom Hubrecht d52033fc77 nix/develop: Don't ignore SSL_CERT_FILE when its value is meaningful
Change-Id: I31e85a5995edc40ed2e687077ffdf563e717abb4
2026-02-28 12:32:45 +00:00
benaryorg 052d04512e libfetchers: Provide gitDir for rev-list operation
Without the `--git-dir` git will attempt to figure out which the git directory is on its own.
This causes issues when the `GIT_DIR` envvar is set in the environment for other reasons (such as being part of a `git rebase`).
Providing this parameter overrides the environment and thus makes sure the revs are always coming from the intended repository.

Fixes: #1135
Change-Id: Ibd43cfd8e0278463c0e1ccf86779982947a6038a
Signed-off-by: benaryorg <binary@benary.org>
2026-02-28 09:06:18 +00:00
eldritch horrors dda934965d testing: migrate build-jobless.sh
Change-Id: Ica9a0c5b8bea50d302ad633d3801431adcdba5e7
2026-02-27 17:43:07 +00:00
eldritch horrors 378c86eadf testing: migrate compute-levels.sh
this test wasn't even run

Change-Id: I735c8b2d2c63a65c665d6344a98ddb3bbbf94f43
2026-02-27 17:42:17 +00:00
eldritch horrors 298373615e testing: migrate impure-eval.sh
Change-Id: Ifd2b6c117511461ce08fa3f9e63635857cb5b015
2026-02-27 17:42:17 +00:00
eldritch horrors 14d8209198 testing: migrate output-normalization.sh
Change-Id: I51a021b27fa27b531bb49b8529bae2e9bf74641a
2026-02-27 17:42:17 +00:00
eldritch horrors b2ae7c3965 testing: migrate pass-as-file.sh
Change-Id: I9c3a940ede9353e977e60e0650eaa5a64cc6fa5e
2026-02-27 17:42:17 +00:00
eldritch horrors 32a96169d6 testing: migrate optimise-store.sh
Change-Id: I900183e11ba1405c9aa72028a8902ad8cf023e69
2026-02-27 17:42:17 +00:00
eldritch horrors 5fb0dd156d testing: migrate build.sh
Change-Id: I9d2da21cc226e0c1ef2dfa4d475c1989bbbfaf79
2026-02-27 17:42:17 +00:00
eldritch horrors 5f2c771b5a testing: migrate placeholders.sh
Change-Id: Iad6a6f53dac23cc5e49961571dd4c0545d616d7e
2026-02-27 17:42:17 +00:00
eldritch horrors b8b69dde05 testing: migrate local-store.sh
Change-Id: I5172fc2611a56b19f55d5c05dacdfef5cf330739
2026-02-27 17:42:17 +00:00
eldritch horrors 26f1397b75 testing: migrate suggestions.sh
Change-Id: Iad28262035aa96c5ef6fa33e2a830b5fa8a9ae50
2026-02-27 17:42:17 +00:00
eldritch horrors 8cf21fcf75 testing: migrate case-hack.sh
Change-Id: I552dd596764a779e1485a6326363d4f4283110f3
2026-02-27 17:42:17 +00:00
eldritch horrors 4caa622d78 testing: migrate fetchMercurial.sh
Change-Id: Iab81ea161e3be69bf7753b3ed9cd8f59cd8fe0ed
2026-02-27 17:42:17 +00:00
Qyriad f13566a3f6 repl: fix 'tokens-no-whitespace' in :use's Nix expression
Change-Id: Ifa2bc6b1204cc5a85422128c76b192296a6a6964
2026-02-27 08:51:40 +00:00
eldritch horrors 0bcdfe2c43 testing: migrate fmt.sh
Change-Id: Icc593b57a06c7fdf75762094982788f6351dcadc
2026-02-26 19:43:39 +00:00
Raito Bezarius bcab3d5da3 libstore/build: set impure environment variables only if they are set
To stop spurious warnings, we will stop this bizarre behavior of setting
empty values to impure environment variables.

On the warning side, we verify that the presence of the environment
variable.

The corresponding test is updated to "there is a warning" to "there is
no warning".

Change-Id: I12f5c6445ef00a83d269488d7aed0b0f61aeec12
2026-02-26 15:33:22 +00:00
Raito Bezarius 72a6d5ff48 tests/functional2: test spurious warnings for certificates
All impure environment variables are initialized as part of `initEnv()`
to an empty value if they are unset.

Whenever `NIX_SSL_CERT_FILE` is set, this cause a spurious warning.

Let's document it here as a test before we fix it.

Change-Id: Iccba8ccb487d9cc25490e940ff09c1c5a13ae097
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-02-26 15:33:22 +00:00
Raito Bezarius 0741e24266 tests/functional2: migrate (un|)sandboxed CA tests
CA tests have grown quite complicated and are hard to debug and
manoeuver for new needs.

They are a prime target for F2 migration and they were extremely
pleasant to write.

Most functionality is preserved or improved with additional behaviors
asserted on warnings and the full set of reports.

Change-Id: I70cd52abbe5ff13f56744b966ab00962ad3a49d6
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-02-26 15:33:22 +00:00
eldritch horrors dde7bddbd4 f2: fix Nix::add_[dx]p_feature type hints
Change-Id: I743b3ac821315465d1d22700ca9b06d8cc1985f0
2026-02-26 14:16:13 +00:00
eldritch horrors f2df62439c testing: migrate flakes/flakes.sh (part 18)
nonflake inputs

Change-Id: I5017ece5028652e3ae19c5e00e67358fc9c0253d
2026-02-26 13:11:25 +00:00
eldritch horrors 30ce32e2f6 testing: migrate flakes/flakes.sh (part 17)
symlinks in flake dirs, recursive lookups, update with override

Change-Id: I1491ca8e618ff5e06a06d3cc3648ae0750a1ffde
2026-02-26 13:11:25 +00:00
eldritch horrors b92f1aa865 testing: migrate flakes/flakes.sh (part 16)
input overrides during locking

Change-Id: I20e8e8bc2579f2f9bbaf7b522647a520d010ec43
2026-02-26 13:11:25 +00:00
eldritch horrors cbe4d1b339 testing: migrate flakes/flakes.sh (part 15)
flake follows handling during locking

Change-Id: Ia3f2b7a8df1d0ec51fd97d14d49788b33dda7754
2026-02-26 13:11:25 +00:00
eldritch horrors 2634585a48 testing: migrate flakes/flakes.sh (part 14)
flake clone

Change-Id: I6697d109465eaededfb2ac8ee552b6ac971d2e8a
2026-02-26 13:11:25 +00:00
eldritch horrors f0f8117d5b testing: migrate flakes/flakes.sh (part 13)
builds with incomplete lockfiles

Change-Id: Ibf386ec98208d5b706236277e2eae9e144d9bdb0
2026-02-26 13:11:25 +00:00
eldritch horrors 93af25a706 testing: migrate flakes/flakes.sh (part 12)
gc rooting behavior

Change-Id: I7b3aa765b8e08aa8a4ce96988629ee76c76b46a0
2026-02-26 13:11:25 +00:00
eldritch horrors c45e34bbc5 testing: migrate flakes/flakes.sh (part 11)
input updates with cli commands

Change-Id: Idddfe77a285f9c2cbc4f1463454af539042bc23e
2026-02-26 13:11:25 +00:00
eldritch horrors f864626a1c testing: migrate flakes/flakes.sh (part 10)
getFlake behavior

Change-Id: Iff9bb6e834ff2545db11b72f5a6ab3ddf42e5662
2026-02-25 12:47:08 +00:00
eldritch horrors c090a9d1ec testing: migrate flakes/flakes.sh (part 9)
bulk of build tests

Change-Id: I2b357162e16e2d14bb8ae6247ad126ad452c0825
2026-02-25 12:47:08 +00:00
eldritch horrors 3327a1fcae testing: migrate flakes/flakes.sh (part 8)
eval-system influences attribute choice

Change-Id: I02d611ed17748c73d5c77ebd0a44f558ab63d1c8
2026-02-25 12:47:08 +00:00
eldritch horrors 7976f9fb6e testing: migrate flakes/flakes.sh (part 7)
registry maintenance and queries

Change-Id: Id0aef61ce91972417ba3a941aba7b2c9ca05bf7c
2026-02-25 12:47:08 +00:00
eldritch horrors b4846d4e51 testing: migrate flakes/flakes.sh (part 6)
flake attr matching

Change-Id: If5a1f01f9939740636482d2755eb836e2166ce97
2026-02-25 12:47:08 +00:00
eldritch horrors 5d11ed07f5 testing: migrate flakes/flakes.sh (part 5)
build bare repo, build tarball, lock path urls without repo

Change-Id: I7cb7494dcf29ec9b88c923c54a798685725785a1
2026-02-25 12:47:08 +00:00
eldritch horrors 4ef9fb3aee testing: migrate flakes/flakes.sh (part 4)
metadata query functionality

Change-Id: I8f3866316994426664468edfbe154505ed2428af
2026-02-25 12:47:08 +00:00
eldritch horrors 126ef6321d testing: migrate flakes/flakes.sh (part 3)
add-path and path-info interactions

Change-Id: I8649442eb54d539957d4339a00b948e1173d2da7
2026-02-25 12:47:08 +00:00
eldritch horrors 987a906317 testing: migrate flakes/flakes.sh (part 2)
legacy cli interactions

Change-Id: Ibdefbbf4b10ea8554a75caf589bb1f5a26639f4a
2026-02-25 12:47:08 +00:00
eldritch horrors 1df00b7db0 testing: migrate flakes/flakes.sh (part 1)
handling of alternate lock file locations

Change-Id: I402fa3b1a48805e571eecc6772f2656e93c68086
2026-02-25 12:47:08 +00:00
eldritch horrors e76c6afd8d testing: migrate flakes/follow-paths.sh
Change-Id: I825445a51f496dbe2efde684a0045e6fb56d9c0a
2026-02-25 12:47:08 +00:00
Thomas MiedemaandQyriad 6182a5e659 nix-daemon: source nix-profile-daemon.sh only once
Cherry-picked-from: https://github.com/NixOS/nix/pull/12805
Co-authored-by: Qyriad <qyriad@qyriad.me>
Fixes: #1134
Change-Id: I0c575f6b974e06b5064564bb084829fa6a6a6964
2026-02-24 18:36:39 +00:00
skye 53c0e884d8 Migrate EvalState::eval from out param to return a Value
Instead of taking in a final argument `Value &` out parameter which it
writes to, it now returns its result

Change-Id: Iab6bc3a3ac6a4b17c6d31115a766a6ea6a6a6964
2026-02-24 13:00:30 -05:00
skye d14613459b libexpr: Migrate EvalState::callFunction to return a Value
Previously it had an out parameter. Now it has a return value.

Change-Id: I9ec465a7d23b99da9132f1ab0fcc5cf16a6a6964
2026-02-24 13:00:30 -05:00
eldritch horrors 3b0e2ddd0a libutil: don't report DecompressionStream shutdown errors
we already report errors that happen during reads via exceptions
rethrown from read. reporting errors during destruction too is a
source of confusion for users since these errors are not usually
relevant and just the decompressor thread reporting short reads.
shorts reads during shutdown are not an error, they're expected.

fixes #1138

Change-Id: I7983ef0ed7722460f1d683bc8171a454b3d06e90
2026-02-24 15:28:56 +01:00
Qyriad 6b4de44461 nix-env/query: don't use RAII for closing xml tag
I could instead add the right braces or manually ensure the
XMLOpenElement destructor is run at the right time. Or I could just
write what I actually want to happen.

Fixes #1137.

Change-Id: Ie1f157de1632571fb0c21e26d8e3cae56a6a6964
2026-02-24 12:28:45 +01:00
skye 1ef7ccfc72 libexpr: migrate Expr::eval to return a Value, take 2
This is a rebase of CL 1626 after the performance problems that blocked
that change are no longer an issue.

Change-Id: I4a17f7606c5fdc9a924933a860eb401f6a6a6964
2026-02-23 18:11:47 -05:00
skye 62a2663436 libexpr: Replace Value::mkBool with constructor calls
Change-Id: I714271f6cbd2f5b2d6e1e7fe7eb7feab6a6a6964
2026-02-23 15:12:35 -05:00
rootile d641a829bb tests/functional2: migrate brotli.sh and zstd.sh
Change-Id: I5f1252e8f29a9551f3d6b2ed8f0598f524906aed
2026-02-23 20:44:46 +01:00
skye 864c5e7507 libexpr: Replace Value::mkInt with constructor calls
Change-Id: I09b8e3aa61042a60c2ae767fc44c26b66a6a6964
2026-02-23 11:55:02 -05:00
skye 23a0b78a16 libexpr: Replace Value::mkFloat with constructor calls
The pseudo-constructor `Value::mkFloat` would previously be called on an
default-constructed (under-initialized) `Value` to create a properly
initialized `Value` that represents a float. This change removes mkFloat
and constructs float `Value`s directly.

Change-Id: I48ae3a836842ce5e5eda6323404ba7576a6a6964
2026-02-23 11:51:29 -05:00
skye 492d7bbe1f libexpr: Convert Value::mkStringMove to a constructor
The pseudo-constructor `Value::mkStringMove` would previously be called
on a default-constructed (under-initialized) `Value` to create a
properly initialized `Value` that represents a string, reusing an
existing GC allocated Str. This change turns that method into a proper
constructor

Change-Id: I8d7a97e2afce231a04ecf56fdd6d22d06a6a6964
2026-02-23 11:40:02 -05:00
rootile 6b9a121637 testing: throw an error when a command object has not been run
it sometimes happens that one forgets to add `.run().ok()` to a command,
leading to things not actually being tested, potentially even slipping
though code reviews!

This commit adds a check at fixture teardown time, checking that all
commands have been run. Sadly, due to when this check happens, we cannot
add a test checking for this behavior

Change-Id: If3df2c20c267b9f03ae0ca099b77c57e2310f335
2026-02-23 17:21:01 +01:00
eldritch horrors b015654133 testing: also report tests that fail teardown as failures
this includes tests that fail teardown when *skipped*, which confuses
the tap parser by reporting more tests than advertised in the header.
not sure what to do about this though, and it is better than nothing.

Change-Id: I4fc6badacbfa3b3d5f5f4a4ad76b177379bb4a30
2026-02-23 16:57:35 +01:00
eldritch horrors 3c1c130c59 testing: disable progress reports in tap mode
pytest-tap didn't get it right in combination with xdist. we need to
replace the reporter *completely*, which is just incredibly weird :/

Change-Id: I2e35b9dc8ea4b24563b9b3306312778781eb674e
2026-02-23 15:26:18 +00:00
skye e8f161ead1 libexpr: Replace Value::mkPath with constructor calls
The pseudo-constructor `Value::mkPath` would previously be called on an
default-constructed (under-initialized) `Value` to create a properly
initialized `Value` that represents a path. This change
removes mkPath and constructs path `Value`s directly.

Change-Id: I9021de1ff59490828f9fec6866e083996a6a6964
2026-02-23 09:37:40 -05:00
skye d07bbb109e libexpr: Replace Value::mkAttrs with constructor calls
The pseudo-constructor `Value::mkAttrs` would previously be called on an
default-constructed (under-initialized) `Value` to create a properly
initialized `Value` that represents an attribute set. This change
removes mkAttrs and constructs attr `Value`s directly.

Change-Id: I11cd801eefecd454a7a5b6229d6770d06a6a6964
2026-02-23 03:54:35 +00:00
eldritch horrors c2b61c5da3 testing: migrate flakes/mercurial.sh
hg is *so fucking slow* omfw

Change-Id: I0f4d1d2a546a75f965ff017c9451fb1d441990b1
2026-02-22 20:46:06 +00:00
eldritch horrors 7a3f352105 testing: migrate flakes/flake-in-submodule.sh
Change-Id: I9dcf63a2f63b54de541536a00dbd5d8df941ea33
2026-02-22 20:46:06 +00:00
eldritch horrors 8b1ca49fef testing: migrate flakes/develop-r8854.sh
Change-Id: Ib993d30edb97d7705acbf5d94f1831ffbe191d92
2026-02-22 20:46:06 +00:00
eldritch horrors d69048e92b testing: migrate flakes/develop.sh
Change-Id: Ibd97c54efb72285a4b969fe11e6e6adf3a2d5511
2026-02-22 20:46:06 +00:00
Jade Lovelace 01ff67595b nix3-add-path: add references-list argument for ca with references
This is not ca-derivations. We don't care about self-references or any of the
rewriting or stuff like that; if you want something like that, write
your user code so it figures out where it is.

The reason I want to do this is for integrating other build systems with
Lix: if you're importing something built *outside the store* with a
non-Nix build system, it makes no sense to put it in an input-addressed
path since it's not possible to come up with a derivation for it.
But you need *some* hash, so the output hashing is the most sensible option.
It is also nice because of not needing trusted user privileges to import
it, since the hash describes the exact contents of the output path.

We use this feature (implemented externally to Lix; this CL eliminates
that step) at Mercury to integrate buck2 with Nix on the output side: we
import things to the Nix store as ca paths with references.

These can then be consumed by Nix language with:

```
# Hack from https://git.lix.systems/lix-project/lix/issues/402#issuecomment-5889
path:
builtins.appendContext path {
  ${path} = {
    path = true;
  };
}
```

Test plan:
```
$ nix store add-path --references-list xx-refs-list ./README.md
/nix/store/szcwnm13d9gmxx8fly0bz82l42jgysw6-README.md

$ cat xx-refs-list
/nix/store/g9hhwjbkdrw0wnbd3axfs4icyb37nr6b-bash-interactive-5.3p3

$ nix path-info --json /nix/store/szcwnm13d9gmxx8fly0bz82l42jgysw6-README.md | jq .
[
  {
    "ca": "fixed:r:sha256:1pj59fy7zcrn949ry9kgv4ba17h2sy3z2is469abj912cvbl14n3",
    "narHash": "sha256-w5JA12YiJLlUMkRH8YfXAp6gFtlvJp8TSTazf7xLRd4=",
    "narSize": 1384,
    "path": "/nix/store/szcwnm13d9gmxx8fly0bz82l42jgysw6-README.md",
    "references": [
      "/nix/store/g9hhwjbkdrw0wnbd3axfs4icyb37nr6b-bash-interactive-5.3p3"
    ],
    "registrationTime": 1771266146,
    "valid": true
  }
]
```

Change-Id: I005a03003dfc24108e018e599dbe0b5d6a6a6964
2026-02-21 22:50:13 +00:00
eldritch horrors ff8a10f9cd testing: move shell-hello.nix from global assets to flakes
Change-Id: I0039e82cd5ed069d901f4dd96cf33102216a11ea
2026-02-21 16:36:44 +00:00
eldritch horrors 46f99487de testing: use TAP for when running f2 from meson
this requires some hacks to make error reports visible, but hey. it's
better than no progress reports at all, and successful runs no longer
spew huge amounts of useless log output onto the developer's terminal

Change-Id: I9e4766b2f825a4ec451e117eb4609db65f328785
2026-02-21 16:36:44 +00:00
vczf 86268bd618 meson: fix broken build when using custom build directory
Fixes path resolution issue with meson-embedded bash script when
`build` is a symlink, or a custom build directory is passed as a
argument to `just` or `meson`.

Change-Id: I67b13c524d196241bb9a8a3b8ad2c17c2c094ed8
2026-02-20 23:32:33 +00:00
eldritch horrors c040a9d8e4 libstore: only check cgroup support when actually building
not all operations that involve workers need to build. for example nix
copy --from calls instantiate thir worker with the *origin* store, not
the store they copy *into*. for binary cache stores this is not likely
to ever work if cgroups are enabled and the copy is run on normal user
credentials, even though no cgroups will ever be needed to copy things

fixes #1088

Change-Id: I065e29e1a1d0f58d81823609ef0701ff82cdd1d5
2026-02-19 22:26:59 +01:00
eldritch horrors 4fcb434998 testing: migrate flakes/registry.sh
Change-Id: Iba7dd30efc19075a63c505db497b3c0967b47f57
2026-02-18 15:25:08 +00:00
eldritch horrors 4deed5ab35 testing: migrate flakes/build-paths.sh
Change-Id: Ia7f15abd8f5444c69fef4da0d080a2933ac264d8
2026-02-18 13:00:37 +00:00
eldritch horrors 03b8a6dcc2 testing: migrate flakes/flake-metadata.sh
Change-Id: I8370a279bbfa224f27cdba0cf9e79ade6d58644f
2026-02-18 11:32:33 +00:00
eldritch horrors fedb4d5ead testing: migrate flakes/inputs.sh
Change-Id: I4446441cb7eea51a42f055f042cceb3e63b84b92
2026-02-18 11:32:33 +00:00
eldritch horrors 28e1cccb49 testing: migrate flakes/init.sh
Change-Id: If132a14e3d10578489cdca03f67c2166f1362d6e
2026-02-18 11:31:40 +00:00
eldritch horrors fc7165401f testing: migrate flakes/symlink_paths to git fixture
Change-Id: Ieb6eb4b9b91c920fa5ee395dc0f7308965355045
2026-02-17 17:22:24 +01:00
eldritch horrors b1776ce4e2 testing: migrates flakes/subdir-flake.sh
Change-Id: I9ac02056d490473dd751f7ec7857840290f5afc5
2026-02-17 17:22:23 +01:00
eldritch horrors fa7edb9e01 testing: migrate flakes/bundle.sh
Change-Id: I734b52da3c62d6f562d6c843b89cb55ba6bd70d2
2026-02-17 17:21:44 +01:00
eldritch horrors 9adc840eda testing: migrate flakes/unlocked-override.sh
Change-Id: I101c96860e0a025a066880d952d2f24f9b92571e
2026-02-17 17:21:42 +01:00
eldritch horrors 899c5fe9f0 testing: migrate flakes/absolute-paths.sh
Change-Id: Icb9f7e1c8bf17327e32e1ad81f2bfdb4246ba2d7
2026-02-17 16:01:00 +01:00
eldritch horrors 2d73b59679 testing: migrate flakes/search-path.sh
Change-Id: I69c3efe2a33cfb216ffecf5b4bd7f57abb80acfd
2026-02-17 16:01:00 +01:00
eldritch horrors 8500339d95 testing: migrate flakes/config.sh
Change-Id: I7f19b33c30330ccd1f01b72b2e36a542f03f4e49
2026-02-17 16:01:00 +01:00
eldritch horrors 762a28a698 testing: migrate non-pty bits of flakes/show.sh
Change-Id: I4884fd34fa485f9f91281dc3efd69dedd3aad3d9
2026-02-17 16:00:59 +01:00
eldritch horrors ffefebd9f4 testing: migrate flakes/check.sh
Change-Id: I4cb9c675ccfc1763e54ce80f8521300b608bb0eb
2026-02-17 14:20:50 +01:00
eldritch horrors c6931c4176 testing: migrate flakes/circular.sh
Change-Id: Ia9eb3631278957c449dd8791e9cf02cb47705a63
2026-02-17 13:53:26 +01:00
eldritch horrors 04988fa318 f2: add git and git_cmd fixtures for calling git
Change-Id: Icdc03c76164d0db503a2f6c90f2bcb2377d9ced5
2026-02-17 13:53:26 +01:00
eldritch horrors f31ece23da testing: migrate flakes/run.sh
Change-Id: Id953cd257c3831d67531ffa4a131607519361227
2026-02-17 13:53:25 +01:00
Max Siling f1ce35f53c libfetchers: produce a proper error when both ref and rev are set
Affects `github`, `gitlab` and `sourcehut` fetchers.
Previously this was an assertion, which crashed the evaluator
with SIGABRT.

Fixes: #1133
Change-Id: Ia9bb8dd29ac8b9c97bf048827f62c5076a6a6964
2026-02-16 14:25:40 +03:00
eldritch horrors 9520e663c8 libstore: send all changed settings to builtin-builder
this includes logger verbosity, which isn't a setting for some reason.

fixes #1111

Change-Id: Ib078205b41069628010273645e26baf33b1c6d14
2026-02-12 18:00:33 +00:00
eldritch horrors 6e3a7711ca libutil: allow retrieving all *changed* settings too
overridden-ness can be reset, and is usually reset such that setting
value taken from a config file are not considered as overriden. when
launching builtin builders we *do* want to send config file settings
changes to the builder, so we'll need one more getter method for it.

Change-Id: I861538a469121c77ebc1898a276439e6b756797d
2026-02-12 18:24:25 +01:00
eldritch horrors 9723dc2c89 testing: migrate nix-profile.sh test
Change-Id: Id7b4b1c36943123c9d5f538b05cd67408c1cb269
2026-02-11 20:46:18 +00:00
eldritch horrors bffbe73493 f2: remove unused build arguments
they're no longer used since non-diverted stores are the default now.

Change-Id: I277b819340c2b69e1fd06607e562221469b77926
2026-02-11 20:46:18 +00:00
eldritch horrors b34f136f10 f2: don't use diverted stores unless specifically requested
diverted stores are only necessary when the logical store paths of
objects matter for the test itself, such as for derivation hashes,
substitution from golden sample nars, or actual tests of the store
diversion functionality. all other tests can use undiverted stores
to run, especially since only linux can build in diverted a store.

Change-Id: I62f0907bdef9961609af22b610195fcec54c1e57
2026-02-11 20:46:18 +00:00
Raito Bezariusandeldritch horrors 505d0669dc libstore/build: fix starvation during substitution
When the destructor of PathSubstitutionGoal is run, this happens in a
sync context and can cause starvation of all ongoing IO w.r.t. to other
substitutions, including our own substitution.

While there's only a decompressor thread per stream, the other side of
the IO runs on the event loop.

In order to fix this, it is sufficient to remove the thread indirection
and inline the async code.

Fixes #1126. Great thanks to horrors' patience.

Co-authored-by: eldritch horrors <pennae@lix.systems>
Change-Id: I3eb37bc37d156f0f5528364e568fdaa2ced58011
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-02-11 14:18:00 +00:00
piegames ef2fd27467 deprecated-features/rec-set-dynamic-attrs: Downgrade to warning for now
Looks like too much stuff is breaking on this, so let's make it only a
warning for now to ease transition

Change-Id: I52d50ceb1fe1fbe9f4e28d0aabf3537f7e4d52d1
2026-02-11 12:24:35 +01:00
piegames ae4a000576 deprecated-features/broken-string-escape: Improve warning message
Explicitly catch common errors (trying to escape line breaks, badly
escaping interpolations) to provide better messages and user guidance
for these cases.

Change-Id: I3dd1b2ad3bca33be393e65be5e72f4fb9544a46a
2026-02-11 12:24:35 +01:00
rootile a2c91c000e f2: migrate build-delete.sh
Change-Id: I457620a33514477eccb449d4a6237a5ea43fe73d
2026-02-10 21:36:39 +00:00
rootile 45dfadeafa f2: move multiple-outputs.nix to global assets
Change-Id: I666af75a29727a6ea0c207e016d4723d19cbaa6f
2026-02-10 21:36:30 +00:00
eldritch horrors 51f1294bfc packaging: add asan libraries to closure-info if needed
devshells and asan build may fail to run builtins otherwise

Change-Id: Ia9a909671a00ff03822d9847aa086338a4763e86
2026-02-10 16:03:08 +01:00
eldritch horrors 95ac829cf3 libexec: unlazify launch-builder capnp message reading
StreamFdMessageReader reads message data *lazily*. if you don't access
all segments of the message before you close the underlying stream you
may find yourselv reading from something *very* different, and in this
case that something is The Void™. this causes reads to fail, writes on
the other side to fail to match, and finally our build launch to fail.
this does not lead to happy outcomes, so we will copy the full message
into a fresh new buffer *before* we try to access any of its contents.

fixes #1118

all-analysis-by: deprekated <kate@lix.systems>
Change-Id: I105540831fde855817194e9e539acf177f54a6f4
2026-02-09 17:30:05 +00:00
rootile a99b6f18c8 f2: migrate toString-path.sh
Change-Id: I862f532e94e385aa0f14c03e38e7e003c7bc83c3
2026-02-09 15:37:41 +01:00
rootile f761785099 tests/functional2/nix: refactor NixSettings
This is the long awaited refactor of the NixSettings.
It allows one to set, unset and update any and all settings with a neat
and easy-to-use interface

closes #846

Change-Id: Id4cfb5f853cc1168b506a1f6f405076f3a7cab65
2026-02-09 15:37:40 +01:00
eldritch horrors 2b4f1e076c build-remote: catch exceptions in Instance::build
this was just forgotten when the migration was done.

fixes #1083

Change-Id: I7a94edf304323b0c43e0a1cff39e5a52696c50e3
2026-02-09 11:43:56 +00:00
eldritch horrors 879b07fd3d libstore: treat more substituter failures as recoverable
if a substituter is entirely offline and cannot be queries at all we
should not be failing if other substituters are configured. likewise
if a substituter goes offline after querying but before we try using
it we should attempt to fetch that path from some other substituter.

ideally we'd treat all substituters as a single entity instead of as
one store each, then have that single entity take care of fallbacks,
retries, error reporting, etc. that requires larger rewrites though.

fixes #1061

Change-Id: I9d8fc0544ff380bf017256e8fcc82823dc634f10
2026-02-08 19:14:31 +00:00
eldritch horrors b983c15336 libutil: remove startProcess
it's only used by runProgram2, and runProgram2 can do something much better.

Change-Id: Idba563e1adbe3fd8ce07a0bb8ad4fc1b0cc057b9
2026-02-07 22:34:18 +01:00
eldritch horrors 6063ffead9 libutil: remove unused functions
Change-Id: I2b1c42460de50aff1f742856654c59fc4ce88e04
2026-02-07 20:23:33 +00:00
eldritch horrors 2cc49da1ec libmain: remove explicit std::cerr buffering
we don't use std::cerr often enough to want this, and since cerr flushes
after every operation anyway it never did anything useful to begin with.

Change-Id: Ia54be340826da5073e9a1786c463555f4f0e491c
2026-02-07 20:23:27 +00:00
eldritch horrors 909cbb0e40 libutil: improve runProgram2 log message
include argv0 if needed and program path at all times.

Change-Id: Icc5e28e32334e22f67fd58bd88784d4ddd5e583a
2026-02-07 20:34:49 +01:00
eldritch horrors 684aba046a libstore: *actually* always report launch-builder failures
kj exceptions get wrapped as Error instead of passed through as is.
luckily this also means that we can add context to them very easily

Change-Id: Icedab6c016f4434447dd38ba14138c102fc6149a
2026-02-06 15:55:53 +01:00
eldritch horrors ba4f4f917a libstore: always report launch-builder stderr on setup failures
Change-Id: Iac5d5ffe4df05714554766e591bc331405a8a108
2026-02-04 22:35:50 +00:00
eldritch horrors 8b73cbbb67 libstore: correctly initialize build request union members
oops. we have to use init* here, not get*. get returns a discarding
builder for something that was not inited previously, but the linux
cause worked anyway because the first member is created by default!

Change-Id: I40f8a12a04eef2f4e3a80d1537ac9b975490a027
2026-02-03 21:21:30 +01:00
eldritch horrors aa896041e0 libstore: asyncify build child setup completion wait
Change-Id: Ica70af2a1205830f1ca4bb48f42d09923cff2e58
2026-02-03 14:11:59 +00:00
eldritch horrors ac64c727b5 libstore: move build child launching to libexec
this allows us great flexibility in how children are launched (since the
actual launching is done by a separate executable), makes fork no longer
needed in the core codebase (outside of runProgram, anyway), and we even
get to use linux vfork to its full potential to decrease the launch cost
of sandboxes to a constant factor (previously it was O(#drvs + #deps) of
the build graph, which obviously goes to n² quickly if you are unlucky.)

Change-Id: I66e2d1b20242dc24d708666ef325fb8725bd9296
2026-02-03 14:11:33 +00:00
eldritch horrors 1079fe9884 libutil: kill process groups properly
we can have a ProcessGroup for a pid that *should* be a process group
but hasn't gotten around to setting its pgid yet. in such cases we do
want to be killing the thing anyway, not shoot into the void and hope
the right thing falls over. so far this has not been a problem due to
a mixture of just not having done this and being slow enough to work.

Change-Id: I4e0e54513252d8e18256b9286b819bfa957d70dc
2026-02-03 14:51:01 +01:00
eldritch horrors b8a9eaf1c8 libstore: don't use libutil as much for linux sandox setup
if we move this out of libstore and don't want to pull in all of libutil
with its myriad side effects std::filesystem is our best option, by far.
most notably we don't replace pathExists because std::filesystem::exists
behaves like `stat()` on symlinks, not like the `lstat()` as we require.

Change-Id: I1e488418dcabb33f2ebb73d8c3d1b43528aa51f1
2026-02-03 14:51:00 +01:00
eldritch horrors adf17a7b39 libstore: catch all exceptions in builder setup, not just lix errors
this lets us use std::filesystem and other apis to make builder setup easier.

Change-Id: Ie0303139171161887b610f845e2948fe07c143e0
2026-02-03 00:27:40 +01:00
eldritch horrors 8bd344718b libstore: transfer derivation build setup errors as strings
we will soon not have "proper" lix exceptions to report back any more.

Change-Id: I5061f289bcae64bf26d29cc9d0ec9af61315084e
2026-02-03 00:27:40 +01:00
eldritch horrors e575a3a930 libstore: reformat DarwinLocalDerivationGoal::execBuilder
it'll make diffing later a little bit easier.

Change-Id: I57b62fa0977648cf6948a07c1a103b0e1d6b6624
2026-02-03 00:27:40 +01:00
eldritch horrors 3d77ee8d94 libstore: move macos sandbox config to capnp
Change-Id: I0bc7c60329e0f24e15649c526386ba2466314b18
2026-02-02 19:30:52 +00:00
eldritch horrors 3896e265da libstore: move linux sandbox config to capnp
Change-Id: I3394353ed3f738976132c00973231af70dcffad4
2026-02-02 18:26:57 +01:00
eldritch horrors 0cc9d01ad0 libstore: move tmpDirInSandbox, enable-core-dumps, buildUser into capnp
since we're using tmpDirInSandbox as the working directory for the new
process we also rename it accordingly. buildUser likewise turns into a
different Credentials type because exposing user lock state seems odd.

Change-Id: Id4a1a6eb733f774c893f373b91c2a271a4b84185
2026-02-02 18:26:57 +01:00
eldritch horrors ac7a622b38 libstore: move builder/args/envs to capnp build request struct
Change-Id: If558e5b5ba9b195e31927ca5b5d0c2be743ce3f2
2026-02-02 18:26:56 +01:00
eldritch horrors ced825791a libstore: add capnp build request parameter struct to builders
there's nothing in here yet, we'll add that piece by piece.

Change-Id: Ib276d9e8281bb08013197db0f2bbfd8eec76b5ce
2026-02-02 18:26:56 +01:00
eldritch horrors f09ed729b5 libstore: generate darwin sandbox profile outside of sandbox process
Change-Id: I1a82e1dfa3709e1513d7acbdff50dc594cbc2323
2026-02-02 14:20:54 +00:00
eldritch horrors 9a31cc7da0 libutil, libstore: move closeExtraFDs to derivation goal
it's only used there.

Change-Id: I61ee47d37214c59c073cc9ed671ac1c82430227c
2026-02-02 14:20:54 +00:00
eldritch horrors 52590089df libutil, libstore: move bindPath to libstore linux platform bits
it's only used for linux sandbox setup, and can't be used elsewhere anyway.

Change-Id: I3560e141e5250cf9e72dc1576f87384a8e01f446
2026-02-02 14:20:54 +00:00
eldritch horrors dd54f45bc7 libstore: fix linux sandbox parent death signal handling
setting the signal is not enough, we must also check that the process we
expect to be parent to actually *is* our parent, not another process (eg
init if the daemon exited). we also have to set the death signal *after*
all set[ug]id calls, otherwise it will be cleared again by such changes.

Change-Id: I4e8c9102ea407576ed85b3203c8bb9bfb56762de
2026-02-02 14:20:54 +00:00
eldritch horrors 61e57329eb libstore: inline setupSyscallFilter
it's only used this once, and it accesses a (cached) global variable for
the filter. we want to move all sandbox setup state into a single object
soon, moving filter setup will make it a little bit easier to deal with.

Change-Id: I234d92d5ca044a16644b70bd303bfb7956c120f0
2026-02-02 14:20:54 +00:00
eldritch horrors ab6d8f513b libstore: always unmask all signals when launching build processes
when starting builders we want the inner processes to run with a blank
slate. if some signals are masked for any reason the builder processes
may attempt to send signals to each other that are never delivered; we
avoid this by unmasking all singals. since every build tree also has a
session and process group of its own we are not in danger of sending a
signal to a builder by accident from any source, so unmasking is okay.

Change-Id: I90720ed2bd44502ffb6d2bb848c05369809abeba
2026-02-02 14:20:54 +00:00
eldritch horrors 9ad8136825 libutil: always restore mounts from restoreProcessContext
daemons only need to restore the signal mask anyway, nothing else.

Change-Id: Id2a91f33ccf68f4d1af1bc526973a4bee066ff0b
2026-02-02 14:20:54 +00:00
eldritch horrors b908f9135c *: only increase stack size if evaluations are done
we don't need to mess with this rlimit for e.g. the daemon. increasing
the limit later should always be safe since we don't allocate (or map)
much before constructing the eval states that ultimately fill our heap
and could thus make stack expansion impossible after some time passes.

Change-Id: Ieafda537fbc99a6a7f83a093a981e7df947da437
2026-02-02 14:20:54 +00:00
eldritch horrors c20aaf6ca7 libstore: inline commonExecveingChildInit into single user
Change-Id: Ia389ec8c5e375b8386949c5fb031a52f27e76d37
2026-02-02 14:20:54 +00:00
eldritch horrors 1d227cbe07 libstore: extract capability raising into raiseAmbientCaps
this will be needed in other places in the future, and splitting it out
also clarifies the surrounding code. the keep-caps dance launchPasta is
doing doesn't have to be moved since it is only needed to allow setuid.

Change-Id: I6baaa138c2b1bca9626971ed3266c1a971a63acc
2026-02-02 14:20:54 +00:00
eldritch horrors 576ff2f598 update nixpkgs, pre-commit-hooks
the devshell no longer worked for us due to the recent deprecations :D
let's update pre-commit too because while it doesn't fail it does warn

Change-Id: Ic2060c82e4e97bb7a96cebd29097abefabdfe733
2026-02-02 15:08:49 +01:00
rootile 64d610fddc chore: reflect account migration
Change-Id: Iee327470932e58707473e876982cf22b392c2efa
2026-01-31 20:59:02 +00:00
piegames 16bd27fb78 deprecated-features/rec-set-overrides: Upgrade to hard error
Change-Id: Ifec24ee905e821058a7259be00460bf2988429d8
2026-01-31 21:58:33 +01:00
piegames c76632e17d deprecated-features/ancient-let: Upgrade to hard error
Change-Id: Ib856a665a8175a880b3ff52dde9d34769f24713b
2026-01-31 21:58:33 +01:00
piegames adfbc836c0 libexpr: Expand shadow-internal-symbols deprecated features to code null, true and false
Change-Id: If20efb9afced8665ba5c3b45cd09542e398867aa
2026-01-31 21:58:33 +01:00
eldritch horrors 1042d26c31 libstore: remove impersonate-linux-26 setting
it's ancient, it does not do what it was added for (improving
determinism), and it probably hasn't been needed for anything
in a very long time. we can probably get away with killing it

Change-Id: I66f5c841964d9ad62726cb2dae8d6fc42095399f
2026-01-31 20:05:45 +00:00
eldritch horrors cf9735f82e libstore: don't modify pathsInSandbox while mounting stuff
mostly because this will make it easier to change the data source for
them, and especially to change to data source to something immutable.

Change-Id: Ic5f1a55d02d4c2cc928c3f8b308d07167efb467b
2026-01-31 20:05:45 +00:00
eldritch horrors f5a2251966 libstore: move rewriteResolvConf to LinuxLocalDerivationGoal
it's only used there.

Change-Id: I9e267ce8b178ef3996d55b5980475a7e914ba0aa
2026-01-31 20:05:45 +00:00
eldritch horrors b41af64d1e libstore: compile linux syscall filter in prepareSandbox
this is literally part of preparing the sandbox.

Change-Id: Ic1a574bdaa68b5f39326b91c10198b774f7b2f7e
2026-01-31 20:05:45 +00:00
eldritch horrors 0d4baa5528 libstore: don't keep tempdirs open after we need them
closing them as soon as we're done ensure that the fd table doesn't
balloon in size, which in turn lets us build larger graphs. it also
makes forking processes cheaper due to less fd table copy overhead.

Change-Id: I233d1b7358ffe1b05680f845cd99de38b179f449
2026-01-31 20:05:45 +00:00
piegamesandCommentator2.0 7e68f93ed7 libexpr: Require whitespace between certain tokens
Fixes #135, #136

Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: Ia1880633c1ee3b9242487fbc30b6d781d88987fb
2026-01-31 20:44:34 +01:00
Commentator2.0androotile 98d0215ca2 tests/functional2: migrate substitute-truncated-nar.sh
Change-Id: I7225930ed6ec999b38bde8bcd23e7203fd4be1b6
2026-01-31 18:09:24 +01:00
piegamesandCommentator2.0 17f1bcfd2c libexpr: Deprecate or in non-keyword positions
Test cases courtesy of rhenrdic

Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: Id8df684ddd00d07b49e1c9e68bf41ee6c0e6887c
2026-01-31 15:32:28 +01:00
piegamesandCommentator2.0 af166146ff nix::parser::State::addAttr: Forbid dynamic attrs in recursive attrsets
Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: I92656b3b27f551bf286abc0d680c4a1c542337d7
2026-01-31 15:32:27 +01:00
piegamesandCommentator2.0 51dcc6ac0d nix::parser::State::addAttr: Forbid mixed-rec merges
Fixes #350, https://github.com/NixOS/nix/issues/9020

Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: If78d144dc35839b7668c0e0ad796252fcfc42ea0
2026-01-31 15:32:27 +01:00
piegamesandCommentator2.0 cbaa172775 libexpr: Warn on floating point literals without leading or trailing zero
Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: I0b58531ad091b22dc59d5717f5d1c8c814b4d2ea
2026-01-31 15:32:27 +01:00
piegamesandCommentator2.0 56dee9186f libexpr: Warn on incorrect string escapes
In Nixpkgs, there are several strings like "\d\.\d" which attempt to be
a regex but are just literally "d.d". The escaping rules are silly and
we should warn our users about that.

Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: I779b0757358fc9adc34dc140e1670b83abc93b67
2026-01-31 15:32:27 +01:00
piegamesandCommentator2.0 f1fbd1d095 libexpr: Warn on incorrect string usage
The indentation stripping semantics of strings are fairly bad and have a
few gotchas where they behave unintuitively. But the good news is, that
these cases are easy to catch and can be avoided.
This commit adds a warning in the parser when such strings are detected.

Unfortunately Nixpkgs uses this kind of a lot, so we won't be able to
actually enable this warning for a while to come.

Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>
Change-Id: I3b3b68c2eee4cd70959d3f4ca643cb6caf3a2217
2026-01-31 15:32:27 +01:00
piegames 4e1c216fd3 libexpr: Fix rec-set-overrides detection
Unfortunately, the previous code only detected superficial __overrides
and did not catch cases like `rec { __overrides.foo = 2; }`.

Change-Id: Ic38bdef1a6a3bdea91915aef44447f4ecc238259
2026-01-31 15:32:27 +01:00
piegames 9ad0ace8c0 deprecated-features: Rewrite feature descriptions
Changed the writing style of the descriptions, expanded with more
examples and rationale, and added the new timline metadata in the
frontmatter.

Change-Id: I218389e3504fc21f4eb45a927e77a41a1a70d4f5
2026-01-31 15:32:27 +01:00
piegames f289462c59 eval: Don't expose partially constructed sets
This turns several instances of unsoundness into runtime infinite
recursion errors

Fixes https://github.com/NixOS/nix/issues/7012,
https://github.com/NixOS/nix/issues/3241

Change-Id: Id8d352c5a78ef08d8913f07fe83f55c875684714
2026-01-31 15:32:27 +01:00
rootileandpiegames 7bd3202175 lix/code-generation: add timeline information to deprecated features
Change-Id: I5d5cf28c62cea116cb01bf433eb69a8c859809a8
2026-01-31 15:32:27 +01:00
Commentator2.0andpiegames 8c857790a3 lix/code-generation: clean up code properly
The code within the code-generation had tons of code-duplicates and was
overall quite meh to read, understand and expand.

This commit refactors the code-generation to make it more readable and
comprehensible, while also unifying its usage a bit more

Change-Id: I3a5df8b7d8d9b6c76e02ef47dfb151c7dab7d0ab
2026-01-31 15:32:27 +01:00
eldritch horrors 279926d215 meson: merge libs
lix, where modularity is made up and the patterns don't matter. merging
everything to match actual behavior of the system makes using rust much
easier because we'll have only *one* library to link, not half a dozen.

Change-Id: Ie3cb1db659798511128716402497697320bd0484
2026-01-30 17:29:51 +00:00
eldritch horrors 2e0cc67ec8 libstore: start pasta much earlier
starting pasta as soon as we have all namespaces it must be in available
lets it start up while we finish creating the sandbox. this may speed up
sandbox launches somewhat, but likely not enough to show up in practice.

Change-Id: Id6724cbdc48b99284cd7ba7b56c98829d74557c5
2026-01-30 00:29:27 +00:00
eldritch horrors a2500db977 libstore: remove unnecessary linux-specific RunOptions
Change-Id: I07303c2aea78cf9f17b89b5cea922271ce26f029
2026-01-30 00:29:27 +00:00
eldritch horrors d43c6dd100 libstore: use raw syscall for inVFork setgroups
Change-Id: Ia656d2697b883d2b058984787556915b34f44211
2026-01-30 00:29:27 +00:00
eldritch horrors ab4f8718f9 libstore: start pasta from a vfork child
mostly as a prototype for other process launching optimizations, but
also to move linux-only bits out of runProgram2. we want to stop the
fork+exec dance we do now and migrate to posix_spawn, but linux will
always need an amount special handling for launching build children.

Change-Id: Ied55dc0de95c05b52aaca923be2e3c1d101f47e0
2026-01-30 00:29:05 +00:00
eldritch horrors b6c8f412a2 libstore: generalize linux vfork infra to also allow exec'ing
we'll use this to run programs from a vforked child instead of using
runProgram. ideally we would like to have runProgram be as efficient
as possible, but our mount namespace handling makes this harder than
is worth dealing with right now. the linux derivation goal is a good
place to prototype functionality like this, especially since we need
fine control over credentials and file descriptor tables of children

Change-Id: Ibc356613ae10b06ea81de9575611948f5ee353b6
2026-01-29 19:00:56 +01:00
eldritch horrors 05fed0687d libstore: add processes to cgroups earlier
this was racy previously; a builder may have spawned processes before we
added it to a cgroup. these processes would not be registered correctly.

Change-Id: If60a64a798ee806d5701590a83d1015f55d7b867
2026-01-28 18:49:02 +01:00
eldritch horrors b23bbd5b19 libstore: fix personality setting for unsandboxed linux builds
oops. this was supposed to always happen on function exit.

Change-Id: I25465b4248c33389ca7e70b2a0b52dcc10d86a38
2026-01-28 18:49:02 +01:00
eldritch horrors 56988d8605 libstore: use vfork for linux sandbox launch wrappers
this halves sandbox launch overhead, reducing the build time for 3000
trivial runCommand derivations on our machine from 80 seconds to 44s.
as a nice side effect we also get better error message propagation in
some cases, most notably setgroups failing when run in lix sandboxes.

Change-Id: Ia7c50a844915d9b8a20475b90b2d0179fd2fff34
2026-01-28 15:01:13 +00:00
eldritch horrors bf3d4e8721 libstore: simplify user/net namespace setup
creating user namespaces early means we don't need pipes to signal that
a namespace has been created and set up. we'll also create the netns at
the same time because they're privilege-bound to the userns, and having
both available will let us launch pasta earlier to have it ready sooner

Change-Id: Ie66fe2ab7f50a520fb81dd90944384e168d94476
2026-01-28 15:00:55 +00:00
eldritch horrors c9fe3befc1 libstore: add vfork infra to linux platform bits
vfork can be a lot faster than fork on linux, and we want to use it.

Change-Id: If1665d3c49e525f2722b1e040cd7058f376bd20e
2026-01-28 15:00:43 +00:00
eldritch horrors 7e8f7d0e66 libstore: set up linux sandbox /etc earlier
permissions and ownership will be the same since the sandbox process
will not have changed uid/gid or umask by the time it gets around to
writing these files. all of these files contain some information the
host must provide, be it contents or configuration info of some kind

Change-Id: I0b57cb0699fd29e798ccf330dff99f571f3c0692
2026-01-28 12:41:26 +01:00
eldritch horrors 7d3dde851a libstore: make runPasta a function of LinuxLocalDerivationGoal
this way we can use it anywhere without fear of it being uninitialized.
only the linux platform bit uses this anyway, so we will move it there.

Change-Id: I35e207eec91daa8aa327c4f8b36c0dc8e703a7c4
2026-01-28 12:41:26 +01:00
eldritch horrors bd458f9f89 libstore: make privateNetwork a function of LinuxLocalDerivationGoal
it's only used there, and this avoids using it uninitialized.

Change-Id: I6bd84e3c441dc6750e8ab07822f896136586cd66
2026-01-28 12:41:26 +01:00
Raito Bezarius 57373cba6f nix/daemon: receive supplementary groups on macOS/FreeBSD
`xucred` already contain `cr_ngroups` and `cr_groups`, we just have to
use it properly.

Change-Id: Ic29b4c551f9d93e86e9ed2bef20889d27d5438f4
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-28 08:24:24 +00:00
Raito BezariusandTom Hubrecht c493fb668e nix/daemon: consider supplementary groups during authentication
Two things happens here:

- we consider supplementary groups that are known for authentication,
fixes #968.

- we check supplementary groups if they are our build users group and
throw an error if they are (new behavior).

Nonetheless, we did not remove the ability for `matchUser` to recurse
and check for groups that the user may have but the connection might not
have communicated as part of their groups, i.e. if a process reduces its
list of groups via a call to setgroups, it will still be authorized.
This will come in another commit.

The authorization NixOS test has been extended with a store ping test
running in systemd with DynamicUser=true *AND* a supplementary group in
allowed-users.

Co-authored-by: Tom Hubrecht <github@mail.hubrecht.ovh>
Change-Id: I25b2b8304d66a04651cea523b5585a5d15ceebe8
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-28 08:24:24 +00:00
Raito Bezarius 9e55dd6b8f nix/daemon: receive supplementary groups on Linux
On Linux, SO_PEERGROUPS is an option introduced in 2017, that is, in
Linux 4.13.

Thankfully, Lix targets 5.10+ kernels minimum.

It was chosen to allocate 128 gids by default and ramp up (2x) as needed
rather than allocate a full 65k of integers as it seems wasteful. I bet
the time to the 16 allocations should incur at most an additional
millisecond on a modern system, don't quote me on that though.

This is preparation to enable ability for the daemon to vet based on
supplementary groups.

Related to #968.

Suggested-by: alois31
Suggested-by: eldritch horrors
Change-Id: I26d698327db5d174bf70ca25b0afede132bd9169
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-28 08:24:09 +00:00
Raito Bezarius dbb3edcfea nix/daemon: clean up PeerInfo
Rather than a bunch of booleans, use optional<T> as a way to convey that
the identifier is known or not.

This is preparatory work for SO_PEERGROUP usage.

Change-Id: I0e3ce69e4103f9df5a2161c695bfc650123c1549
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-28 09:20:57 +01:00
eldritch horrors 986191534e libstore: allow config loading without a home dir set
we can already handle this case (by forbidding any ~/... paths in option
values), and since builtin builders are now run via exec we may not have
a home dir set, or even available, for them to resolve. loading a config
file in this situation will fail with an error even if the config is ok.

fixes #1109

Change-Id: I3491b31558871faa34766462747e3c15d1eccc64
2026-01-27 17:13:07 +01:00
eldritch horrors ef8a6cc5f5 libutil: add tryGetHome that doesn't throw on errors
Change-Id: Ib5bcb277e39093b303fe4a66a8903a7c5692f305
2026-01-27 17:13:07 +01:00
Raito Bezarius e083a68a9f libstore/linux: forbid xattrs syscalls
xattrs are revealing some unfortunate brittleness in real world
derivations that are getting -EINVAL errors while executing their test
code.

The reason for this is that Linux checks [1] UID delegations for xattrs
writes.

In the Lix sandbox, except if you enabled a uid-range feature, you have
exactly 3 UIDs: root, nixbld and nobody.

If your test code makes use of UIDs which have not been delegated, you
will receive an EINVAL on your operation. Test code is not resilient
with respect to the number of available UIDs in their namespace.

To avoid further issues for end users who are running into spurious
derivation build failures, we forbid xattrs again for now.

For more information about the plans, please consult or chime in [2].

Fixes #1105. Reopens #838. Fixes #1103.

[1]: https://elixir.bootlin.com/linux/v6.18.6/source/fs/posix_acl.c#L257
[2]: https://zulip.lix.systems/#narrow/channel/9-Store/topic/disablement.20of.20xattrs/with/5295

Change-Id: I864066b34cd8319d2271fac1b179cb4f950d836e
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-26 18:54:51 +00:00
eldritch horrors cfabc37828 libstore: add unix:// uri protocol argument
Change-Id: I7fc27926aa1d89e2190b1deb0252ad33f2b364a5
2026-01-26 18:17:07 +00:00
eldritch horrors bdc220b8ec libstore: allow for multiple daemon sockets with preference
this will let us configure more than one socket to connect/bind to,
which in turn lets us use posix acls on sockets for access control.
we will also need something like this for the final rpc transition.

Change-Id: I9c39f14906e9bf809055ab5c94bf687745b4f69e
2026-01-26 18:17:07 +00:00
eldritch horrors f4458b8e46 libstore: simplify netrc, cafile loading for builtin builders
Change-Id: I8370a1434729c7ff2e44ddbaf173d7068e8ace9f
2026-01-25 19:47:24 +01:00
eldritch horrors 99d674b785 libstore: despecialize sandbox launching
now that builtin builders are regular executables we no longer need to
treat them specially during sandbox launch itself, only while we build
the command line and environment for the sandboxed process. we are not
far from being able to extract platform-dependent sandbox launch code,
ideally moving all of it into (much more replaceable) libexec helpers.

Change-Id: I9b7041314683c56cd70eec9b1b4eae6de228883f
2026-01-25 19:43:13 +01:00
eldritch horrors 049c7b3369 libstore: move the builtin builders to our new executable
this means that builtinFetchurl runs in a real process now, and thus we
no longer need its workarounds for running in a forked process. forking
dropped the signal handler thread and broke the curl state via sharing,
neither of which happens any more now. we can run fetchurl builtins and
their actions straight from the main thread of our builder now, and the
temporary files and settings overrides we did are now also unnecessary.

Change-Id: I738171bc120ffcd541b7ff1424fed7924c2cdc1d
2026-01-25 19:31:38 +01:00
eldritch horrors 58c3ee4c8e builtin-builder: remove unescapeNul that snuck back in
fuck

Change-Id: I5d203fc36c4a2eb2aefde9208d6cefd3619cdf03
2026-01-25 19:30:10 +01:00
eldritch horrors 5abf26a19f add a builtin-builder command for ... builtin builders
this will let us migrate the fork+do_stuff combo of builtin builders we
have today to fork+exec of this new command. we use a subcommand rather
than a simple libexec helper because we would like to avoid linking all
of lix into the simple libexec helpers if possible. this is only hookup
for the builders, none of the buiders are migrated here to ease review.

Change-Id: I9358f1f3fee6ca640c81a7bd865128ae0d0e35a5
2026-01-25 17:26:39 +00:00
eldritch horrors c50a3a426f libutil: add simple NUL escaping/unescaping functions
Change-Id: Ia4cc7b8f1058439f312066422eebfaff1c2c0c6c
2026-01-25 17:29:32 +01:00
eldritch horrors ed6a1e58ea libstore: don't call builtin builders with derivations
call them with their individual parameters instead. this will make it
much easier to turn them into executables we can exec in the sandbox.

Change-Id: Ib49cf44715b2a480fecadabd21216c69cd730ef5
2026-01-25 15:34:59 +01:00
eldritch horrors 21e8347bb6 libstore: make netrc/cafile child args plain strings again
not having the optionals set when the builder runs (e.g. because FOD
hashes were not configured correctly) could cause assertion failures
in the builder process. while this should usually not happen we *do*
want to print a useful error message here instead of a crash report.

Change-Id: I81fb1d45fcbf660d0d9a7f0c0a12c38379ecd4c6
2026-01-25 15:34:59 +01:00
rootile 2f7644c420 tests/functional2: fix wrong usage of env var
Change-Id: I37580e0d74e26e064261c98a1162fbd9e23a9d46
2026-01-23 16:15:55 +01:00
Rebecca Turnerandrootile cb34b56fea tests/functional2: Fix Python LSP by adjusting imports
See: cl/4840

When importing Python modules, we include `functional2` in the module
path, like this:

    from functional2.testlib.fixtures.env import ManagedEnv

This means that python expects to see a file like
`functional2/testlib/fixtures/env.py`. We run `pytest` from `tests/` in
the `justfile` and have `tests/functional2/__init__.py` so `pytest` in
`meson` is able to find these imports.

However, language servers generally consider the `pyproject.toml` to be
the project root, so (e.g.) `pyright` is unable to follow any of the
`functional2` imports, leading to lots of spurious errors.

In cl/4840 I moved `tests/functional2/pyproject.toml` to
`tests/pyproject.toml`, which worked but was considered aesthetically
unappealing.

This diff is much larger but it's a more elegant solution.

Change-Id: I2983c7b87f88f59a4e3521451a9f5acd6a6a6964
2026-01-23 15:06:51 +01:00
eldritch horrors 0453be06b6 libutil: remove unused RunOptions::{chdir, createSession}
Change-Id: Ib2b9f5c094233661a01ad8cea30a44e11931c941
2026-01-22 16:59:39 +01:00
eldritch horrors b5a25f0fb6 libstore: move build hook launching to libexec helper
like diff hooks before the build hooks also use runProgram features that
aren't present in posix_spawn. just like diff hooks we do not expect the
build hook processes to be so fast that launch overhead matters somehow.

Change-Id: If3c33dbd7d2ac20c95886e06d24feda312946c78
2026-01-22 16:59:37 +01:00
eldritch horrors a7f4a675b6 libutil: remove Pid::setSeparatePG
use a wrapper type instead. whether something should be treated as a
single process or a group is a type decision more than a runtime one

Change-Id: I966e998c19e74be64ddd72ab11af809d001f61b5
2026-01-22 16:57:26 +01:00
eldritch horrors 0b03ae1a13 libutil: remove unused Pid::{killSignal, setKillSignal}
Change-Id: Ic7cceef2d82a98cf8fe23260603b1262c097cad4
2026-01-22 15:23:38 +00:00
eldritch horrors 5351518c75 libstore: add a diff hook helper libexec binary
diff hooks use uid/gid switch functionality that is otherwise only
needed for linux sandbox setup and unsupported by posix_spawn. not
doing these switches inside lix core code may let us move to using
posix_spawn for most process launching in the future, and for diff
hooks the added overhead of a wrapper program really does not hurt
at all. diff hooks are expected to be expensive in terms of output
size, process launch overhead is not likely to even be noticeable.

Change-Id: Ifa4b3eedef237632db3eb88d10e6469acae01f9e
2026-01-22 15:23:38 +00:00
eldritch horrors d7b0d322f7 libstore: make diff-hooks work for non-root users
it's kind of weird to not allow diff-hooks in single user mode unless
that user is root. maybe that's why we have no tests for them? we can
at least add a test that diff hooks are run at all when we expect it.

Change-Id: I54d623b5416acda1c205cc062b0f3a33c9f4aaa7
2026-01-22 15:23:38 +00:00
eldritch horrors 36168de584 libutil: remove {Process,Run}Options::dieWithParent
nothing except the linux sandbox actually *needs* this for correctness.
the linux sandbox only uses it to ensure that builder uids are freed up
when the sandbox is torn down, and even *then* it only works as we need
it to with PID namespaces enabled since the parent death signals is not
inherited across fork, but when pid1 of a pid namespace dies the kernel
also kills all namespace members. in all other cases this flag does not
help us that much because it actively prevents child processes cleaning
up after themselves, possibly leaving more trash around than otherwise.

Change-Id: I9ae0a9e91833a91d1011375dda402ac6c0a7ef6f
2026-01-22 15:23:38 +00:00
Raito BezariusandNiko Klanecek 728d2bfee7 contrib/plugins: add mTLS binary cache store plugin
Adds an example plugin implementing an mTLS-enabled binary cache store
(https+mtls:// scheme) using client certificates for authentication.

Darwin fix: don't link liblix* into plugins (host resolves symbols at
runtime via dynamic_lookup). Explicitly link curl so it binds to
Nix-store libcurl, not /usr/lib/libcurl. This prevents the plugin's
curl_easy_setopt calls from operating on the wrong libcurl instance.

Test portability: BSD sed -i wrapper, OpenSSL -sha256 for cert signing,
redirect test server output to log file.

Change-Id: I652b987d3ac45e31df50ff4ba1f523294438c2b6
2026-01-21 22:50:35 +00:00
eldritch horrors 7068cbf010 libstore: extract env and args rewriting from child
this really doesn't have to be here, it doesn't help very much. doing it
in the parent is cheap enough to not care and sandbox setup is not async
yet *anyway*, so we would not even notice if the old way was any faster.

Change-Id: I5a3a99af0fa5928e9a42f9c6589d98ff38b8c775
2026-01-21 15:59:30 +01:00
eldritch horrors 6da0389d0f libstore: move netrc/ca init outside of the build child process
this will make it easier to turn build sandbox processes into helpers.
the point they were at was effectivly unsandboxed except for a few fds
that were redirected by commonExecveingChildInit, which only made logs
of any errors that much harder to convey from the child to the parent.

Change-Id: I67006eb33e1e13311bb8d14e6a0c3d5e6baf0c13
2026-01-21 15:59:30 +01:00
eldritch horrors 5ba9a3961c libstore: move setupSyscallFilter to linux platform bits
setting them that little bit later really doesn't hurt us at all.

Change-Id: I6b50fbe0b58d037de729748cb4f87dd628bd111b
2026-01-21 15:59:30 +01:00
eldritch horrors 95c65ce637 libstore: move setPersonality to linux platform
it doesn't do anything anywhere else, and personality setup is not a
critical operation (all it does is change which arch uname returns).

Change-Id: I39d7fcc4916e6882e49191d2294f9b7ee0dbbcd0
2026-01-21 15:59:30 +01:00
eldritch horrors 6edbef7338 libstore: move some macos-specific bits to platform
Change-Id: I9236ffb8e098d09215067b872b5da5e210557815
2026-01-21 15:59:30 +01:00
eldritch horrors c39488d2a4 libstore: move some linux-specific child setup to platform code
best viewed with --color-moved --color-moved-ws=all

Change-Id: I3738f07fd0b39498abf253967906270dc0b215f4
2026-01-21 15:59:30 +01:00
eldritch horrors 113c6fd618 libstore: reformat bits of LocalDerivationGoal
mathbb overbar sigh

Change-Id: I9b5361ba03ff11a89773f7da2262d38fbf39b7af
2026-01-21 15:59:30 +01:00
eldritch horrors 3937eb9ecc libstore: open builder log pty in parent
there's no need to do it in the fork, we're not changing security
domains before opening the pty anyway. we do change who owns this
pty device, but since we change it via chown we can just *not* do
that before we have an open fd to the pty. in practice this isn't
even necessary because the daemon runs as root, but if we ever do
run the daemon as an unprivileged user we'd need this to be split

Change-Id: I35264ab2954c7ba2c9c24c927366d64acada6772
2026-01-21 15:59:30 +01:00
eldritch horrors 697a86c4af libutil/libstore: move namespace support checks to libexec
this also requires moving namespace support information into Worker and
out of function-scope static variables, otherwise we can't use async IO
for the libexec helper output. we could set the fd to blocking for just
one CL and extract the Worker changes into another that the reverts the
blocking fd usage, but that seems not warranted for the scope of these.

Change-Id: I6996fab1ae74693d50cefb6a6a9c21d61dada1d9
2026-01-20 22:42:53 +00:00
eldritch horrors be27e9696b libutil: move unix chdir+bind/connect to libexec
Change-Id: Ie07ece701454153d3d5c6c34e5613c0d1d5fae03
2026-01-20 22:42:53 +00:00
Justin ! 41a68f206f treewide: print* -> format* for functions not printing
Those functions have been recently refactored to return a formatted
`string` or take an `std::ostream` and only do the formatting have been
renamed to match what they're actually doing.

Change-Id: I3fe32fbe8723c2d93226370b8dd297f16a6a6964
2026-01-20 22:31:59 +00:00
eldritch horrors 761f8ab6eb libutil: fix libexec helper args span calculation
fucking hate C

Change-Id: I678c9eda32911ce7ea5e76c4274b71e45e7f3790
2026-01-20 19:16:00 +01:00
eldritch horrors 8039d69818 libutil: move killUser innards to libexec
Change-Id: Iddd3099c31c91b18c946f7ba2db79c221e7686fe
2026-01-20 16:43:23 +01:00
eldritch horrors d9187b4ee0 libmain: run pagers with a libexec helper
this is mostly a test and example for the libexec helper infrastructure,
but it also lets us simplify pager launching until we we can more easily
handle executable-not-found errors the launch fallbacks would cause when
using runProgram2 instead of fork. ideally we'd use `posix_spawn` later.

fixes #1104

Change-Id: Ia33cc12e8a9d60ffad6f5c055bb1b8b596810e64
2026-01-20 14:02:12 +00:00
eldritch horrors 9921615410 libutil: add libexec helper infrastructure
the new libexec directory is not available as a setting like other
directories (e.g. binDir) are since we consider libexec helpers to
be very internal. repointing them is like repointing a .so file we
dynamically link to; it can work, but needs much more preparation.

Change-Id: I40e64be0b32276f2864c0f2eb0b998d4c8ce7c88
2026-01-20 13:53:44 +00:00
eldritch horrors 9b334faa81 meson: use escaping functions for config.h defines
Change-Id: If7677d8040e0da0b72fc9498f2c920a0f1bb25f7
2026-01-20 13:53:44 +00:00
Pol Dellaiera 7009944370 chore: replace edolstra/flake-compat with lix-project/flake-compat
Change-Id: Ia7409ecb2f61d1ff6c8c4031025226e8549b22b6
2026-01-20 12:31:41 +00:00
Commentator2.0 eca222c7ca tests/functional2: migrate dump-db.sh
Change-Id: Ife8ff62add37f50867f55a5eaa26f7a68fad1c78
2026-01-20 10:08:36 +00:00
Commentator2.0 cdd8508bc9 tests/functional2: Provide a shortcut to clear a store
Change-Id: Ic28fb8a81ef95a1b83fa8099f5337e89f630f8e1
2026-01-20 10:08:14 +00:00
eldritch horrors d5bdc1c240 tests: remove outdated comment in test-session
we *are* using runProgram2, just not its builtin stdout stream.

Change-Id: I1766a9e443f539979f1f780a6d32294d103fb10f
2026-01-19 20:31:30 +00:00
eldritch horrors e2991e1245 libstore: use runProgram2 to launch build hooks
we don't need the full sandbox setup helpers for this: mount namespaces
do not need to be kept, loggers are not needed, and redirections can be
done by runProgram2. once the build hook is removed we will not run the
communication bits from a different process anyway, this prepares that.

Change-Id: I95d28f7c2c25e43ccd82b448d270403ce4f28852
2026-01-19 19:46:29 +00:00
eldritch horrors f2432be62d libstore: use runProgram2 for ssh connections
we do not need explict redirection management now, and dieWithParent
doesn't need an override either. we'd much prefer to kill ssh if the
process in charge exits; even ssh multiplexers are not fazed by this

Change-Id: I81e28b7605df73c887878ea4716228c7ad0f5c6f
2026-01-19 19:45:28 +00:00
eldritch horrors 39869c8b35 libutil: add setsid support to runProgram2
Change-Id: I9c023f2497cab12f1a7bfafd0baa82ffb5912d3e
2026-01-19 19:28:46 +01:00
eldritch horrors 6c7a80e449 libutil: reformat runProgram2
yeah. sorry about that.

Change-Id: I33d55d0014a53346a5c0ce07091a086374172b30
2026-01-19 19:28:46 +01:00
eldritch horrors a28dc8f77f tests: use runProgram2 for repl tests
the redirections the tests did were once not possible with runProgram2,
but they have been for a while now. we should use them instead of fork.

Change-Id: Ia422c8941ed04a9403dee68bfe938d68952253da
2026-01-19 19:28:46 +01:00
eldritch horrors 1719d60531 libutil: return pid object from RunningProgram::release
returning the pid as a pid_t instead of as a Pid raii wrapper is only
convenient for daemon use (where it'll eventually go away). using the
released pid correctly in other places is harder without the wrapper.

Change-Id: Ib42a2f357d2f0849beabd015b321bfff31334eda
2026-01-19 19:28:46 +01:00
Tom Hubrecht 7d764670c8 nix/path-info: Don't print missing paths as no fetch can be done
Fixes #323

Let's now all go an a little rant about spaghetti code...

The result of this code is that the missing paths are not printed
anymore. The basic issue was that the parent class of this command is
StorePathsCommand, which inherits from BuiltPathsCommand, and their
purpose is to work on path that are clearly in the store, building them
if needed (and ofc telling the user about what's missing), the sequance
of calls is:

- BuiltPathsCommand::run(ref<Store> store, Installables && installables)
- Installable::toBuiltPaths( *getEvaluator()->begin(aio()),
getEvalStore(), store, realiseMode, operateOn, installables);
  where operateOn is Output by default, realiseMode is Derivation, so
the only thing that can be built are the derivations for the required
installables
- Installable::build(state, evalStore, store, mode, installables)
- Installable::build2(state, evalStore, store, mode, installables,
bMode)

And that final call has the following:

```
    switch (mode) {

    case Realise::Nothing:
    case Realise::Derivation:
        state.aio.blockOn(printMissing(store, pathsToBuild, lvlError));
```

So there were two options, hack a new spaghetti in the existing
spaghetti code, or condense all those calls that are actually useless in
our case because they mostly transform a list of installables into a map
from installables to their BuiltPath which are then iterated to retrieve
the final outputs, whereas it is possible to directly get the required
paths in a much more efficient manner and without printing unrequired
stuff through a multitude of intertwined function calls by simply
replacing one method that was previously inherited from the grandparent
class

Change-Id: I1d2baaef5a099cd98b63b5346f2613914c6cd2ac
2026-01-18 20:25:39 +00:00
eldritch horrors 54180f4c35 libmain: remove RunPager
it's no longer needed now that withPager exists. also fix a
logger-never-resumed bug that never showed up in the world.

Change-Id: I7311a50896f5291364320ec4c88506dc3bb11d4c
2026-01-18 19:17:14 +00:00
eldritch horrors a7bc1be03f commands: RunPager RAII -> withPager wrapper
RunPager is weird and confusing in that it replaces what stdout *is*
depending on environmental conditions. this has not caused problems,
but it's easy to imagine situations in which it would (eg if the stl
decided to capture the stdout fd by duplicating it). using a wrapper
for this also makes clear *what* actually goes into the pager; while
the previous contract was semi-reasonable it was also very implicit,
and with the proliferation of functions we had that printed directly
to stdout it would have been easy to send wrong output to the pager.

using a wrapper also makes process management much easier because we
do not have to rely on destructors to always produce correct output.

Change-Id: Ifd3760940af1ec719fe856158c913cbb9a5bf270
2026-01-18 19:17:11 +00:00
eldritch horrors 46b86ffa49 nix-store, nix-env: reformat some bits
this will make the next commit a lot more readable.

Change-Id: I74ffad9b9f635c35d51861982558a5e020ab4687
2026-01-18 19:17:09 +00:00
eldritch horrors efd8e7cb8d nix-env: don't print to stdout from printTable
return a string instead, and write that to stdout explicitly.

Change-Id: I4a8da8ad860994f4ec05997fb226041e4da302ea
2026-01-18 19:17:06 +00:00
eldritch horrors 3194e3b6f4 nix-store: don't print to stdout from printTree
print into a provided stream instead.

Change-Id: I52495154163e40d05b6897aa129eb9b3d81348dc
2026-01-18 19:17:04 +00:00
eldritch horrors 98cb3014e8 legacycmd: don't print to stdout from printDotGraph
return a string instead, and write that to stdout explicitly.

Change-Id: I21e7a1eb22f2772e31b754823f64f941be080c56
2026-01-18 19:16:45 +00:00
eldritch horrors 49c698cf7f legacycmd: don't print to stdout from printGraphML
return a string instead, and write that to stdout explicitly.

Change-Id: Ia2d2019064da16fd35630217c445b4bcc4cdf2c2
2026-01-18 19:16:39 +00:00
eldritch horrors 7be922b3c8 libutil: remove unused blockInt
this has been unused since ab3ce1cc13,
which is now almost ten years ago. surely it was just forgotten then

Change-Id: Ib93b52d4ce5f19629432c5f91ff426582c57f99b
2026-01-18 19:16:33 +00:00
eldritch horrors 8b114520a2 libstore: make Pool::get fully cancel-safe
cancelling a get() promise could leave the pool with allegedly in use
resource handles that do not actually exist. this would cause asserts
in ~Pool to fire (and crash the entire program due to bad accounting)

probably fixes #1041

Change-Id: Ic61ab9b658f02f71e8be7577b8a1115600846f86
2026-01-18 17:22:41 +00:00
eldritch horrors 48d5e9f07d meson: remove prelinking
the issues it was solving are fixed now :)

Change-Id: I4f38d3ada22f454b57ea8245eadede0500e29451
2026-01-18 15:04:22 +00:00
eldritch horrors cef9572c24 meson: use combined library as dependency for executables
Change-Id: I1b6be3edff83c24d1c3ba3f7b4bfeb0e240039bb
2026-01-16 16:52:03 +00:00
eldritch horrors dbdc3ee28c meson: unify pkgconfig files
merge all pkgconfig-found libraries into a single one and redirect all
existing lib files to the merged variant. the clean separation between
libraries is largely fictional anyway because the main config block is
in libstore and cannot reasonably be moved out, or because libutil has
assumptions built into its behavior that libmain later establishes, or
because libexpr messes with global boehmgc configuration. nearly every
kind of layering violation imaginable can be found *some*where in lix,
and not pretending that this is not the case will let us clean up some
of them. this will also allow us to merge these libraries at the meson
level which is itself necessary to make rust code easier to integrate.

Change-Id: I172f8a08d5d90ded0a0a99fd9e0fa5d804db00a7
2026-01-15 21:50:40 +00:00
Raito Bezariusandeldritch horrors 62519f8d83 libstore/local-store: remove xattrs all the time
xattrs scrubbing was gated behind Linux platforms, but Lix can safely
assume that POSIX APIs are available.

macOS implements these APIs modulo some creative ideas.

Fixes #1008.

Change-Id: I1566df4923bf24092d3fd32ccf6a96e4256e87b2
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-15 15:53:38 +00:00
Raito Bezariusandeldritch horrors b6d5e3f05a libstore/platform/linux: allow xattrs in the sandbox
Fixes #838.

xattrs were historically disabled in 2017, since then, NFS v4.2 gained
support for xattrs and almost all filesystems support xattrs. In
addition, moving the build directory to a xattrs-supporting filesystem
is always an option. Programs may exploit xattrs (including ACLs) during
their build process and testing phase, to better serve these programs,
we will remove this limitation.

Lix will use POSIX ACLs for its UNIX domain sockets in the future and be
one of these programs which will run tests making use of xattrs, while
not writing any xattrs in the derivation outputs themselves.

xattrs are still scrubbed from derivation outputs so it is not possible
to obtain an advantage by writing a security-related xattr to a well
chosen file.

Tests were added to test these scenarios on Linux. Darwin is carefully
excluded because of #1008 and #1090, solving that is welcome. In the
meantime, they are marked xfail.

Change-Id: Ia3255eeb8442e83db4f10dcb5a51cbc368a2550d
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-15 16:40:47 +01:00
Commentator2.0andeldritch horrors 8f474399f5 tests/functional2/nix: only convert path to physical if it isn't already
Change-Id: I88e5079ef01872302aade365444d9b028088ff95
2026-01-15 16:06:59 +01:00
Commentator2.0 042a147aff f2/lang: rename the test functions to be selectable using their expected names
one would expect the lang tests to be selectable (using `-k`) using
`eval_okay` `eval_fail` etc though this was not the case so far.

This commit renames the functions to reflect the expected names

Change-Id: I4cd340c093d774feeb4d96820d28e49c665b159f
2026-01-15 15:30:34 +01:00
eldritch horrors 60dec3eeed meson: don't install repl-overlays.nix header
it's only included in a single .cc file.

Change-Id: If8ed9b1043e40ac070776470a5b49a44d181b793
2026-01-15 14:09:17 +00:00
eldritch horrors 9183c5b182 meson: move cpp_args up one level
these defines may apply to any part of lix, not just libstore.

Change-Id: Ic75098a7aab01b101f22d9c7d94ad9c5db45ab88
2026-01-15 13:55:18 +00:00
Raito Bezarius 40b5f53755 package: pass our own lix to perl-bindings
I don't know how this was missed or no one really complained about it,
but perl-bindings was using CppNix if nix was not overlaid to our own
Lix.

If you overlay Lix manually, the resulting Lix's perl-bindings cannot
really refer to Lix itself, therefore, it's CppNix.

Change-Id: Ie5ce95564cb7fb5444acbea6124619c5121e1576
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-15 11:54:20 +00:00
Commentator2.0 455724d9dc tests/functional2: rename binary cache directory for easier debugging which (cache) cache is being used
Change-Id: Id5a446422a8e1535ada723115bb2d8a10b0f2b8a
2026-01-15 11:37:02 +00:00
eldritch horrors 63b0a01d75 *: remove GlobalConfig static initializers
Change-Id: I23f8d24eb586fb4756e60a8bd5b76966a9febd31
2026-01-14 22:43:29 +00:00
eldritch horrors 8285288540 libexpr: fix app chain extension
during the value rewrite we accidentally broke extension of incomplete
primop application. this only shows up when binding on incomplete call
to a primop to a name, binding an incomplete call to *that* to another
name, and then finally calling the second binding with enough args for
a complete primop application. since this only shows up when calling a
primop with three or more args it took a while to surface. we have few
builtins that match this: foldl', replaceStrings, and substring. these
are not used incompletely in this manner very often, so this lingered.

fixes #1102

Change-Id: I218dffc14ae876efc86a86c7eb6c895e2405201c
2026-01-14 22:05:16 +00:00
eldritch horrors 6cc2ef7c6d libexpr: remove RegisterPrimOp static initializer helper
Change-Id: I0cc6d54fca26c66b13f930303086b08b2afb4d54
2026-01-14 16:22:08 +00:00
eldritch horrors 14de5fa627 *: fix non-local-dir includes
these ended up referring to different directories and would break during
source reorganization (or even just including them in different places).

Change-Id: I91e8db04e3d3565efd5920982ed5bc59d2c27058
2026-01-14 16:22:08 +00:00
eldritch horrors e0d6271fc1 libstore: fix incorrect docs for plugin-files
RegisterCommand was renamed in b30556f8f1
and de-static-ified in 4d9fe67430. adding
new settings was never possible with static instances since settings do
need an existing Config instance during construction; GlobalConfig must
be used to add settings. it is not possible to change existing configs.

Change-Id: I26af8abc375ba5883fce060ffefc710d6dfbca4c
2026-01-14 16:22:08 +00:00
K900 543bc5cf6b package: more specific warning conditions
Avoids warning spam if overridden with nixos-unstable as an input.

Change-Id: I7cc4da757371c582366bc13adcbce742e312b5c7
2026-01-14 18:09:13 +03:00
Alois Wohlschlager 58ffd67704 packaging: adjust pkg-config files after the rust-monocrate changes
Since lix-doc is no longer a separate library, the pkg-config files were broken
for static builds. Adjust them to refer to the new monocrate library instead.

Actually, since the monocrate library is static in all cases it needs to be
linked explicitly even when everything else is linked dynamically. I assume
this only doesn't break the dynamic nix-eval-jobs because it doesn't actually
use anything from it.

Change-Id: Icf29938688f4fa87425ff346a3105ef56a6a6964
2026-01-13 14:22:01 +00:00
Tom Hubrecht f431464382 libutil/hash: Simplify some parts
Use a span representing the underlying hash, this allows comparing based
on those spans. Other minor tweaks to the header file.

Change-Id: Ie05960439e60500109083c06d347d6cdf41bfda8
2026-01-12 15:56:05 +01:00
Raito Bezarius 45783a0435 lix/nix-shell: partial revert shebang mitigations for macOS
I54d04a770b8e78484815db88a8bc88776a6a6964 introduced shebangs in many
places to satisfy macOS needs.

Unfortunately, our rc shell logic is non-trivial and is exploited by
external piece of code such as
https://github.com/chisui/zsh-nix-shell/blob/master/nix-shell.plugin.zsh#L78
to keep shells intact while nix-shell-ing.

We go for a partial revert because there's no obvious fix on the short
term. This reintroduces macOS random bugs during builds until we figure
out a proper fix.

Related discussion:
https://zulip.lix.systems/#narrow/channel/7-Infra/topic/.60macos-builder02.60.20DISABLED/near/4538

Change-Id: I8245f89c10302c2b13da691e441b1c4d5c797e9a
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-11 12:50:47 +00:00
Tom Hubrecht e29263b638 libutil/hash: Add default values for Hash::to_string
The sane default is to print in SRI format, and include the hash type

Change-Id: I7efcb5dcfbe56c82dbf1928e2bb35cdd3ff089c6
2026-01-10 18:26:15 +00:00
Tom Hubrecht 16d884bd1f fix(log-format): Apply the required setting with the nix2 cli
Fixes #1099

Change-Id: I658743aae7ec7a7f295c849079166a5940d93e82
2026-01-10 18:12:01 +00:00
Raito Bezarius e9cccd47e2 libstore/build: report better error messages for --check
When --check is ran with no output, this is seen as having *SOME*
invalid outputs, actually, ALL of them are invalid here.

Instead of reporting a confusing error, let's consider ALL of outputs
being invalid to be no output at all available and advise the user to
rerun the build without --check.

If there's *some* (>0) invalid outputs, let's print them exactly to give
a chance to the user to remediate this.

Fixes #485.

Change-Id: I00955ef9ea4f129e2c98d68c73b1e981f90278a0
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-10 12:42:50 +01:00
Commentator2.0 8f9ed687da code-generation: run ruff
Change-Id: I591247ed56f89feba5daf3cbb94211d72a3ba99c
2026-01-10 00:07:33 +00:00
Qyriad 0d3fdbdb54 Exorcise MORE Darwin test demons because functional1 is /awful/
Yeah uh, I don't think `$shell` is ever set in the functional1
environment. Pretty sure this has been expanding to `''` THIS WHOLE
TIME.

Also `SHELL` is `/sbin/nologin` in that builder. idk why so I'm just
passing `shell` unconditionally in functional's `mkDerivation` helper.

Maybe next we should put `set -euo pipefail` into all these test
builders?

Change-Id: Ie5fb85305932c03a901ba84ffcce48f16a6a6964
2026-01-09 18:13:29 +01:00
Qyriad 68a72d2bdf Finally exorcise Darwin Demons causing flakey functional tests
macos-builder02 in particular has been having problems for a while now
that no one could reproduce. We believe we have finally found the cause:
missing shebangs, not just in the tests themselves but *also* in the
inline scripts `nix-shell` itself writes.

Fixes #1042.
I believe this will also fix #1093.

See also: https://github.com/NixOS/nix/pull/14778

Change-Id: I54d04a770b8e78484815db88a8bc88776a6a6964
2026-01-09 12:28:19 +01:00
Qyriad 0800b1588e add release notes for the repl load fixes
Change-Id: I09bc11de2779b6a5f0372a70ba3abb716a6a6964
2026-01-08 18:35:13 +01:00
Raito BezariusandQyriad 6cbbe19b5c libcmd/repl: :load failure clean up loaded files
When `:load`-ing a file that doesn't result in a successful outcome, the
"loaded" file is removed again from the list of loaded files.

This avoids having it be used as part of `:reload` which will probably
not result in a positive outcome.

Instead, the user is expected to retry `:load` before issuing a
`:reload`.

Fixes #50.

Change-Id: I85d025cf39f79e8e02117628bffa20c81917dc3f
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-08 18:35:13 +01:00
Raito BezariusandQyriad f4be01b4be libcmd/repl: do not clear the environment on empty reloads
If `:reload` is used with no file loaded, the environment is completely
cleared.

That's a surprising behavior and one of the root cause behind #50.

Environment clear is only performed if there's files to reload.

Change-Id: Icb014f490a83aaa4d758dbf37822db16d5bb65c1
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-08 18:35:13 +01:00
Raito BezariusandQyriad 0f1208c406 libcmd/repl: reload flake references
Change-Id: I87beaf92c7fa4238452d0c82051b42f0e3ca19a5
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-08 18:35:13 +01:00
Qyriad 7be72ca667 libcmd/repl: refactor to preserve order across :l/:lf
Change-Id: I109bdd21a69aa5e6d7a8cc86350662cd6a6a6964
2026-01-08 18:19:04 +01:00
Qyriad 851c4e372e add log-format setting to release notes (oops)
This was mistakenly left out of b97b2e858bab¹. oopsie, soz

[1]: b97b2e858b

Change-Id: I1b7210143d66480b6a8a044f0db5f0cd6a6a6964
2026-01-08 11:21:48 +01:00
Tom Hubrecht 1bd381654c libutil/hash: Drop printHash16or32 function
Its only use is in nix prefetch, inline it there instead

Change-Id: Ibb60df41a205cde2a4f383e8cff05dc6d4c032b8
2026-01-07 16:04:52 +00:00
Raito BezariusandQyriad 43434d675e libcmd/repl: track loaded flake references
Only successful loads counts towards the list of loaded flake
references.

Change-Id: I04128f90e57ef8352183d72dc6def7a09d52173a
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-07 16:28:30 +01:00
Qyriad 1ae5610a4e libutil: cleanup abstract-config.{cc,hh} a little
Change-Id: I472682ece81718c63cb7c9053b6249836a6a6964
2026-01-06 16:35:49 +01:00
Qyriad ed16987d47 libutil: extract out AbstractConfig
libutil config.{hh,cc} and libstore/globals.{hh,cc} contain so many
interrelated things. Hopefully we can separate them out a little bit for
clarity.


Change-Id: Ib78fc46fe305d13aada8886e2e168d446a6a6964
2026-01-06 16:35:49 +01:00
Qyriad 03780ad850 remove unused includes in libstore/globals.hh
Change-Id: I14e31b32458b5caa20cbfa9b116c08316a6a6964
2026-01-06 16:35:49 +01:00
Qyriad b97b2e858b feat: make log-format a setting
Vaguely one half of #186.
Fixes #827.

Change-Id: Ie6a296465beb089bf812ea27091648ca6a6a6964
2026-01-06 16:35:49 +01:00
Qyriad c3b70a8968 CI: -Ddefault_library=both
This makes that the default for all builds... which I'm not sure is the
right option, but it is also very cheap to do so, and adding an entire
other Lix build just for static libraries (not to be confused with
static Lix) would be prohibitively expensive.

Change-Id: Id173c77cfa62886724378ca599d21c8c6a6a6964
2026-01-06 16:35:49 +01:00
Qyriad 03dc13a314 rust support in libutil via rust-monocrate
Co-authored-by: Jade Lovelace <jadel@mercury.com>

Change-Id: I026f271b07c9e27012f9ee1c16a2a1f4ba7f6ba3
2026-01-06 16:35:49 +01:00
Qyriad 357ee01002 build: attempt to normalize Rust handling to support static linking
Co-authored-by: Jade Lovelance <jade@lix.systems>

Change-Id: Icfd3cabaa6abc0a39f501b4b6c6b73df4cb66e6a
2026-01-06 16:35:49 +01:00
Tom Hubrecht b482ebbbc8 treewide: Rename Base to HashFormat
Co-authored-by: Yueh-Shun Li <shamrocklee@posteo.net>

`base` is ambiguous, since it's not about the digital bases, but about
the format of hashes. Base16, Base32 and Base64 are all character maps
for binary encoding.

Documentation of the format is also added.

Cherry-pick of:
https://github.com/NixOS/nix/pull/7708/commits/838c70f62116328ce01cb41a01886e4f1b9a727f
https://github.com/NixOS/nix/pull/7708/commits/5043e6cf4ea537dfe599470797c5b310ab0e94b9

Change-Id: Ief5425f3c2056a4cca75838091e4dfa5cca88872
2026-01-06 11:22:06 +00:00
Raito Bezarius b730fab286 f2/testlib/env: build initial path via build_env
`build_env` is assumed to be a certain trivial environment, e.g. a
singleton search path.

An environment in general is either empty, contain one or more search
paths separated by a colon.

It seems that the intent was to set the `build_shell` first as a
prepended path in the managed environment then extend via the
`build_env` parts.

This fixes a usecase when the `BUILD_TEST_ENV` is non-trivial.

Change-Id: If5b8ab976d867a57ce0b8d29255f64695e30a8b2
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-06 10:13:01 +00:00
piegames 9588b1ad1b libexpr/eval: Split out expression evaluation
In an attempt to slowly split up and clean up `eval.cc`

The `Expr::eval` functions contain the most important logic when needing
to touch something on the evaluator, and having them spread across the
3kloc eval.cc file was really annoying. This should help, though more
cleanups are yet to come

Change-Id: I2c2d15a024ab1ec3fc5591f628d6768341a1c8ab
2026-01-05 23:54:34 +01:00
Tom Hubrecht 7b8947ea63 tests/evalNixpkgs: Split out into its own file and set NIX_CONFIG
This adds a way to control the deprecated features that need to be
enable while evaluating the specific nixpkgs version

Change-Id: Ia2b9a29f1966d4d5f32239a36ba8270330007da9
2026-01-04 23:00:24 +00:00
Tom Hubrecht cfedc951b6 tests/nixpkgsLib: Split out into its own file and set NIX_CONFIG
This avoids rebuilding Lix each time we need to modify the lib tests
(as flake.nix stays unchanged), and adds a way to control the deprecated
features that need to be enable while evaluating the nixpkgs lib
testsuite

Change-Id: I2baa1cf90effcaf9d53337c6a7a5b24d6297178c
2026-01-04 22:52:32 +00:00
Raito Bezarius f683332bb3 f2/testlib/fixtures/nix: support flags on nix.eval
Certain evaluation requires to pass impurity arguments, add `flags`
to add more arguments to the instantiation.

Change-Id: I538ca2ff12c07cc66e845b42f81baa87f11b8f0f
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-04 22:09:39 +00:00
Raito Bezarius f981162bf3 f2/testlib/fixtures/env: test_root cannot be None
`test_root` can never be `None`.

Change-Id: I9ed344b55a733ad92ffa79e6799e44d97285109f
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-04 22:09:33 +00:00
Raito Bezarius 8b5c085aca f2/testlib/fixtures/env: home cannot be None
Is there a situation where `home` can be None? This hinders the ability
to use it quickly without type gating in the test code itself.

Change-Id: Idd739ddad67e10d6f7a6aad283c0e3b7cd08106a
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-04 20:40:18 +00:00
Raito Bezarius 5ae8f62146 lix/libutil/cgroup: remove trailing \n in cgroup.controllers
Otherwise, this result in debug traces with a \n cutting the list of
controllers.

Change-Id: I8aba6379d335c4edab9d9ddb3fb411813d8dc426
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-04 18:23:32 +00:00
Raito Bezarius 63871751ce linux/cgroups: rename cgroups to nix-build@$drvHash-$uid
The prior use of the UID is uninteresting in general for consumers who
wants to learn things about _what_ the build is, not what is the UID of
the build user running it.

Achieving this with a place where a mapping between cgroup names and
build requests are maintained is non trivial because there's no "global"
daemon that keeps track of this information and such a daemon would
require a persistent location to track this.

Rather than solving that, we will just encode the derivation hash inside
the cgroup name. Userspace can simply pull this apart and query Nix to
obtain the original corresponding derivation for more information.

This provides userspace with a way to map cgroup names to pnames for
example. Going further, if you have a map between attribute paths and
derivation hashes, you can power a database of cgroup metrics per
attribute paths by combining all of that.

In addition to this rename, we adopt a systemd-ish convention for
template units (`@`).

As a result, userspace tooling that will scrape cgroup metrics will
discover a consistent path as long as they filter out the UID part,
especially in context of Id6c458aad30eaa08c3609ac8280a7dde8e8f3cf9
change.

This problem is tracked under #1073.

Change-Id: I238d0568a3e4b1ff3057781c0639528d666b4d37
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-04 18:23:32 +00:00
eldritch horrors 56d6ac3114 *: wrap nlohmann exceptions at the source
nlohmann has customization points for exception throws. we can use these
instead and wrap json exceptions at the source instead of playing a game
of whack-a-mole with json errors all over the tree. since nlohmann needs
macros set to achieve this we can no longer precompile its headers *and*
must forbid including it anywhere without the proper defines or ordering
of include directives will break lix with ODR violations, if we see them
at all before we get another json-related bug report. a new lint will be
in charge of ensuring this doesn't happen. we also re-allow direct calls
to nlohmann json parsing since error handling is no longer a problem. we
will keep the wrapper for more convenient error context handling though.

fixes #1092

Change-Id: I54ecc14f5bec5e2177729b41c3703216e76cc6a3
2026-01-04 16:25:06 +00:00
Commentator2.0 8798cdcd30 tests/functional2: migrate compression-levels.sh
Change-Id: I4a0257f6c0dd7df9b0ec82d0164a3bae7e978c9c
2026-01-04 15:57:36 +01:00
Raito Bezarius e1f5a981ef libcmd/repl: rework command handler
It's 2026 and the command handler was entirely manual!

We introduce a basic command handler framework for the REPL that handles
all the previous (implicit) features reasonably well.

This also builds up the infrastructure for nicer features.

Most important feature is that now we can let external plugins adds
commands to the REPL.

There's slight REPL changes:

- errors for debugger commands are more explicit.
- short-hand have a long-hand version.
- help shows command sorted by std::map natural key sorting (based on aliases)
  while keeping the special syntaxes for the REPL language at the top.
- sections were introduced for Flakes commands.
- :st was merged into one command with an optional argument marker.

Change-Id: Ibd24f994491bf5d45d4b218fd84c0944ae5050fd
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-04 14:12:23 +01:00
piegames ee608784dd libexpr/eval: Refactor force* and eval*, introduce check*
Status quo: We have `force$Type` and `eval$Type`, both which first
produce a value and then do a type check. The type checking logic is not
consistently implemented, with lots of code duplication.
This change does:

- Introduce new `check*` functions which unify the logic (the error
handling unfortunately still needs some duplication for now)
- Make both `force*` and `eval*` use the `check*` function for the
actual type checking
- Inline and dismantle the `eval*` functions for being of little use and
little used. This makes the `ExprOp*::eval` implementations for binary
logic operators more verbose, but IMO that's a good thing: The
implementation now needs to be a lot more explicit about the
short-circuiting semantics, something which was previously hidden behind
the short-circuiting semantics of the C++ language, in a way that could
easily be overlooked and lead to confusion, which is something that
happened to me twice in a year.
- Changes `forceAttrs` and `forceList` to include the context in case
`forceValue` fails (compared to only when the type check fails). This
was done for code consistency, because I could not find any reason why
list and attrs had different semantics here than int, float and bool. So
far the visible change is minimal (see the diff on the err.exp), however
this needs vetting for potential performance regressions.

Change-Id: I33e5c706d46850c9e1126293ee01dab85ba07587
2026-01-03 22:37:20 +01:00
piegames d387c9113c libexpr: Replace StaticSymbols with NixSymbolTable
That struct has been annoying me since I've encountered it. There is no
reason for having to track all these symbols out of band in the state.

Change-Id: I5c2c0d8174af0a51f9b456cc3651d8203a406d09
2026-01-03 13:19:55 +01:00
piegames eac96ef6b5 libexpr/NixSymbolTable: Init
The names were prefixed with `sym_` to allow faithfully representing
names that start with __. (Previously the underscores were omitted, at
the cost of readability for people less familiar with the intricate
details of Nix. Is `toString` literally `toString` or is it
`__toString`? etc.) As a bonus, this allows to easily grep for any
symbol through the entire code base to find where it is used. I've done
exactly that and grouped and annotated the symbols based on their usage.

Change-Id: I230fecd9b0b18e0984ac8111c1e6381f45c5abf2
2026-01-03 13:19:55 +01:00
Rebecca Turner 80d88ce407 functional2/pyproject.toml: clarify pytest norecursedirs setting
I was pretty confused by this when I saw it, not realizing that `build`
meant `tests/functional2/build` and not the top-level Meson `build`
directory.

Change-Id: I4865f196e5bf029419c6b488e78cbfb46a6a6964
2026-01-02 10:57:43 -08:00
piegames 3917e6b63a clang-format: Raise column limit to 110
100 causes too much diff churn w.r.t. current code style

"120 cols would be nuisance for us because our two-column layout is
exactly 118 wide (not counting the line number margin)"
"Ours is exactly 118 too"

Change-Id: Ifc7f21003e1011a17a1d799afaee775aeb927fd5
2026-01-02 17:51:33 +00:00
piegames 406fde33eb clang-format: Don't compact ifs and loops onto a single line
Change-Id: I422c7ee2b9865f9354f327cd2f151a7ff6c612b1
2026-01-02 17:51:33 +00:00
piegames 9ab386880d clang-format: Reduce alignment
Change-Id: I8326dba369707bc2d736c7e44d256d037dad9614
2026-01-02 17:51:33 +00:00
eldritch horrors 7dff4efc4a testing: migrate build-remote-trustless-*
Change-Id: I3edc3fe5babc93833bfe1e7c4bdeb02dc6ac17cd
2026-01-02 15:37:09 +01:00
eldritch horrors cc5c62ad72 testing: migrate daemon-trust test
Change-Id: I65fcdbe8f9d2f5ca4654341ed4a8878ef67b841a
2026-01-02 15:37:09 +01:00
eldritch horrors 7cf17f56f4 tests/f2: add marker for tests requiring a full sandbox
Change-Id: Ia96651273510867524814c0ce10b08aa8d655181
2026-01-02 15:37:09 +01:00
eldritch horrors 8984fddeae tests/f2: add a daemon context manager to Nix
Change-Id: I9047ac8b2ab3d0ea03b245e86aab71ad0aa888a1
2026-01-02 15:37:09 +01:00
eldritch horrors f580444348 tests/f2: add async command execution
running commands in the background like this lets us test daemons.

Change-Id: I8bf687d62f084344e59f7f5a94aedde069f7f66a
2026-01-02 15:20:39 +01:00
eldritch horrors 02a9c784d5 tests/f2: make all nix.conf setting settable
Change-Id: I5a2401c961b4328b681f6f8efb708017c756dab0
2026-01-02 13:01:14 +00:00
eldritch horrors a7bd1a8a80 tests/f2: allow string lists as config values
not all values are sets. the search path for example is definitely ordered.

Change-Id: Ice94fe324319731ae3a83c757768c48576ba8b36
2026-01-02 13:01:14 +00:00
Raito Bezarius bdd6bd5e38 libcmd/repl: factor out buildWithProgressBar
This logic is used in the various build-related REPL commands and is
factored out to make it easier to write the handlers for each
build-related REPL commands.

Change-Id: Iaa18df489db75495b12924e9a76b3fff1975eb64
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-01 22:02:50 +01:00
Raito Bezarius e798115c76 libcmd/repl: factor inDebugger
The completions for debug commands is purposefully left out because it
is going to go away in the next changes.

Change-Id: Ibc78b7587de3f15857bb09a3a0732334693ad550
Signed-off-by: Raito Bezarius <raito@lix.systems>
2026-01-01 22:02:50 +01:00
eldritch horrors 25d8495451 packaging: fix a bunch of old-nixos leftovers
remove compatibility junk we no longer need from our packaging.

Change-Id: I4642cb354ba6c4a4b64e4730c98c2c68b03040f7
2026-01-01 18:50:19 +00:00
Qyriad 163060f4df fix Wdefaulted-function-deleted in Pos/Origin
This warning was only showing up in newer Nixpkgs but presumably
technically applies either way.

Change-Id: I9606c8ebc599538789d502a8af3388346a6a6964
2026-01-01 18:21:13 +01:00
Rebecca Turner 22b33b9d08 package.nix: set $BUILD_TEST_ENV/$BUILD_TEST_SHELL more consistently
cl/4796 introduced a bug where running `just test-functional2` would
hang forever on macOS but `meson test -C build --suite installcheck
functional2` would succeed because of a mismatch between the
`$BUILD_TEST_SHELL` environment variable and the `-Dbuild-test-shell`
build option set in `mesonFlags`.

We can move these definitions to `finalAttrs.buildTestShell` and similar
and use those values in _both_ `mesonFlags` and `env` in order to make
them consistent in all cases.

See: https://gerrit.lix.systems/c/lix/+/4796/comments/50def5b4_fa5671f2
Change-Id: If300bbe46d6269ace29b44156fb4a5196a6a6964
2025-12-30 11:34:44 -08:00
eldritch horrors 570f5b8d1f libutil: always include sys/syscall.h
linux always need this as well for capabilites.

fixes #1087

Change-Id: I57aebca5c9a381c392a87cdf4b144f1efe140d5f
2025-12-30 13:03:19 +00:00
Rebecca Turner bad5a4dcc5 gitignore subprojects/.wraplock
I'm not sure what's creating this file. But something is, so let's
ignore it.

Change-Id: If05fb0851630d827ecb7b75cf2cf0b466a6a6964
2025-12-29 21:24:05 +00:00
Commentator2.0 1c42640347 tests/functional2: fix build-shell not working properly on darwin when running tests outside of meson
Change-Id: If5068ad5460d08de69f64f924c4e86e56ac0559c
2025-12-29 21:06:28 +01:00
Commentator2.0 ac1b8e91d6 maintainers: run ruff
additionally, the issue_import has been removed, as our mirror has been
disconued

Change-Id: I8cb4c807db6c415b0fd340ead58be341a05e6a34
2025-12-29 17:55:16 +00:00
Maximilian Bosch fae54ba5a8 tests/regression-reference-checks: move to functional2
Change-Id: Iccc58b4f2341606bedcaf7ad3eda0bb7ea9d8cd7
2025-12-29 11:13:07 +01:00
Maximilian Bosch 76254181c7 tests/check-refs: move to functional2
Change-Id: Ied5a50d324ee55939886795ca29896c732c45237
2025-12-27 11:11:55 +01:00
Maximilian Bosch 8d21057d49 tests/functional2: use bash as builder
...and add both a static bash and busybox into the sandbox for building:

    $ /nix/store/fz43jxs5qfg5vldzk38y2hmrcl58qk18-busybox-1.36.1/bin/sh -c 'declare -A foo'
    /nix/store/fz43jxs5qfg5vldzk38y2hmrcl58qk18-busybox-1.36.1/bin/sh: declare: not found

The reason is that busybox's `sh` doesn't know about `declare` which
means it cannot build derivations with `__structuredAttrs = true;`.

Change-Id: Ie3ca431f862fd3e59dc649582704ae739ee5834a
2025-12-27 11:11:55 +01:00
Alois Wohlschlager fa62109164 tests/functional2: stop littering TMPDIR so much
Nearly each tests gets a fresh store (in the test root residing under TMPDIR),
which with default settings means 8 MiB of reserved space to be deleted by the
user in case of space shortages, which of course for a test suite is just
wasted. Stop doing that to considerably reduce the litter (experimentally, from
3.7 GiB to 67 MiB per run). The old functional test suite already did the same.

Change-Id: I912cdda6e796ea37cfee0b8fe0478e976a6a6964
2025-12-27 07:05:15 +01:00
eldritch horrors 1546ea0d5f tests/f2: make ManagedPath searchable
Change-Id: Idccf83a4471d76362153535125a269abbbb03c62
2025-12-26 20:56:51 +00:00
eldritch horrors 9ebe5acf39 tests/f2: don't set NIX_STORE_DIR unconditionally
this is only needed on macos, and only for tests that build anything. on
linux it can actually *break* stuff due to unfortunate interactions with
store url parsing, which is required to work for any remote build tests.

Change-Id: Ic6f7e090f15e129fc365d7edc56cdbc1a5686047
2025-12-26 20:14:39 +00:00
Steve WalkerandXYenon 4d67200b80 flake: Fix follow symlinks
Contributes towards #106.

(cherry picked from commit 24d11d22c31dd7773cbcef6ea077e62ea114e2a3)
Upstream-PR: https://github.com/NixOS/nix/pull/12286
Change-Id: I523c76e31f27fac5d73eff76b22894adcd6ee135
2025-12-26 13:01:28 +08:00
Jade LovelaceandRebecca Turner b2feecf7e7 libexpr: use MaintainCount for call depth
This was duplicate code.

Change-Id: I40697da80c3b8123c9cc3f10e5be5cc49c35629d
2025-12-23 14:18:11 -08:00
Commentator2.0 c0f177081b fix: tests/functional2/lang: remove empty file
apparently this file slipped through the code review (the actual test
does exist, no worries) but this empty file and init py exist, sitting
here empty. This commit drops them as they serve no purpose

see commit 1b7ad3a7ad

Change-Id: I64c4e03cd3ceedf9e430ae014127966bd8e4269d
2025-12-23 14:38:23 +01:00
K900 8f27c09a08 nix-eval-jobs: set meta.mainProgram
Change-Id: I77c645a4ddec4e90884942f1919a41e1e3cd66aa
2025-12-22 09:43:02 +03:00
Fiona Behrens 2b1c6b6e5e lix-doc: test: add rust tests to check suite
Add the rust tests defined in lix-doc to the check test suite.

Change-Id: I2677679d89fccef0f73fb93abf87334706492739
2025-12-21 14:11:30 +00:00
Seth FlynnandSergei Zimmerman 8eb57801a5 nix3: use pure/restricted eval for help pages
This avoids any complications that can arise from the environment
affecting evaluation of the help pages (which don't need to be calling
out to anything external anyways)

I don't think this is actively causing problems now - though it did in
Nix! - so this is largely preventative, but I don't really see a reason
why this was ever running in impure mode in the first place either

Based-on: https://github.com/NixOS/nix/pull/14086
Co-authored-by: Sergei Zimmerman <sergei@zimmerman.foo>
Change-Id: Ice0c760562d70c09934249edc3b767473516d372
2025-12-21 13:56:58 +00:00
Max Siling 39ee6829b2 libfetchers: fix error message for bad indirect URL
It used to say "GitHub URL ... is invalid", which is wrong and confusing.

Change-Id: I89a00aee21a56710d6afdfa0510d4e9c6a6a6964
2025-12-21 00:00:13 +03:00
eldritch horrorsandkloenk fde68055df tests: fix f2 build tests
- test_check used an old version of an error message
- test_good2 did not build an unspecified dependency
- test_attribute_selection used a fixed drv path. we
  can't keep this with the current setup because the
  drv `system` makes the drv hash platform-dependent

fixes #1081

Co-Authored-By: kloenk <me@kloenk.dev>
Change-Id: Ia009740f8b5432e83467ea451a5ff53d5e141b3f
2025-12-20 20:01:08 +00:00
eldritch horrors 521b42866d nix/daemon: socket-activate single connections
the cgroups experimental feature does not work properly without this
because we do not stop subdaemons when the main daemon is shut down.
systemd needs the assigned cgroups to be empty to restart the daemon
and thus cannot cleanly restart the daemon if any connections exist.
starting a fresh unit for each connection creates a new cgroup every
time instead of sharing any delegations and thus solves the problem.

fixes #1030

Change-Id: Id6c458aad30eaa08c3609ac8280a7dde8e8f3cf9
2025-12-20 15:09:23 +00:00
Commentator2.0 c1debca36b tests/functional2: migrate tarball.sh
Change-Id: I8fb889a5723e34453597fbce2e027fb49a859319
2025-12-19 20:44:25 +01:00
Jade Lovelace 605de55fed package.nix: stop rebuilding aws-sdk-cpp
A friend reported that this is rebuilding, which doesn't make any sense
because nixpkgs also has a lix from nightly that surely has the same
dependency and thus it surely should be built on hydra, right?

Turns out no, since they were overriding the requiredSystemFeatures to
remove big-parallel. Silly, but we can match that and get cache hits.

Change-Id: I4b1c8e850c6c38b03881354e978f41a10592ec95
2025-12-18 21:26:00 +01:00
Justin !andTom Hubrecht 32d7c02b96 nixpkgs: bump to 25.11
This bump nixpkgs input to 25.11 and fix the two warnings that were
coming with the update:

1. `pkgs.system` => `pkgs.stdenv.hostPlatform.system`
2. `runCommandNoCC` => `runCommand`

also:

1. remove cppnix 2.3 compat tests (cppnix 2.3 is officially dead now)
2. remove lowdown 1.3 compat tests (nixpkgs no longer carries it)

Co-authored-by: Tom Hubrecht <github@mail.hubrecht.ovh>

Change-Id: I78526b5d8992a6c63ecd7f0c7c1fa6346a6a6964
2025-12-17 20:59:59 +01:00
Qyriad 72b120faf5 refactor LogFormat to libutil I guess
It only debatably belongs in libutil since libutil doesn't know what a
progress bar is but whatever.

It was either that or libstore. Since I'm about to make it a setting.

Change-Id: Iba59b0a190087b316ff3191a0ddd9ec36a6a6964
2025-12-17 15:50:50 +01:00
Commentator2.0 fc0073f540 tests/functional2: provide an empty repository as a global asset (needed for flake tests)
Change-Id: Icef02d7ae9594aa73a1679bed8f98be053fb693c
2025-12-16 11:15:51 +00:00
Commentator2.0 b2ee6c36a0 tests/functional2: paritally migrate test_fixed.sh
Change-Id: I3e4479b3ca718f24f604b52a6717ce18f793553b
2025-12-16 08:31:50 +00:00
Commentator2.0 a078462013 tests/functional2: refactor global assets
make the global_assets folder more readable by placing asset pack files
within a dedicated folder instead of building up a mess similar to f1

Change-Id: Ia2c16f38eb6da96e1e73584bd91391ee56acb410
2025-12-16 08:31:40 +00:00
Jade Lovelace 70319f1840 tarfile: unit test suite
This will probably get the implementation of the fixtures revised when
we land the new extraction code, but we are setting it up to be generic
against that.

The operator-> thing is kind of a crime. But it also makes the code
vastly more readable so it's impossible to say if it's bad or not.

Change-Id: Ia5aca69cefaa03cd533ad19d20d856ff7e76a546
2025-12-15 22:42:31 +01:00
Jade Lovelace 88cea98b82 refactor: use std::unique_ptr for libarchive state, remove destructor
Change-Id: Ib16eefc17ae53874b295476fae515305525a7f2b
2025-12-15 21:21:04 +01:00
Tom Hubrecht 0ebb1c524d daemon: Make the error more explicit when the sandbox group tries to connect
Fixes #1069

Change-Id: I32ece312b0a1c4fbbc21902d71a15c6ff40b3aed
2025-12-14 20:43:20 +01:00
Tom Hubrecht b2b95775bd misc: Really fix the unused-variable warning
When everything else has failed, cast it to the void

Change-Id: I8f9769e60c359a6a17151e9199749f5c7042566f
2025-12-14 20:43:20 +01:00
Tom Hubrecht 5157fbaf2c testWithNix: Don't depend on CppNix
Change-Id: Ia0903d93796c30e370d99d02877cc93c258b8f32
2025-12-14 15:20:16 +01:00
Rebecca Turner 3e3573cb58 libutil: reformat tarfile.{cc,hh}
Change-Id: I24670300157213fba787df62931776416a6a6964
2025-12-13 16:35:22 -08:00
Max Siling 6bf187537a libfetchers: use commit hash as rev for tag refs
Instead of manually reading the ref file,
which gives the tag object hash when ref is a tag,
shell out to git.

The logic for finding the ref file is left for cache TTL tracking.

Fixes: #1070
Change-Id: I490b1e62f83cf602c56232c6081a52166a6a6964
2025-12-13 23:15:18 +03:00
Qyriad 43b1b63df9 libutil: add shim to impl operator<< in terms of std::format
Change-Id: Ie749801f669c0cfcd93b8ff559add96a6a6a6964
2025-12-13 15:07:39 +01:00
Qyriad 9d6e71bd56 feat(nix3-store-delete): unlink root and delete its closure at the same time
Feel free to bikeshed the name --unlink

Change-Id: I71a44d873d88e5a2ab300af3f0a868dd6a6a6964
2025-12-13 15:05:12 +01:00
Tony Wasserka a6f0e59c2c doc/contributing: Fix typo
`--extra-deprecated-features` with `=` is not recognized, instead it must be followed by a space.

Change-Id: I2b817b7cc6fb11a3672422a1756ba87da1623b3b
2025-12-11 18:09:46 +01:00
hansemschnokeloch 227852f221 Edit doc/manual/src/glossary.md
Change-Id: I6d70112874ae22efb440aacdff0faedc89c395d6
2025-12-11 07:46:10 +00:00
Tom Hubrecht 36a61d922c lix-clang-tidy: Avoid using llvm::Twine
> A Twine is not intended for use directly and should not be stored

Change-Id: Ie243d109bc3feb75867ed748c5e4cbcddfafd3e1
2025-12-09 17:13:36 +01:00
Tom Hubrecht 5d21b8262b clang-tidy: enable bugprone-multi-level-implicit-pointer-conversion
The default clang version in nixos 25.05 was llvm 19, we are now even
past that

Change-Id: Ieb62616fb87c4d2a8d892136a7164822aa1eceb6
2025-12-09 14:51:43 +00:00
Tom Hubrecht 50c47c340f misc: Remove unused private field, move unused variable in #if, remove virtual specifier
Those are new warnings that come with a more up-to-date llvm

Fixes #1066

Co-authored-by: eldritch horrors <pennae@lix.systems>

Change-Id: I305d0d810d12a5e8d31c7d89e0cdb3a82df71556
2025-12-09 14:29:35 +01:00
Qyriad 2c68244142 build/functional2: don't require installation for tests to run correctly
Change-Id: I9a2bd83c09c8a009e683c73bf2a669036a6a6964
2025-12-09 11:13:55 +01:00
Kate Temkin 15969c51c3 legacy/build-remote: fix a missing format string argument
Change-Id: Ic3156695a7f41367d413f2da3b5791d489576d47
2025-12-09 09:47:21 +00:00
Tom Hubrecht 3db533c637 clang-tidy: enable bugprone-implicit-widening-of-multiplication-result
Change-Id: I7c7bae6c27aa59da23097ec89305cfc60ec9e8e3
2025-12-09 08:32:37 +00:00
Qyriad b2bcd99d59 functional2: fix bug in physical_store_path_for()
I guess on aarch64-darwin dirs.store_dir can be a str?

Change-Id: If4baa1f48f641775c6e3ab9ce7a58e476a6a6964
2025-12-08 19:07:44 +01:00
Alois Wohlschlager a99842e0af nix-eval-jobs: asyncify the coordinator
Change-Id: I62007ed4d43029a4c793c0152c06490d6a6a6964
2025-12-08 18:32:12 +01:00
Raito Bezarius b5a8720a47 legacy/nix-shell: export NIX_LOG_FD
As far as I can tell, there's no harm to let know a nix-shell invocation
about NIX_LOG_FD being stderr.

Fixes #336.

Change-Id: Ifdb3591813251d4bc481158d28dc18e1489de72c
Signed-off-by: Raito Bezarius <raito@lix.systems>
2025-12-08 09:12:40 +00:00
Raito Bezarius 908acdfa2f nix3-develop: export NIX_LOG_FD
As far as I can tell, there's no harm to let stdenv know that they can
write to file descriptor 2 which is stderr inside of a nix3-develop
shell.

Contributes towards #336.

Change-Id: I51dcbcbc19a1698a0d1255f9d943d9ebd15d115d
Signed-off-by: Raito Bezarius <raito@lix.systems>
2025-12-08 09:12:40 +00:00
Maximilian Bosch be3e4bf78e tests/functional/output-cycles: move to functional2
Change-Id: I682f62a695ba7722e2b3063bf831fc50a19eb153
2025-12-07 21:47:10 +01:00
Maximilian Bosch 0a5f474a25 libstore: fix reporting output cycles on drvs with references to other drvs
Closes #1064

The culprit here is that `genGraphString` is only invoked with the
store-paths associated with the outputs of the derivation, so when
filling `dependents`, the `graph_data.find(p)` call would return the end
of the iterator when doing this for references to other store-paths.

As a result, the code wrote information behind the graph data-structure
causing a corruption. For me, this resulted in a SIGSEGV most of the
time and in a few cases in an uncaught `map::at`-exception as reported
by Niklas.

This patch changes two aspects of the original implementation:

* When filling `dependents` in the node-set, use `map.at()` instead of
  `map.find()->second`. The latter doesn't make any sense and was the
  cause of corrupting memory. The `at` would've made it far easier to
  spot this in the first place.

* Filter out store-paths that don't belong to a different output of the
  derivation when creating `outputGraph`. This variable is used on two
  places, `genGraphString` and for topological sorting.

  The latter already filters out store-paths from a different drv, so
  this is happening now when creating the variable in the first place
  such that `genGraphString` never ends up with corrupt data in the
  first place. This is the actual bugfix.

Implemented a regression-test for this case to be sure.

Change-Id: Ie02144d89c32b0a776cb1ece0601d0229315ebc3
2025-12-07 21:47:09 +01:00
eldritch horrors 6410748c9f libcmd: add raw arg access to legacy commands
we'll need this to modify argv for socket-activated daemons. this is our
replacement for the old savedArgv mechanism that was unscoped and fucky.

Change-Id: Ie048eb8ea99f1c9cd627a051292c836c83197068
2025-12-07 18:49:34 +00:00
eldritch horrors aba740a276 libcmd: remove unused savedArgv
this was only used in the pre-exec daemon days.

Change-Id: I3bbb113f9940e6980f01af60e6614a9656b0fd03
2025-12-07 18:49:34 +00:00
eldritch horrors 1e8f7c7c76 nix/daemon: remove settings copy from parent
the parent daemon does not change any settings before starting a child,
so there's nothing we may want to change that is not already set by the
config file. this also doesn't prevent changes of the config file being
applied to daemons where we do not expect it since it'll only restore a
setting to the parents' value if the child also has an override for it.

Change-Id: Ic5a9ef13458c103ec9979cb187ba8d3ce5e1e719
2025-12-07 18:49:34 +00:00
Qyriad 400b55a410 nix-eval-jobs: use C++23 to match Lix
Change-Id: Ia770f849fd43b360fc641d478abe084e6a6a6964
2025-12-07 18:34:24 +01:00
Qyriad 0714a21b03 perl-bindings: use C++23 to match Lix
Lix changed to C++23 in 4ea8c9d61¹, but the perl subproject wasn't
updated with it. This commit corrects that.

[1]: 4ea8c9d643

Change-Id: I5464138d206d87cf25762720b147487d6a6a6964
2025-12-07 18:34:24 +01:00
Commentator2.0andQyriad 0bcaffa640 functional2: add a hash_path shortcut to Nix
Co-authored-by: Qyriad <qyriad@qyriad.me>

Change-Id: If0b9213d264b60e687ceb2d4d232d23f6a6a6964
2025-12-07 15:34:03 +01:00
Qyriad f6f03d0a52 functional2: add helper to get actual store paths to Nix fixture
Co-authored-by: Commentator2.0 <lix@crystal-cavern.systems>

Change-Id: I13f8ba9d59ae863cf08109a01c638c7f6a6a6964
2025-12-07 15:34:03 +01:00
Tom Hubrecht 8ebe893854 clang-tidy: enable lix-fixincludes
The reorganization has been done

Change-Id: Ib8eec6656f375f8329fe4caefd009369aa36d8f2
2025-12-07 14:05:39 +00:00
Tom Hubrecht 1a304964aa package: Add libllvm to the inputs when linting
This should allow better stacktraces when clang-tidy fails miserably on
aarch64 machines

Change-Id: Ia795cf1dc012bd8f06b429d97184b88c80dd72cb
2025-12-07 11:40:03 +01:00
Tom Hubrecht 543ae33d26 functional2: Increase timeout in the cycles detection test
On a busy CI the 1s timeout is not always enough

Change-Id: Ie39be01ae8818df8c9026d28907f5b145a452e3b
2025-12-06 22:33:19 +00:00
Raito Bezarius 6928c6f952 libstore/store-api: offer more information about drv parsing errors
We offer the three usual options: verify, repair then delete and direct
people to report us corruption so we can fix if this is induced by us.

Fixes #447.

Change-Id: I0df61769d732d227333c206f312857c0593f7bce
Signed-off-by: Raito Bezarius <raito@lix.systems>
2025-12-06 20:30:38 +00:00
Raito Bezarius 7f32b71b6b libstore/derivations: expand error message for the first misparse
If the derivation does not start with D, do not return a simple
"expected string 'D'" error but a full error message.

This contributes towards #447.

Change-Id: Iee05f3918e4cc43e79f244ab2fd64a52cf2bb6d2
Signed-off-by: Raito Bezarius <raito@lix.systems>
2025-12-06 20:30:38 +00:00
Raito Bezarius d2ca1810b1 nix/upgrade-nix: disallow daemon connections for the store
Prior to I6a6a6964d2b5ad47ae5ea9eb11af9b6373ce2141 — `sudo nix
upgrade-nix` would perform direct store access.

This ensured a certain number of desireable properties for upgrading the
Lix binary itself.

We re-introduce direct store access for upgrading Lix binaries.

Fixes #1060.

Change-Id: I523c4d3023ed5fe9eff8fde9a266c56a0de47d8c
Signed-off-by: Raito Bezarius <raito@lix.systems>
2025-12-06 20:30:15 +00:00
Raito Bezarius 7fbb366ce2 lix/legacy/nix-build: save up 30ish chars in $NIX_BUILD_TOP
Alternative to cl/4661 discussed in #1044.

It can be assumed that `$tmpdir/build-top` can be created safely without
any risk, this way, we don't need to reuse the random directory creation
primitive.

Fixes #1044.

Change-Id: Iec52477f3047fc40959b183c607312d5a40fc8c9
Signed-off-by: Raito Bezarius <raito@lix.systems>
2025-12-06 19:48:08 +01:00
766 changed files with 22282 additions and 11646 deletions
+4 -3
View File
@@ -4,9 +4,10 @@ AccessModifierOffset: -4
AlignAfterOpenBracket: BlockIndent
AlignEscapedNewlines: Left
AlignOperands: DontAlign
AllowShortBlocksOnASingleLine: Always
AlignTrailingComments: false
AllowShortBlocksOnASingleLine: Empty
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortIfStatementsOnASingleLine: Never
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
@@ -35,7 +36,7 @@ BreakAfterAttributes: Always
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BreakConstructorInitializers: BeforeComma
ColumnLimit: 100
ColumnLimit: 110
EmptyLineAfterAccessModifier: Leave
EmptyLineBeforeAccessModifier: Leave
FixNamespaceComments: false
+2 -7
View File
@@ -8,16 +8,12 @@ Checks:
- -bugprone-narrowing-conversions
# kind of nonsense
- -bugprone-easily-swappable-parameters
# too many warnings for now
- -bugprone-implicit-widening-of-multiplication-result
# Lix's exception handling is Questionable
- -bugprone-empty-catch
# many warnings
- -bugprone-unchecked-optional-access
# many warnings, seems like a questionable lint
- -bugprone-branch-clone
# extremely noisy before clang 19: https://github.com/llvm/llvm-project/issues/93959
- -bugprone-multi-level-implicit-pointer-conversion
# we don't compile out our asserts
- -bugprone-assert-side-effect
# FIXME(jade): figure out if this warning is any good
@@ -29,9 +25,6 @@ Checks:
# crimes must be appropriately declared as crimes
- cppcoreguidelines-pro-type-cstyle-cast
- lix-*
# This can not yet be applied to Lix itself since we need to do source
# reorganization so that lix/ include paths work.
- -lix-fixincludes
# This lint is included as an example, but the lib function it replaces is
# already gone.
- -lix-hasprefixsuffix
@@ -40,3 +33,5 @@ Checks:
CheckOptions:
bugprone-reserved-identifier.AllowedIdentifiers: '__asan_default_options'
bugprone-unused-return-value.AllowCastToVoid: true
ExtraArgs: ["-Werror=unnecessary-virtual-specifier"]
+3
View File
@@ -41,3 +41,6 @@ buildtime.bin
*.pyc
**/.idea
# Yeah, I've got no clue.
/subprojects/.wraplock
+3
View File
@@ -1,2 +1,5 @@
Fiona Behrens <me@kloenk.dev>
Fiona Behrens <me@kloenk.dev> <me@kloenk.de>
rootile <lix@rootile.de>
rootile <lix@rootile.de> <commentator2.0@crystal-cavern.systems>
rootile <lix@rootile.de> <lix@crystal-cavern.systems>
Generated
+4
View File
@@ -39,6 +39,10 @@ dependencies = [
"rowan",
]
[[package]]
name = "lixutil-rs"
version = "0.0.0"
[[package]]
name = "once_cell"
version = "1.19.0"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["lix/lix-doc"]
members = ["lix/lix-doc", "lix/libutil"]
[workspace.package]
edition = "2021"
+19
View File
@@ -0,0 +1,19 @@
# Darwin: don't link liblix* into plugins (host process provides them at runtime).
# Explicitly link curl so it binds to Nix-store libcurl, not /usr/lib/libcurl.
if is_darwin
plugin_deps = [
liblix.partial_dependency(includes : true, compile_args : true),
curl,
]
else
plugin_deps = [liblix, curl]
endif
plugin_mtls_store = shared_module(
'plugin_mtls_store',
'plugin_mtls_store.cc',
dependencies : plugin_deps,
install : false,
build_by_default : true,
link_args : is_darwin ? shared_module_link_args : strict_shared_module_link_args,
)
@@ -0,0 +1,14 @@
R"(
**Store URL format**: `https+mtls://...`
This store allows a binary cache to be accessed via HTTPS with mutual TLS (client certificate authentication).
Both parameters are required:
- `tls-certificate`, a path to the TLS client certificate
- `tls-private-key`, a path to the TLS private key backing the client certificate
If you don't need mTLS, use `https://` instead.
)"
+102
View File
@@ -0,0 +1,102 @@
#include "lix/libstore/store-api.hh"
#include "lix/libutil/config.hh"
#include "lix/libstore/http-binary-cache-store.hh"
#include <stdlib.h>
#include <curl/curl.h>
namespace nix {
struct mTLSBinaryCacheStoreConfig : HttpBinaryCacheStoreConfig
{
using HttpBinaryCacheStoreConfig::HttpBinaryCacheStoreConfig;
const std::string name() override
{
return "mTLS HTTP Binary Cache Store";
}
std::string doc() override
{
return
#include "mtls-http-binary-cache-store.md"
;
}
PathsSetting<nix::Path> tlsCertificate{
this,
"",
"tls-certificate",
"Path of the TLS client certificate in PEM format as expected by CURLOPT_SSLCERT"
};
PathsSetting<nix::Path> tlsKey{
this,
"",
"tls-private-key",
"Path of the TLS client certificate private key in PEM format as expected by CURLOPT_SSLKEY"
};
};
struct mTLSBinaryCacheStoreImpl : public HttpBinaryCacheStore
{
struct Keyring
{
nix::Path tlsCertificate;
nix::Path tlsKey;
};
mTLSBinaryCacheStoreConfig config_;
std::shared_ptr<Keyring> keyring;
mTLSBinaryCacheStoreConfig & config() override
{
return config_;
}
const mTLSBinaryCacheStoreConfig & config() const override
{
return config_;
}
mTLSBinaryCacheStoreImpl(
const std::string & uriScheme, const Path & _cacheUri, mTLSBinaryCacheStoreConfig config
)
: Store(config)
, HttpBinaryCacheStore("https", _cacheUri, config)
, config_(std::move(config))
, keyring(std::make_shared<Keyring>(config_.tlsCertificate.get(), config_.tlsKey.get()))
{
}
FileTransferOptions makeOptions(Headers && headers = {}) override
{
auto options = HttpBinaryCacheStore::makeOptions(std::move(headers));
auto baseExtraSetup = std::move(options.extraSetup);
auto keyring = this->keyring;
options.extraSetup = [keyring, baseExtraSetup{std::move(baseExtraSetup)}](CURL * req) {
if (baseExtraSetup) {
baseExtraSetup(req);
}
const bool haveCert = !keyring->tlsCertificate.empty();
const bool haveKey = !keyring->tlsKey.empty();
if (!(haveCert && haveKey)) {
throw Error("https+mtls requires both tls-certificate and tls-private-key");
}
curl_easy_setopt(req, CURLOPT_SSLCERT, keyring->tlsCertificate.c_str());
curl_easy_setopt(req, CURLOPT_SSLKEY, keyring->tlsKey.c_str());
};
return options;
}
static std::set<std::string> uriSchemes()
{
return {"https+mtls"};
}
};
}
extern "C" void nix_plugin_entry()
{
nix::StoreImplementations::add<nix::mTLSBinaryCacheStoreImpl, nix::mTLSBinaryCacheStoreConfig>();
}
+15 -9
View File
@@ -1,9 +1,15 @@
(import (
let
lock = builtins.fromJSON (builtins.readFile ./flake.lock);
in
fetchTarball {
url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz";
sha256 = lock.nodes.flake-compat.locked.narHash;
}
) { src = ./.; }).defaultNix
let
lockFile = builtins.fromJSON (builtins.readFile ./flake.lock);
flake-compat-node = lockFile.nodes.${lockFile.nodes.root.inputs.flake-compat};
flake-compat = builtins.fetchTarball {
inherit (flake-compat-node.locked) url;
sha256 = flake-compat-node.locked.narHash;
};
flake = (
import flake-compat {
src = ./.;
}
);
in
flake.defaultNix
+20 -5
View File
@@ -61,11 +61,6 @@ cole-h:
display_name: Cole Helbling
github: cole-h
commentator2.0:
display_name: Commentator2.0 (Rutile)
forgejo: commentatorforall
github: CommentatorForAll
delan:
display_name: delan
forgejo: delan
@@ -104,6 +99,9 @@ goldstein:
forgejo: goldstein
github: GoldsteinE
gustavderdrache:
github: gustavderdrache
horrors:
display_name: eldritch horrors
forgejo: pennae
@@ -198,6 +196,9 @@ nan-git:
ncfavier:
github: ncfavier
nkk0:
github: nkk0
not-my-profile:
display_name: Martin Fischer
github: not-my-profile
@@ -244,9 +245,16 @@ roberth:
display_name: Robert Hensing
github: roberth
rootile:
display_name: rootile (Rutile)
forgejo: rootile
seppel3210:
github: Seppel3210
stevalkr:
github: stevalkr
teofilc:
forgejo: teofilc
github: TeofilC
@@ -273,6 +281,9 @@ vigress8:
forgejo: vigress8
github: vigress8
vlaci:
github: vlaci
vlinkz:
display_name: Victor Fuentes
forgejo: vlinkz
@@ -288,6 +299,10 @@ xanderio:
xokdvium:
github: xokdvium
xyenon:
forgejo: xyenon
github: xyenon
yorickvp:
github: yorickvp
+1 -1
View File
@@ -69,7 +69,7 @@ let
let
result = squash ''
- ${
if inlineHTML then ''<span id="conf-${name}">[`${name}`](#conf-${name})</span>'' else ''`${name}`''
if inlineHTML then ''<span id="conf-${name}">[`${name}`](#conf-${name})</span>'' else "`${name}`"
}
${indent " " body}
+7 -4
View File
@@ -41,10 +41,13 @@ manual = custom_target(
'-euo', 'pipefail',
'-c',
'''
@0@ @INPUT0@ @CURRENT_SOURCE_DIR@ > @DEPFILE@
cd @3@
@1@ build . -d @2@ | { grep -Fv "because fragment resolution isn't implemented" || :; }
cd @SOURCE_ROOT@
@0@ @INPUT0@ @3@ > @DEPFILE@
# Needs to be in lix/doc/manual for e.g. substitute.py
pushd @3@
@1@ build . -d @2@
popd
rm -rf @2@/manual
mv @2@/html @2@/manual
find @2@/manual -iname meson.build -delete
-15
View File
@@ -1,15 +0,0 @@
---
synopsis: "Add `builtins.warn` for emitting warnings from Nix code"
cls: [2248]
category: "Features"
credits: [milibopp, Qyriad]
---
Lix now has a builtin function for emitting warnings.
Like `builtins.trace`, it takes two arguments: the message to emit, and the expression to return.
_Unlike_ `builtins.trace`, `builtins.warn` requires the first argument — the message — to be a string.
In the future we may extend `builtins.warn` to accept a more structured API.
To go along with this, we also have two new config settings:
- [`debugger-on-warn`](@docroot@/command-ref/conf-file.md#conf-debugger-on-warn), which, when used with `--debugger`, makes `builtins.warn` also function like [`builtins.break`](@docroot@/language/builtins.md#builtins-break).
- [`abort-on-warn`](@docroot@/command-ref/conf-file.md#conf-abort-on-warn), which aborts evaluation entirely after the warning is emitted.
@@ -1,13 +0,0 @@
---
synopsis: "Deprecate shadowing internal files through the Nix search path"
issues: [998]
cls: [4632]
category: "Breaking Changes"
credits: [thubrecht]
---
As Lix uses the path `<nix/fetchurl.nix>` for bootstrapping purposes, the ability to shadow it by adding `nix=/some/path` (or `/other/path` that contains a `nix` directory) to the search path is not desirable.
To alleviate potential issues, Lix now emits a warning when the Nix search path contains potential shadows for internal files, which will be changed to an error in a future release.
The warning can be disabled by enabling the deprecated feature `nix-path-shadow`.
@@ -1,10 +0,0 @@
---
synopsis: "Warn instead of erroring when the final destination of a transfer changes in-flight"
cls: [4641]
issues: [fj#1004]
category: "Miscellany"
credits: [thubrecht]
---
Lix will now emit a warning during downloads where the final destination changes suddently mid-transfer instead of throwing an error.
This transfer behavior has been known to happen very rarely while fetching from some CDNs.
@@ -1,10 +0,0 @@
---
synopsis: 'functional lang migration'
issues: [lix#856]
cls: [3213, 3214, 3215, 3224, 4092, 4093, 4094, 4095, 4096, 4097, 4098, 4099, 4100, 4101, 4102, 4103, 4104, 4105, 4106, 4107, 4108, 4109, 4110, 4111, 4112, 4113, 4114, 4115, 4116, 4117, 4122, 4123, 4269, 4270, 4271, 4272, 4273, 4274, 4347, 4348, 4349, 4350, 4351, 4352, 4569, 4570, 4571, 4572, 4573, 4574, 4596, 4597, 4598, 4599, 4600, 4601, 4602, 4603, 4604, 4605]
category: Development
credits: [piegames, commentator2.0]
---
We have done it! The functional/lang framework has now been fully migrated to functional2/lang.
This means: no more `just clean` and `just install` mess and whatever because one removed a test.
The lang test suite is also getting a face lift, with an improved folder structure and restructuring of many tests.
-10
View File
@@ -1,10 +0,0 @@
---
synopsis: "Allow remote builders to be configured using TOML"
cls: [4533]
category: "Features"
credits: [commentator2.0, Qyriad]
---
Lix now supports configuring remote builders using a TOML file instead of the old, very cursed and incomprehensible format.
This comes with not only a human-understandable file, but also with better messages and error reports on misconfiguration.
A more detailed Documentation can be found on the [distributed-builds](@docroot@/advanced-topics/distributed-builds.md) Wiki-page
-8
View File
@@ -1,8 +0,0 @@
---
synopsis: "Default to showing build logs in the new-style (nix3) CLI"
cls: [4674]
category: "Miscellany"
credits: [k900]
---
Lix will now show logs by default, in addition to the progress bar, when invoked through the new-style "nix3" CLI (`nix build`, etc)
@@ -1,31 +0,0 @@
---
synopsis: "Move /root/.cache/nix to /var/cache/nix by default"
cls: [4671]
issues: [fj#634]
category: "Breaking Changes"
credits: [raito]
---
By default, Lix attempts to locate a cache directory for its operations (such
as the narinfo cache) by checking the value of `$XDG_CACHE_DIR`.
However, since the Nix daemon is a system service, using `$XDG_CACHE_DIR` is
not typical in this context.
To address this, systemd provides a better solution. Specifically, when
`CacheDirectory=` is set in the `[Service]` section of a systemd unit, it
automatically sets the `$CACHE_DIRECTORY` environment variable and systemd will
manage that cache directory for us.
Now, our systemd unit includes `CacheDirectory=nix`, which sets the
`$CACHE_DIRECTORY` and takes precedence over `$XDG_CACHE_DIR`.
If the daemon is run under user units, systemd will automatically set
`$XDG_CACHE_DIR`.
If neither of these variables is set, Lix falls back to its default behavior.
By default, Lix will try to find a cache directory for its various operations
(e.g. narinfo cache) by looking into `$XDG_CACHE_DIR`.
In summary, what was stored in `/root/.cache/nix` is now moved to
`/var/cache/nix/nix`.
-9
View File
@@ -1,9 +0,0 @@
---
synopsis: "Add an indication of nix-shell nesting depth"
cls: [4657]
issues: [fj#826]
category: "Improvements"
credits: [thubrecht]
---
When in a nix shell (either via a `nix-shell` or a `nix develop` invocation), a variable `NIX_SHELL_LEVEL` is exported to indicate the nesting depth of nix shells.
-20
View File
@@ -1,20 +0,0 @@
---
synopsis: Derivations can now be printed in detail in `nix repl`
cls: [3842]
category: Improvements
credits: [Lunaphied]
---
Traditionally derivations printed in the REPL would only print a formatted object
representing the path of the derivation file it refers to. This makes inspecting
the enhanced derivation attribute sets encountered from `mkDerivation` or similar
wrappers more difficult. Even the `:p`/`:print` command would not elaborate attribute sets
tagged as a derivation.
With this change you can now use `:p`/`:print` to directly inspect a derivation
by providing one as the top-level object. Derivation attribute sets will only be
printed two levels deep and internal derivation attrsets will remain in unexpanded
path form as before. `drvAttrs` will also be elided as these attributes are already
present in the top-level attribute set of the derivation. These heuristics provide
a balance between readability and functionality. When the `:p`/`:print` is omitted,
a bare derivation is printed in the path format as before.
@@ -1,37 +0,0 @@
---
synopsis: Remove `fetch-closure` experimental feature
issues: [fj#1010]
cls: [4595]
category: "Breaking Changes"
credits: [just1602]
---
The `fetch-closure` experimental feature has been removed.
Outside of allowing the user to import closure from binary cache,
`fetchClosure` also allow you to do the following:
* rewrite non-CA path to CA
* reject non-CA paths at fetching time
* reject CA paths at fetching time
Some people are using those mechanism to prevent users from having to build any
package and force going via the declared cache or as a way to use ancient/old
software without paying the evaluation cost of a second nixpkgs.
Both use cases are somewhat of an antipattern in Nix semantics. If the user
cannot fetch a program directly via the substituter mechanism and fall back to
local build, this is a feature AND a misconfiguration. If the user cannot build
certain derivations because they are too expensive, the build directives should
pass `-j0` or similar.
As for the second usecase, there's a different way to do it that also allows to
have a way to reproduce the paths that are hardcoded in that file, perform
`import (fetchurl "https://my-cache/${hashparts storepath}.drv")` rather, i.e.
an IFD to a possibly well known name. The backend can generate them on the fly
or once, and possess stable names.
Finally, as for the non-CA → CA features, Lix removed ca-derivations.
fetchClosure offers ca-derivations-like features which suffers from similar
shortcomings albeit lessened. It only follows that we should rather deprecate
and remove these capabilities.
+1
View File
@@ -200,6 +200,7 @@
- [Release Notes](release-notes/release-notes.md)
- [Upcoming release](release-notes/rl-next.md)
<!-- RELENG-AUTO-INSERTION-MARKER (see releng/release_notes.py) -->
- [Lix 2.95 (2026-03-13)](release-notes/rl-2.95.md)
- [Lix 2.94 (2025-11-17)](release-notes/rl-2.94.md)
- [Lix 2.93 (2025-05-09)](release-notes/rl-2.93.md)
- [Lix 2.92 (2025-01-18)](release-notes/rl-2.92.md)
@@ -135,7 +135,7 @@ How those are combined within the configuration file differs for the formats, an
8. `ssh-public-host-key` (**optional**)
The public host key of the remote machine.
Defaults to basic ssh behavior (checking contests of the known-hosts file)
Defaults to basic ssh behavior (checking contents of the known-hosts file)
### Using a TOML configuration
@@ -19,7 +19,7 @@ This description is not normative, but a feature removal may roughly happen like
1. Add a warning when the feature is being used.
2. Disable the feature by default, putting it behind a deprecated feature flag.
- If disabling the feature started out as an opt-in experimental feature, turn that experimental flag into a no-op or remove it entirely.
For example, `--extra-experimental-features=no-url-literals` becomes `--extra-deprecated-features=url-literals`.
For example, `--extra-experimental-features no-url-literals` becomes `--extra-deprecated-features url-literals`.
3. Decide on a time frame for how long that feature will still be supported for backwards compatibility, and clearly communicate that in the error messages.
- Sometimes, automatic migration to alternatives is possible, and such should be provided if possible
- At least one NixOS release cycle should be the minimum
+4 -1
View File
@@ -383,7 +383,10 @@ I grepped `lix/` for `get[eE]nv\("` to find the mentions in Lix code.
Overrides compile-time configuration of various locations used by Lix. See `lix/libstore/globals.cc`.
**Expected value**: a directory
- `NIX_DAEMON_SOCKET_PATH` (optional) - Overrides the daemon socket path from `$NIX_STATE_DIR/daemon-socket/socket`.
- `LIX_DAEMON_SOCKET_DIR` (optional) - Overrides the daemon socket directory from `$NIX_STATE_DIR/daemon-socket`.
**Expected value**: a directory
- `NIX_DAEMON_SOCKET_PATH` (optional) - Overrides the daemon socket path from `$NIX_STATE_DIR/daemon-socket/socket`. Ignored if `LIX_DAEMON_SOCKET_DIR` is set.
**Expected value**: path to a socket
- `NIX_LOG_FD` (output) - An FD number for logs in `internal-json` format to be sent to.
+1 -1
View File
@@ -89,7 +89,7 @@
[store path]: #gloss-store-path
- [file system object]{#gloss-store-object}
- [file system object]{#gloss-file-system-object}
The Nix data model for representing simplified file system data.
+546
View File
@@ -0,0 +1,546 @@
# Lix 2.95 "Kakigōri" (2026-03-13)
# Lix 2.95.0 (2026-03-13)
## Breaking Changes
- Deprecate shadowing internal files through the Nix search path [lix#998](https://git.lix.systems/lix-project/lix/issues/998) [cl/4632](https://gerrit.lix.systems/c/lix/+/4632)
As Lix uses the path `<nix/fetchurl.nix>` for bootstrapping purposes, the ability to shadow it by adding `nix=/some/path` (or `/other/path` that contains a `nix` directory) to the search path is not desirable.
To alleviate potential issues, Lix now emits a warning when the Nix search path contains potential shadows for internal files, which will be changed to an error in a future release.
The warning can be disabled by enabling the deprecated feature `nix-path-shadow`.
Many thanks to [Tom Hubrecht](https://git.lix.systems/tom-hubrecht) for this.
- More deprecated features [cl/2092](https://gerrit.lix.systems/c/lix/+/2092) [cl/2310](https://gerrit.lix.systems/c/lix/+/2310) [cl/2311](https://gerrit.lix.systems/c/lix/+/2311) [cl/4638](https://gerrit.lix.systems/c/lix/+/4638) [cl/4652](https://gerrit.lix.systems/c/lix/+/4652) [cl/4764](https://gerrit.lix.systems/c/lix/+/4764)
This release cycle features a new batch of deprecated (anti-)features.
You can opt in into the old behavior with `--extra-deprecated-features` or any equivalent configuration option.
- `broken-string-indentation` indented strings (those starting with `''`) might produce unintended results due to how the whitespace stripping is done. Those cases will now warn the user.
- `broken-string-escape` "escaped" characters without a properly defined escape sequence evaluate to "themselves". This is in most cases unintended behaviour, both for writing regexes, and using legacy or uncommon escape sequences like `\f`. The user will now be warned, if those are present.
- `floating-without-zero` so far, one was able to declare a float using something like `.123`. This can cause confusion about accessing attributes. Floating point numbers must now always include the leading zero, i.e. `0.123`
- `rec-set-merges` Attribute sets like `{ foo = {}; foo.bar = 42;}` implicitly merge at parse time, however if one of them is marked as recursive but not the others then the recursive attribute may get lost (order-dependent). Therefore, merging attrs with mixed-`rec` is now forbidden.
- `rec-set-dynamic-attrs` Dynamic attributes have weird semantics in the presence of recursive attrsets (they evaluate *after* the rest of the set). This is now forbidden.
- `or-as-identifier` `or` as an identifier has always been weird since the `or` (almost-)keyword has been introduced. We are deprecating the backcompat hacks from the early days of Nix in favor of making `or` a full and proper keyword.
- `tokens-no-whitespace` Function applications without space around the arguments like `0a`, `0.00.0` or `foo"1"2` are now forbidden. The same applies to list elements. The primary reason for this deprecation is to remove foot guns around surprising tokenization rules regarding number literals, but this will also free up some syntax for other purposes (e.g. `r""` strings) for reuse at some point in the future.
- `shadow-internal-symbols` has been expanded to also forbid shadowing `null`, `true` and `false`.
- `ancient-let` deprecation has been turned into a full parser error instead of a warning.
- `rec-set-overrides` deprecation has been turned into a full parser error instead of a warning.
Many thanks to [piegames](https://git.lix.systems/piegames), [rootile (Rutile)](https://git.lix.systems/rootile), and [eldritch horrors](https://git.lix.systems/pennae) for this.
- Move `/root/.cache/nix` to `/var/cache/nix` by default [lix#634](https://git.lix.systems/lix-project/lix/issues/634) [cl/4671](https://gerrit.lix.systems/c/lix/+/4671)
By default, Lix attempts to locate a cache directory for its operations (such
as the narinfo cache) by checking the value of `$XDG_CACHE_DIR`.
However, since the Nix daemon is a system service, using `$XDG_CACHE_DIR` is
not typical in this context.
To address this, systemd provides a better solution. Specifically, when
`CacheDirectory=` is set in the `[Service]` section of a systemd unit, it
automatically sets the `$CACHE_DIRECTORY` environment variable and systemd will
manage that cache directory for us.
Now, our systemd unit includes `CacheDirectory=nix`, which sets the
`$CACHE_DIRECTORY` and takes precedence over `$XDG_CACHE_DIR`.
If the daemon is run under user units, systemd will automatically set
`$XDG_CACHE_DIR`.
If neither of these variables is set, Lix falls back to its default behavior.
By default, Lix will try to find a cache directory for its various operations
(e.g. narinfo cache) by looking into `$XDG_CACHE_DIR`.
In summary, what was stored in `/root/.cache/nix` is now moved to
`/var/cache/nix/nix`.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) for this.
- Remove `fetch-closure` experimental feature [lix#1010](https://git.lix.systems/lix-project/lix/issues/1010) [cl/4595](https://gerrit.lix.systems/c/lix/+/4595)
The `fetch-closure` experimental feature has been removed.
Outside of allowing the user to import closure from binary cache,
`fetchClosure` also allowed you to do the following:
* rewrite non-CA path to CA
* reject non-CA paths at fetching time
* reject CA paths at fetching time
Some people are using those mechanism to prevent users from having to build any
package and force going via the declared cache or as a way to use ancient/old
software without paying the evaluation cost of a second nixpkgs.
Both use cases are somewhat of an antipattern in Nix semantics. If the user
cannot fetch a program directly via the substituter mechanism and fall back to
local build, this is a feature *and* a misconfiguration. If the user cannot build
certain derivations because they are too expensive, the build directives should
pass `-j0` or similar.
As for the second usecase, there's a different way to do it that also allows to
have a way to reproduce the paths that are hardcoded in that file, perform
`import (fetchurl "https://my-cache/${hashparts storepath}.drv")` rather, i.e.
an IFD to a possibly well known name. The backend can generate them on the fly
or once, and possess stable names.
Finally, as for the non-CA → CA features, Lix removed ca-derivations.
fetchClosure offers ca-derivations-like features which suffers from similar
shortcomings albeit lessened. It only follows that we should deprecate
and remove these capabilities.
Many thanks to [just1602](https://git.lix.systems/just1602) for this.
## Features
- `nix store add-path` now supports references [cl/5205](https://gerrit.lix.systems/c/lix/+/5205)
Lix supports two categories of hashes in store paths: input-addressed and output-addressed.
Currently, in Nix language, there is no way to produce output-addressed paths with references, as fixed-output derivations forbid references.
However, the Nix store actually *supports* references in output-addressed paths.
This is very useful for importing build products created outside of Lix that reference dependency store paths since such build products have no associated derivation so don't make any sense to input-address.
Previously, output-addressed paths with references could only be created by writing a custom client to the rather-baroque Nix daemon protocol; now it's available in the CLI.
Using `nix store add-path --references-list-json REFS_LIST_FILE SOME_PATH` with a JSON list of string store paths, you can now create such paths with the Lix CLI.
They may be consumed from Nix language using something like `builtins.storePath` or the following which also works in pure evaluation mode:
```nix
# Hack from https://git.lix.systems/lix-project/lix/issues/402#issuecomment-5889
path:
builtins.appendContext path {
${path} = {
path = true;
};
}
```
Many thanks to [jade](https://git.lix.systems/jade) for this.
- Add `builtins.warn` for emitting warnings from Nix code [cl/2248](https://gerrit.lix.systems/c/lix/+/2248)
Lix now has a builtin function for emitting warnings.
Like `builtins.trace`, it takes two arguments: the message to emit, and the expression to return.
_Unlike_ `builtins.trace`, `builtins.warn` requires the first argument — the message — to be a string.
In the future we may extend `builtins.warn` to accept a more structured API.
To go along with this, we also have two new config settings:
- [`debugger-on-warn`](@docroot@/command-ref/conf-file.md#conf-debugger-on-warn), which, when used with `--debugger`, makes `builtins.warn` also function like [`builtins.break`](@docroot@/language/builtins.md#builtins-break).
- [`abort-on-warn`](@docroot@/command-ref/conf-file.md#conf-abort-on-warn), which aborts evaluation entirely after the warning is emitted.
Many thanks to [Emilia Bopp](https://git.lix.systems/milibopp) and [Qyriad](https://git.lix.systems/Qyriad) for this.
- `keep-env-derivations` is now supported for nix3 CLI (`nix profile`) [lix#1095](https://git.lix.systems/lix-project/lix/issues/1095) [cl/5332](https://gerrit.lix.systems/c/lix/+/5332)
The `keep-env-derivations` feature is now available for `nix profile`. This allows users to prevent the garbage collection of derivations used to install a profile, even when `keep-derivations = false` (set to `true` by default).
Previously, `nix-env` supported this feature, but `nix profile` **never** did. This caused issues when garbage collection removed the associated `.drv` files, which are required, for example, by vulnerability management tools (e.g. [vulnix](https://github.com/nix-community/vulnix)) for proper operation.
This issue has now been resolved.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) for this.
- Make `log-format` a setting [cl/4686](https://gerrit.lix.systems/c/lix/+/4686)
The [`--log-format` CLI option](@docroot@/command-ref/opt-common.md#opt-log-format) can now be set in [`nix.conf`](@docroot@/command-ref/conf-file.md#conf-log-format)!
For example, you can now persistently enable the `multiline-with-logs` log format [added in Lix 2.91](@docroot@/release-notes/rl-2.91.md) by adding the following to your `nix.conf`:
```conf
log-format = multiline-with-logs
```
Or the equivalent in a NixOS configuration:
```nix
{
nix.settings.log-format = "multiline-with-logs";
}
```
Many thanks to [Qyriad](https://git.lix.systems/Qyriad) for this.
- Allow remote builders to be configured using TOML [cl/4533](https://gerrit.lix.systems/c/lix/+/4533)
Lix now supports configuring remote builders using a TOML file instead of the old, very cursed and incomprehensible format.
This comes with not only a human-understandable file, but also with better messages and error reports on misconfiguration.
A more detailed Documentation can be found on the [distributed-builds](@docroot@/advanced-topics/distributed-builds.md) documentation page.
Many thanks to [rootile (Rutile)](https://git.lix.systems/rootile) and [Qyriad](https://git.lix.systems/Qyriad) for this.
- Emit warnings when encountering IFD with `warn-import-from-derivation` [nix#13279](https://github.com/NixOS/nix/pull/13279) [cl/3879](https://gerrit.lix.systems/c/lix/+/3879)
Instead of only being able to toggle the use of [Import from
Derivation](https://nix.dev/manual/nix/stable/language/import-from-derivation) with
`allow-import-from-derivation`, Lix is now able to warn users whenever IFD is encountered with
`warn-import-from-derivation`.
Many thanks to [Seth Flynn](https://git.lix.systems/getchoo), [gustavderdrache](https://github.com/gustavderdrache), and [Eelco Dolstra](https://github.com/edolstra) for this.
## Improvements
- Collect Flakes untrusted settings into one prompt [lix#682](https://git.lix.systems/lix-project/lix/issues/682) [cl/2921](https://gerrit.lix.systems/c/lix/+/2921)
When working with Flakes containing untrusted settings, a prompt is shown for each setting, asking whether to vet or approve it. This looks like:
```
nix flake lock
warning: ignoring untrusted flake configuration setting 'allow-dirty', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
warning: ignoring untrusted flake configuration setting 'sandbox', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
The following settings require your decision:
- allow-dirty = false
- sandbox = false
Do you want to allow configuration settings to be applied?
This may allow the flake to gain root, see the nix.conf manual page (yes for now/Allow always/no/No to all)
```
In Flakes with a large number of settings to approve or reject, this process can become tedious as each option must be handled individually.
To address this, all untrusted settings are now consolidated into a single prompt: allowing for bulk acceptance permanently or not, rejection, or detailed review. For example:
### Scrutiny scenario
```console
nix flake lock
warning: ignoring untrusted flake configuration setting 'allow-dirty', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
warning: ignoring untrusted flake configuration setting 'sandbox', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
The following settings require your decision:
- allow-dirty = false
- sandbox = false
Do you want to allow configuration settings to be applied?
This may allow the flake to gain root, see the nix.conf manual page (yes for now/Allow always/no/No to all) n
warning: you can set 'accept-flake-config' to 'false' to automatically reject configuration options supplied by flakes
Do you want to allow setting 'allow-dirty = false'? (yes for now/Allow always/no for now) y
Do you want to allow setting 'sandbox = false'? (yes for now/Allow always/no for now) n
```
### Reject everything scenario
```console
nix flake lock
warning: ignoring untrusted flake configuration setting 'allow-dirty', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
warning: ignoring untrusted flake configuration setting 'sandbox', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
The following settings require your decision:
- allow-dirty = false
- sandbox = false
Do you want to allow configuration settings to be applied?
This may allow the flake to gain root, see the nix.conf manual page (yes for now/Allow always/no/No to all) N
Rejecting all untrusted nix.conf entries
warning: you can set 'accept-flake-config' to 'false' to automatically reject configuration options supplied by flakes
```
### Accept everything scenario
```console
nix flake lock
warning: ignoring untrusted flake configuration setting 'allow-dirty', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
warning: ignoring untrusted flake configuration setting 'sandbox', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
The following settings require your decision:
- allow-dirty = false
- sandbox = false
Do you want to allow configuration settings to be applied?
This may allow the flake to gain root, see the nix.conf manual page (yes for now/Allow always/no/No to all) y
```
### Accept everything PERMANENTLY scenario
Note that accepting everything permanently will authorize these options for any
further operations.
The file containing this trust information is usually located in
`~/.local/share/nix/trusted-settings.json` and can be edited manually to revoke
this permission until Lix provides a first-class command for this manipulation.
```console
nix flake lock
warning: ignoring untrusted flake configuration setting 'allow-dirty', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
warning: ignoring untrusted flake configuration setting 'sandbox', pass '--accept-flake-config' to trust it (may allow the flake to gain root, see the nix.conf manual page)
The following settings require your decision:
- allow-dirty = false
- sandbox = false
Do you want to allow configuration settings to be applied?
This may allow the flake to gain root, see the nix.conf manual page (yes for now/Allow always/no/No to all) A
```
Many thanks to [isabelroses](https://git.lix.systems/isabelroses), [Raito Bezarius](https://git.lix.systems/raito), and [eldritch horrors](https://git.lix.systems/pennae) for this.
- `--check` or `--rebuild` is clearer about a missing path [lix#485](https://git.lix.systems/lix-project/lix/issues/485)
Previously, when running Lix with --check or --rebuild, failures often surfaced
as an unhelpful error:
> "some outputs of '...' are not valid, so checking is not possible"
This message could mean two different things:
- The requested output paths don't exist at all, or,
- Some outputs exist but are not known to Lix
Lix cannot reliably distinguish these cases, so it treated them the same.
We've updated the error messages to clarify what Lix can determine: whether any
valid outputs (> 0) are present or whether no outputs are available.
When no valid outputs can be found, Lix will now suggest building the derivation
normally (without --check or --rebuild) before trying again.
When some valid outputs are present, Lix now reports which ones are valid,
shows the full list of known outputs, and also suggests building the derivation
normally.
In the future, Lix may automate this recovery step when it knows how to rebuild
the paths, but implementing that safely requires more extensive changes to the
codebase.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) for this.
- `nix develop` no longer ignores the env variable `SSL_CERT_FILE` [cl/5042](https://gerrit.lix.systems/c/lix/+/5042)
Running `nix develop` and `nix print-dev-env` on shells that define the environment variable `SSL_CERT_FILE` now works correctly by exporting that variable inside the built shell.
Many thanks to [Tom Hubrecht](https://git.lix.systems/tom-hubrecht) for this.
- Linux sandbox launch overhead greatly reduced [cl/5030](https://gerrit.lix.systems/c/lix/+/5030) [cl/5073](https://gerrit.lix.systems/c/lix/+/5073) [cl/5074](https://gerrit.lix.systems/c/lix/+/5074)
Sandboxed builds are now much cheaper to launch on Linux, with constant management
overhead. This will mostly be noticeable when building derivation trees containing
many small derivations like nixpkgs' `writeFile` or `runCommand` with scripts that
exit quickly. In synthetic tests we have seen build times of 3000 small runCommand
drop from 80 seconds to 14 seconds, which is the most optimistic case in practice.
Many thanks to [eldritch horrors](https://git.lix.systems/pennae) for this.
- mTLS store connections via a plugin [cl/3754](https://gerrit.lix.systems/c/lix/+/3754) [cl/3696](https://gerrit.lix.systems/c/lix/+/3696) [cl/3697](https://gerrit.lix.systems/c/lix/+/3697) [cl/3698](https://gerrit.lix.systems/c/lix/+/3698)
To support use cases requiring mutual TLS (mTLS) authentication when connecting
to remote Nix stores, e.g. private stores, we have introduced a **contributed**
mTLS plugin extending the Lix store interface.
This design follows an extensibility model which was brought up [by a proposal
of making Kerberos authentication possible in Lix
directly](https://gerrit.lix.systems/c/lix/+/3637).
This mTLS plugin serves as a concrete example of how store connection
mechanisms can be modularized through external plugins, without extending Lix
core. This idea can be generalized to integrate automatic certificate renewal
or advanced integrations with secrets engine or posture checks.
It enables custom TLS client certificates to be used for authenticating against
a remote store that enforces mTLS.
To use the plugin, configure Lix manually by setting in your `nix.conf`:
```
plugin-files = /a/path/to/libplugin_mtls_store.so
```
Currently, this must be done explicitly. In the future, Nixpkgs will provide a
mechanism to reference an up-to-date and curated set of plugins automatically.
Making plugins easily consumable outside of Nixpkgs (e.g., from external plugin
registries or binary distributions) remains an open question and will require
further design.
Contributed plugins come with significantly reduced **stability** and
**maintenance** guarantees compared to the Lix core. We encourage users who
depend on a given plugin to take on maintenance responsibilities and apply for
ownership within the Lix mono-repository. These plugins are subject to removal
at any time.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito), [eldritch horrors](https://git.lix.systems/pennae), [mic92](https://github.com/mic92), [vlaci](https://github.com/vlaci), and [nkk0](https://github.com/nkk0) for this.
- Add an indication of nix-shell nesting depth [lix#826](https://git.lix.systems/lix-project/lix/issues/826) [cl/4657](https://gerrit.lix.systems/c/lix/+/4657)
When in a nix shell (either via a `nix-shell` or a `nix develop` invocation), a variable `NIX_SHELL_LEVEL` is exported to indicate the nesting depth of nix shells.
Many thanks to [Tom Hubrecht](https://git.lix.systems/tom-hubrecht) for this.
- `nix store delete` can now unlink a GC root before deleting its closure [cl/4660](https://gerrit.lix.systems/c/lix/+/4660)
Ever build something, and then you want to delete it and whatever dependencies it downloaded?
Before you had to resolve the `result` symlink and copy it, then delete it, *then* `nix store delete --delete-closure --skip-live` on the path you copied.
Now you can just pass `--unlink` and the `result` symlink itself.
Many thanks to [Qyriad](https://git.lix.systems/Qyriad) for this.
- `nix path-info` no longer lies to the user about fetching paths [lix#323](https://git.lix.systems/lix-project/lix/issues/323) [cl/4866](https://gerrit.lix.systems/c/lix/+/4866)
When running `nix path-info` with an installable that is not present in the store, Lix no longer
tells the user which paths are missing and that they will be fetched, as the documentation clearly
states that this command does not fetch missing paths.
Many thanks to [Tom Hubrecht](https://git.lix.systems/tom-hubrecht) for this.
- Derivations can now be printed in detail in `nix repl` [cl/3842](https://gerrit.lix.systems/c/lix/+/3842)
Traditionally derivations printed in the REPL would only print a formatted object
representing the path of the derivation file it refers to. This makes inspecting
the enhanced derivation attribute sets encountered from `mkDerivation` or similar
wrappers more difficult. Even the `:p`/`:print` command would not elaborate attribute sets
tagged as a derivation.
With this change you can now use `:p`/`:print` to directly inspect a derivation
by providing one as the top-level object. Derivation attribute sets will only be
printed two levels deep and internal derivation attrsets will remain in unexpanded
path form as before. `drvAttrs` will also be elided as these attributes are already
present in the top-level attribute set of the derivation. These heuristics provide
a balance between readability and functionality. When the `:p`/`:print` is omitted,
a bare derivation is printed in the path format as before.
Many thanks to [Lunaphied](https://git.lix.systems/Lunaphied) for this.
- Reject `__json` in structured attributes derivations [lix#380](https://git.lix.systems/lix-project/lix/issues/380) [cl/5286](https://gerrit.lix.systems/c/lix/+/5286)
In structured attributes derivations, `__json` is used internally to store the
JSON representation of the `env` attribute field that users can set.
Unfortunately, a user can set `__json` *and* enable structured attributes,
resulting in a broken derivation from a semantic point of view.
As no user can benefit from setting `__json` *and* enable structured attributes,
we disallow that possibility and throw an error from now on.
This is not seen as a breaking change because there's no user code that can
benefit from this behavior, hence, it's an improvement to user experience.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) for this.
- Shells support `$NIX_LOG_FD` now [lix#336](https://git.lix.systems/lix-project/lix/issues/336) [cl/4694](https://gerrit.lix.systems/c/lix/+/4694) [cl/4695](https://gerrit.lix.systems/c/lix/+/4695)
Lix's "debugging" shells (`nix3-develop` and `nix-shell`) now set the
`$NIX_LOG_FD` environment variable.
This means that [hook logging in
stdenv](https://github.com/NixOS/nixpkgs/pull/310387) appears while debugging
derivations via `nix3-develop` or `nix-shell`.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) for this.
- Supplementary groups are now supported for daemon authentication [lix#968](https://git.lix.systems/lix-project/lix/issues/968) [cl/5021](https://gerrit.lix.systems/c/lix/+/5021)
macOS, FreeBSD and Linux now support receiving supplementary groups during UNIX domain authentication to a Lix daemon.
This change is particularly beneficial for systemd units with `DynamicUser=true` that need to connect to a Lix daemon, using a `SupplementaryGroups=` allocated by systemd in the context of the process. This is desirable if you wish to harden Lix clients.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito), [Tom Hubrecht](https://git.lix.systems/tom-hubrecht), [alois31](https://git.lix.systems/alois31), and [eldritch horrors](https://git.lix.systems/pennae) for this.
## Fixes
- Nix shells' `$NIX_BUILD_TOP` are shorter [lix#1044](https://git.lix.systems/lix-project/lix/issues/1044) [cl/4663](https://gerrit.lix.systems/c/lix/+/4663)
Following the changes in 2.94.0 to shorten build directory paths, aimed at [resolving UNIX domain socket length issues](https://gerrit.lix.systems/c/lix/+/4168/13) and [improving nix-shell](https://git.lix.systems/lix-project/lix/issues/940), we inadvertently introduced an excessively long path for the `$NIX_BUILD_TOP` environment variable used by Nix shells (their effective temporary `/build` directory).
To fix this, we replaced the `build-top-$HASH` directory name with simply `build-top`, reducing these paths by at least 30 characters.
We also added a test to ensure that Nix shells do not introduce more than 50 extra characters relative to their base directory (e.g., `/tmp` when `$TMPDIR` is not set).
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) for this.
- Fix resolving of symlinks in flake paths [lix#106](https://git.lix.systems/lix-project/lix/issues/106) [lix#12286](https://git.lix.systems/lix-project/lix/pulls/12286) [cl/4783](https://gerrit.lix.systems/c/lix/+/4783)
Flake paths are now canonicalized to resolve symlinks. This ensures that when a flake is accessed via a symlink, paths are resolved relative to the target directory, not the symlink's location.
Many thanks to [stevalkr](https://github.com/stevalkr) and [xyenon](https://git.lix.systems/xyenon) for this.
- The REPL no longer considers failed loads for `:reload` [lix#50](https://git.lix.systems/lix-project/lix/issues/50) [cl/4864](https://gerrit.lix.systems/c/lix/+/4864) [cl/4865](https://gerrit.lix.systems/c/lix/+/4865) [cl/4700](https://gerrit.lix.systems/c/lix/+/4700) [cl/4889](https://gerrit.lix.systems/c/lix/+/4889)
The [REPL](@docroot@/command-ref/new-cli/nix3-repl.md) allows "loading" files, flakes, and expressions into the environment, with the commands `:load`/`:l`, `:load-flake`/`:lf`, and `:add`/`:a` respectively.
The results of those stay in the environment as-is even if their sources change, until the `:reload` command is used.
However `:reload` would re-perform *all* instances of `:l`/`:lf`/`:a`, meaning you would get things like this:
```nix
nix-repl> :l /tmp/texting.nix
error: getting status of '/tmp/texting.nix': No such file or directory
# oops, typo.
nix-repl> :l /tmp/testing.nix
# Do some stuff…
nix-repl> :reload
error: getting status of '/tmp/texting.nix': No such file or directory
```
This is pretty silly, but also *incredibly* annoying, as it would stop there and *not* reload the correct files anymore.
This effectively meant typoing any of the load commands would make `:reload` useless for the rest of the entire `nix repl` session!
This has been fixed, so now only *successful* loads count towards `:reload`.
Many thanks to [Raito Bezarius](https://git.lix.systems/raito) and [Qyriad](https://git.lix.systems/Qyriad) for this.
- Consistently use commit hash as rev when locking git inputs [cl/4762](https://gerrit.lix.systems/c/lix/+/4762)
Lix will now use commit hashes instead of tag object hashes in the `rev` field
when fetching git inputs by tag in `flake.lock` and `builtins.fetchTree` output.
Note that this means that Lix may change some `flake.lock` files on re-locking. Old `flake.lock` files still remain valid.
Many thanks to [goldstein](https://git.lix.systems/goldstein) for this.
## Development
- Functional lang migration [lix#856](https://git.lix.systems/lix-project/lix/issues/856) [cl/3213](https://gerrit.lix.systems/c/lix/+/3213)
We have done it! The functional/lang framework has now been fully migrated to functional2/lang.
This means: no more `just clean` and `just install` mess and whatever because one removed a test.
The lang test suite is also getting a face lift, with an improved folder structure and restructuring of many tests.
Only the first CL of the chain is provided but there's way more changes associated to this project.
Many thanks to [piegames](https://git.lix.systems/piegames) and [rootile (Rutile)](https://git.lix.systems/rootile) for this.
## Miscellany
- Warn instead of erroring when the final destination of a transfer changes in-flight [lix#1004](https://git.lix.systems/lix-project/lix/issues/1004) [cl/4641](https://gerrit.lix.systems/c/lix/+/4641)
Lix will now emit a warning during downloads where the final destination changes suddently mid-transfer instead of throwing an error.
This transfer behavior has been known to happen very rarely while fetching from some CDNs.
Many thanks to [Tom Hubrecht](https://git.lix.systems/tom-hubrecht) for this.
- `impersonate-linux-26` setting removed [cl/5047](https://gerrit.lix.systems/c/lix/+/5047)
Linux 3.0 was released 15 years ago. The `impersonate-linux-26` setting was added
14 years ago with no mention of it being necessary to build anything, only saying
that it improves determinism—which isn't accurate since impersonating Linux 2.6.x
still allows the version string to change, and the final component of the version
does still change with each Linux release. Since this setting should be no longer
necessary in modern systems and workarounds for building old code exist (by using
e.g. `setarch --uname-2.6` to wrap builds) we are removing this setting from Lix.
Many thanks to [eldritch horrors](https://git.lix.systems/pennae) for this.
- Default to showing build logs in the new-style (nix3) CLI [cl/4674](https://gerrit.lix.systems/c/lix/+/4674)
Lix will now show logs by default, in addition to the progress bar, when invoked through the new-style "nix3" CLI (`nix build`, etc)
Many thanks to [K900](https://git.lix.systems/K900) for this.
- Lix daemons are now fully socket-activated on systemd setups [lix#1030](https://git.lix.systems/lix-project/lix/issues/1030)
When launched by systemd, Lix no longer uses a persistent daemon process and uses systemd socket
activation instead. This is necessary to support the `cgroups` and `auto-allocate-uids` features
and may improve observability of daemon behavior with common systemd-based monitoring solutions.
The old behavior with a single persistent daemon is still available, but disabled by default. It
is not possible to enable both a persistent daemon and socket activation, starting one stops the
other automatically. Existing installations should not require any changes when they're updated.
Many thanks to [eldritch horrors](https://git.lix.systems/pennae) for this.
- Plugin interfaces have changed (again) [lix#359](https://git.lix.systems/lix-project/lix/issues/359) [cl/4933](https://gerrit.lix.systems/c/lix/+/4933) [cl/4934](https://gerrit.lix.systems/c/lix/+/4934)
The `RegisterPrimOp` class used to register builtins has been removed. Plugins
must now call `PluginPrimOps::add` from their `nix_plugin_entry` with the same
parameters previously passed to `RegisterRrimOp` to register any new builtins.
The `GlobalConfig::Register` helper class has also been removed. Adding config
options to the system is now done with `GlobalConfig::registerGlobalConfig`; a
plugin can add config values by calling this function from `nix_plugin_entry`.
Many thanks to [eldritch horrors](https://git.lix.systems/pennae) for this.
+1 -1
View File
@@ -381,7 +381,7 @@ image
pkgs.buildPackages.runCommand "docker-image-tarball-${pkgs.nix.version}"
{
nativeBuildInputs = [ pkgs.buildPackages.bubblewrap ];
meta.description = "Docker image tarball with Lix for ${pkgs.system}";
meta.description = "Docker image tarball with Lix for ${pkgs.stdenv.hostPlatform.system}";
}
''
mkdir -p $out/nix-support
Generated
+17 -19
View File
@@ -3,17 +3,15 @@
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1696426674,
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
"type": "github"
"lastModified": 1751685974,
"narHash": "sha256-NKw96t+BgHIYzHUjkTK95FqYRVKB8DHpVhefWSz/kTw=",
"rev": "549f2762aebeff29a2e5ece7a7dc0f955281a1d1",
"type": "tarball",
"url": "https://git.lix.systems/api/v1/repos/lix-project/flake-compat/archive/549f2762aebeff29a2e5ece7a7dc0f955281a1d1.tar.gz"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
"type": "tarball",
"url": "https://git.lix.systems/lix-project/flake-compat/archive/main.tar.gz"
}
},
"lowdown-src": {
@@ -35,11 +33,11 @@
"nix2container": {
"flake": false,
"locked": {
"lastModified": 1724996935,
"narHash": "sha256-njRK9vvZ1JJsP8oV2OgkBrpJhgQezI03S7gzskCcHos=",
"lastModified": 1767195068,
"narHash": "sha256-+OMnL79ZjqM/PCz2hoQ12MnXNoSSfBGnsYBOZnA9XbI=",
"owner": "nlewo",
"repo": "nix2container",
"rev": "fa6bb0a1159f55d071ba99331355955ae30b3401",
"rev": "bb6801be998ba857a62c002cb77ece66b0a57298",
"type": "github"
},
"original": {
@@ -108,16 +106,16 @@
},
"nixpkgs_2": {
"locked": {
"lastModified": 1757198069,
"narHash": "sha256-m3VUcOD4rTs8J7S+3dOjWMrAjw6RcITC3XYQ98zhEFs=",
"lastModified": 1773082486,
"narHash": "sha256-TKUDrM0nKUo5s/b8jhjXa2prcu5KU5Cck3HBTRLDjfo=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "0747026fc57ecb9c28901c7f7a2b5dc40e8af43c",
"rev": "7f8b8875bdb38a70c7b5ceb9ba6a6a8d69859e16",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-25.05-small",
"ref": "nixos-25.11-small",
"repo": "nixpkgs",
"type": "github"
}
@@ -125,11 +123,11 @@
"pre-commit-hooks": {
"flake": false,
"locked": {
"lastModified": 1733318908,
"narHash": "sha256-SVQVsbafSM1dJ4fpgyBqLZ+Lft+jcQuMtEL3lQWx2Sk=",
"lastModified": 1769939035,
"narHash": "sha256-Fok2AmefgVA0+eprw2NDwqKkPGEI5wvR+twiZagBvrg=",
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "6f4e2a2112050951a314d2733a994fbab94864c6",
"rev": "a8ca480175326551d6c4121498316261cbb5b260",
"type": "github"
},
"original": {
+18 -66
View File
@@ -2,7 +2,7 @@
description = "Lix: A modern, delicious implementation of the Nix package manager";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05-small";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11-small";
nixpkgs-regression.url = "github:NixOS/nixpkgs/215d4d0fd80ca5163643b03a33fde804a29cc1e2";
# Required because Nix 2.18 is not in Nixpkgs ≥ 25.05 anymore.
@@ -24,7 +24,7 @@
flake = false;
};
flake-compat = {
url = "github:edolstra/flake-compat";
url = "https://git.lix.systems/lix-project/flake-compat/archive/main.tar.gz";
flake = false;
};
};
@@ -177,13 +177,12 @@
nixStable = prev.nix;
nixVersions = prev.nixVersions // {
nix_2_3 = prev.nixVersions.nix_2_3.overrideAttrs (old: {
meta = old.meta // {
knownVulnerabilities = [ ];
};
});
# Nix 2.18 has been removed from Nixpkgs ≥ 25.05, so we need to reintroduce it ourselves for our tests.
nix_2_18 = nix_2_18.outputs.packages.${currentStdenv.hostPlatform.system}.default;
nix_2_18 =
nix_2_18.outputs.packages.${currentStdenv.hostPlatform.system}.default.overrideAttrs
(_: {
pname = "nix";
});
};
# Forward from the previous stage as we dont want it to pick the lowdown override
@@ -222,10 +221,7 @@
busybox-sandbox-shell = final.busybox-sandbox-shell or final.default-busybox-sandbox-shell;
};
lix-clang-tidy = final.callPackage ./subprojects/lix-clang-tidy {
# FIXME: To be removed when switching to nixos-25.11-small
llvmPackages = final.llvmPackages_20;
};
lix-clang-tidy = final.callPackage ./subprojects/lix-clang-tidy { };
nix-eval-jobs = final.callPackage ./subprojects/nix-eval-jobs {
stdenv = currentStdenv;
@@ -249,23 +245,9 @@
# And same thing for our build-release-notes package.
build-release-notes = final.nix.passthru.build-release-notes;
lowdown_1_3 =
# If the stable channel we are using ships lowdown >= 1.4, we need
# to swap this around, take the default lowdown from the stable
# channel and add an overridden one for the legacy version.
assert lib.versionOlder prev.lowdown.version "1.4.0";
lowdown =
assert lib.versionAtLeast prev.lowdown.version "2.0.0";
prev.lowdown;
lowdown = prev.lowdown.overrideAttrs (prevAttrs: rec {
version = "2.0.2";
src = final.fetchurl {
url = "https://kristaps.bsd.lv/lowdown/snapshots/lowdown-${version}.tar.gz";
sha512 = "2a4d0rqh8gkw4ca3gkzddp0hjpmmw74cbks8k0inhh0vizmgbn188zdv6m1kgmr019b99g7insli8js3ci1ji7y4n5nk704bswf3z3i";
};
nativeBuildInputs = prevAttrs.nativeBuildInputs ++ [ final.buildPackages.bmake ];
postInstall = lib.replaceStrings [ "lowdown.so.1" ] [ "lowdown.so.2" ] (
prevAttrs.postInstall or ""
);
});
capnproto = prev.capnproto.overrideAttrs (old: {
patches =
@@ -309,14 +291,6 @@
}
);
# Ensure support for lowdown < 1.4 doesn't regress
build-lowdown_1_3 = forAllSystems (
system:
self.packages.${system}.nix.override {
lowdown = nixpkgsFor.${system}.native.lowdown_1_3;
}
);
devShell = forAllSystems (system: {
default = self.devShells.${system}.default;
clang = self.devShells.${system}.native-clangStdenvPackages;
@@ -441,8 +415,6 @@
pkgs.callPackage ./package.nix {
# Required since we don't support gcc stdenv
stdenv = pkgs.clangStdenv;
# FIXME: To be removed when switching to nixos-25.11-small
llvmPackages = pkgs.llvmPackages_20;
versionSuffix = "";
lintInsteadOfBuild = true;
}
@@ -450,35 +422,15 @@
# Make sure that nix-env still produces the exact same result
# on a particular version of Nixpkgs.
evalNixpkgs =
with nixpkgsFor.x86_64-linux.native;
runCommand "eval-nixos" { buildInputs = [ nix ]; } ''
type -p nix-env
# Note: we're filtering out nixos-install-tools because https://github.com/NixOS/nixpkgs/pull/153594#issuecomment-1020530593.
time nix-env --store dummy:// -f ${nixpkgs-regression} -qaP --drv-path | sort | grep -v nixos-install-tools > packages
[[ $(sha1sum < packages | cut -c1-40) = 402242fca90874112b34718b8199d844e8b03d12 ]]
mkdir $out
'';
evalNixpkgs = nixpkgsFor.x86_64-linux.native.callPackage ./tests/nixpkgs/eval.nix {
inherit nixpkgs-regression;
};
nixpkgsLibTests = forAllSystems (
system:
let
nixpkgsFor.${system}.native.callPackage ./tests/nixpkgs/lib.nix {
inherit nixpkgs system;
inherit (self.packages.${system}) nix;
pkgs = nixpkgsFor.${system}.native;
testWithNix = import (nixpkgs + "/lib/tests/test-with-nix.nix") { inherit pkgs lib nix; };
in
pkgs.symlinkJoin {
name = "nixpkgs-lib-tests";
paths = [
testWithNix
]
# NOTE: nixpkgs 25.05 is being ... *creative*, and requires this dance to override
# the evaluator used for the test. it will break again in the future, don't worry.
++ lib.optionals pkgs.stdenv.isLinux [
((pkgs.callPackage "${nixpkgs}/ci/eval" { inherit nix; }).attrpathsSuperset {
evalSystem = system;
})
];
}
);
};
@@ -527,7 +479,6 @@
# devShells and packages already get checked by nix flake check, so
# this is just jobs that are special
build-lowdown_1_3 = self.hydraJobs.build-lowdown_1_3.${system};
binaryTarball = self.hydraJobs.binaryTarball.${system};
perlBindings = self.hydraJobs.perlBindings.${system};
nix-eval-jobs = self.hydraJobs.nix-eval-jobs.${system};
@@ -559,7 +510,7 @@
dockerImage =
let
pkgs = nixpkgsFor.${system}.native;
nix2container' = import nix2container { inherit pkgs system; };
nix2container' = import nix2container { inherit pkgs; };
in
import ./docker.nix {
inherit pkgs;
@@ -591,10 +542,11 @@
inherit stdenv versionSuffix;
busybox-sandbox-shell = pkgs.busybox-sandbox-shell or pkgs.default-busybox-sandbox;
internalApiDocs = false;
includeSanitizerLibs = true;
# Use LLD in the dev shell by default for faster link times.
useLld = stdenv.hostPlatform.isLinux;
};
pre-commit = self.hydraJobs.pre-commit.${pkgs.system} or { };
pre-commit = self.hydraJobs.pre-commit.${pkgs.stdenv.hostPlatform.system} or { };
in
pkgs.callPackage nix.mkDevShell {
pre-commit-checks = pre-commit;
+2 -2
View File
@@ -33,7 +33,7 @@ install: (install-custom)
# Run tests (usually requires `install`) with extra options
test *OPTIONS:
meson test -C build --print-errorlogs {{ OPTIONS }}
meson test -C build --print-errorlogs --max-lines 10000 {{ OPTIONS }}
# Run unit tests only
test-unit *OPTIONS: (test "--suite" "check")
@@ -43,7 +43,7 @@ test-integration *OPTIONS: install (test "--suite" "installcheck")
# Run functional2 tests using pytest directly, allowing for additional arguments to be passed to pytest e.g. for more granular test selection
test-functional2 *OPTIONS:
cd tests && python -m pytest -v {{ OPTIONS }} functional2
cd tests/functional2 && python -m pytest -v {{ OPTIONS }}
alias clang-tidy := lint
+1
View File
@@ -0,0 +1 @@
# noqa: N999 # consistency with rest of the codebase
+104 -84
View File
@@ -1,93 +1,113 @@
from typing import List, NamedTuple
import dataclasses
from enum import Enum
from textwrap import dedent, indent
from typing import NamedTuple
from common import cxx_literal, generate_file, load_data
KNOWN_KEYS = set([
'name',
'type',
'constructorArgs',
'implementation',
'impure',
'renameInGlobalScope',
])
from common import cxx_literal, generate_file, load_data, get_argument_parser
class BuiltinConstant(NamedTuple):
name: str
type: str
implementation: str
impure: bool
rename_in_global_scope: bool
documentation: str
def parse(datum):
unknown_keys = set(datum.keys()) - KNOWN_KEYS
if unknown_keys:
raise Exception('unknown keys', unknown_keys)
return BuiltinConstant(
name = datum['name'],
type = datum['type'],
implementation = ('{' + ', '.join([f'NewValueAs::{datum["type"]}', *datum['constructorArgs']]) + '}') if 'constructorArgs' in datum else datum['implementation'],
impure = datum.get('impure', False),
rename_in_global_scope = datum.get('renameInGlobalScope', True),
documentation = datum.content,
)
VALUE_TYPES = {
'attrs': 'nAttrs',
'boolean': 'nBool',
'integer': 'nInt',
'list': 'nList',
'null': 'nNull',
'string': 'nString',
}
HUMAN_TYPES = {
'attrs': 'set',
'boolean': 'Boolean',
'integer': 'integer',
'list': 'list',
'null': 'null',
'string': 'string',
}
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('--header', help='Path of the header to generate')
ap.add_argument('--docs', help='Path of the documentation file to generate')
ap.add_argument('defs', help='Builtin definition files', nargs='+')
args = ap.parse_args()
builtin_constants = load_data(args.defs, BuiltinConstant.parse)
generate_file(args.header, builtin_constants, lambda constant:
# `builtins` is magic and must come first
'' if constant.name == 'builtins' else constant.name,
lambda constant:
f'''{'if (!evalSettings.pureEval) ' if constant.impure else ''}{{
addConstant({cxx_literal(('__' if constant.rename_in_global_scope else '') + constant.name)}, {constant.implementation}, {{
.type = {VALUE_TYPES[constant.type]},
.doc = {cxx_literal(constant.documentation)},
.impureOnly = {cxx_literal(constant.impure)},
}});
}}
''')
generate_file(args.docs, builtin_constants, lambda constant: constant.name, lambda constant:
f'''<dt id="builtins-{constant.name}">
<a href="#builtins-{constant.name}"><code>{constant.name}</code></a> ({HUMAN_TYPES[constant.type]})
</dt>
<dd>
{constant.documentation}
''' + ('''> **Note**
IMPURE_NOTE = """
> **Note**
>
> Not available in [pure evaluation mode](@docroot@/command-ref/conf-file.md#conf-pure-eval).
''' if constant.impure else '') + '''</dd>
"""
''')
if __name__ == '__main__':
class TypeName(NamedTuple):
human: str
code: str
class BuiltinType(TypeName, Enum):
attrs = TypeName("set", "nAttrs")
boolean = TypeName("boolean", "nBool")
integer = TypeName("integer", "nInt")
list = TypeName("list", "nList")
null = TypeName("null", "nNull")
string = TypeName("string", "nString")
@classmethod
def from_string(cls, t_name: str) -> "BuiltinType":
for t in cls:
if t_name == t.name:
return t
msg = f"Invalid builtin type: {t_name}"
raise ValueError(msg)
@dataclasses.dataclass
class BuiltinConstant:
name: str
documentation: str
# Fields with different name in the Post than in here
# our fields
type: BuiltinType = dataclasses.field(init=False)
# Post fields
type_str: dataclasses.InitVar[str]
constructor_args: dataclasses.InitVar[list[str] | None] = None
implementation: str = ""
impure: bool = False
rename_in_global_scope: bool = True
def __post_init__(self, type_str: str, constructor_args: list[str] | None):
self.type = BuiltinType.from_string(type_str)
if constructor_args is not None:
args = [f"NewValueAs::{type_str}"] + constructor_args
self.implementation = f"{{{','.join(args)}}}"
@property
def code(self) -> str:
cond = "if (!evalSettings.pureEval) " if self.impure else ""
return dedent(f"""
{cond} {{
addConstant(
{cxx_literal(("__" if self.rename_in_global_scope else "") + self.name)},
{self.implementation},
{{
.type = {self.type.code},
.doc = {cxx_literal(self.documentation)},
.impureOnly = {cxx_literal(self.impure)},
}}
);
}}
""")
@property
def docs(self) -> str:
indentation = " " * 3
return dedent(f"""
<dt id="builtins-{self.name}">
<a href="#builtins-{self.name}"><code>{self.name}</code></a> ({self.type.human})
</dt>
<dd>
{indent(self.documentation, indentation)}
{indent(IMPURE_NOTE, indentation) if self.impure else ""}
</dd>
""")
def main():
args = get_argument_parser().parse_args()
builtin_constants = load_data(args.defs, BuiltinConstant)
generate_file(
args.header,
builtin_constants,
lambda constant:
# `builtins` is magic and must come first
"" if constant.name == "builtins" else constant.name,
lambda b: b.code,
)
generate_file(args.docs, builtin_constants, lambda constant: constant.name, lambda b: b.docs)
if __name__ == "__main__":
main()
+74 -66
View File
@@ -1,82 +1,90 @@
from typing import List, NamedTuple, Optional
import dataclasses
from textwrap import dedent, indent
from build_experimental_features import ExperimentalFeature
from common import cxx_literal, generate_file, load_data
from common import (
cxx_literal,
generate_file,
load_data,
get_argument_parser,
get_experimental_features,
)
KNOWN_KEYS = set([
'name',
'implementation',
'renameInGlobalScope',
'args',
'experimentalFeature',
])
class Builtin(NamedTuple):
@dataclasses.dataclass
class Builtin:
name: str
implementation: str
rename_in_global_scope: bool
args: List[str]
experimental_feature: Optional[str]
documentation: str
args: list[str]
experimental_feature: str | None = None
implementation: str = ""
rename_in_global_scope: bool = True
def parse(datum):
unknown_keys = set(datum.keys()) - KNOWN_KEYS
if unknown_keys:
raise Exception('unknown keys', unknown_keys)
return Builtin(
name = datum['name'],
implementation = datum['implementation'] if 'implementation' in datum else f'prim_{datum["name"]}',
rename_in_global_scope = datum.get('renameInGlobalScope', True),
args = datum['args'],
experimental_feature = datum.get('experimentalFeature', None),
documentation = datum.content,
def __post_init__(self):
self.implementation = self.implementation or f"prim_{self.name}"
def generate_code(self, experimental_features: dict[str, str]) -> str:
xf = experimental_features[self.experimental_feature]
cond = (
f"if (experimentalFeatureSettings.isEnabled({xf})) "
if self.experimental_feature
else ""
)
return dedent(f"""
{cond}{{
addPrimOp({{
.name = {cxx_literal(("__" if self.rename_in_global_scope else "") + self.name)},
.args = {cxx_literal(self.args)},
.arity = {len(self.args)},
.doc = {cxx_literal(self.documentation)},
.fun = {self.implementation},
.experimentalFeature = {xf},
}});
}}
""")
@property
def docs(self) -> str:
return dedent(f"""
<dt id="builtins-{self.name}">
<a href="#builtins-{self.name}"><code>{self.name} {
" ".join([f"<var>{arg}</var>" for arg in self.args])
}</code></a>
</dt>
<dd>
{indent(self.documentation, " " * 3)}
{
f"This function is only available if the [{self.experimental_feature}](@docroot@/contributing/experimental-features.md#xp-feature-{self.experimental_feature}) experimental feature is enabled."
if self.experimental_feature is not None
else ""
}
</dd>
""")
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('--header', help='Path of the header to generate')
ap.add_argument('--docs', help='Path of the documentation file to generate')
ap.add_argument('--experimental-features', help='Directory containing the experimental feature definitions')
ap.add_argument('defs', help='Builtin definition files', nargs='+')
ap = get_argument_parser()
ap.add_argument(
"--experimental-features", help="Directory containing the experimental feature definitions"
)
args = ap.parse_args()
builtins = load_data(args.defs, Builtin.parse)
builtins = load_data(args.defs, Builtin)
experimental_feature_names = set([builtin.experimental_feature for (_, builtin) in builtins])
experimental_feature_names.discard(None)
experimental_feature_files = [f'{args.experimental_features}/{name}.md' for name in experimental_feature_names]
experimental_features = load_data(experimental_feature_files, ExperimentalFeature.parse)
experimental_features = dict(map(lambda path_and_feature:
(path_and_feature[1].name, f'Xp::{path_and_feature[1].internal_name}'), experimental_features))
experimental_features[None] = 'std::nullopt'
experimental_features = get_experimental_features(
args.experimental_features, [b.experimental_feature for (_, b) in builtins]
)
generate_file(args.header, builtins, lambda builtin: builtin.name, lambda builtin:
f'''{'' if builtin.experimental_feature is None else f'if (experimentalFeatureSettings.isEnabled({experimental_features[builtin.experimental_feature]})) '}{{
addPrimOp({{
.name = {cxx_literal(('__' if builtin.rename_in_global_scope else '') + builtin.name)},
.args = {cxx_literal(builtin.args)},
.arity = {len(builtin.args)},
.doc = {cxx_literal(builtin.documentation)},
.fun = {builtin.implementation},
.experimentalFeature = {experimental_features[builtin.experimental_feature]},
}});
}}
''')
generate_file(args.docs, builtins, lambda builtin: builtin.name, lambda builtin:
f'''<dt id="builtins-{builtin.name}">
<a href="#builtins-{builtin.name}"><code>{builtin.name} {' '.join([f'<var>{arg}</var>' for arg in builtin.args])}</code></a>
</dt>
<dd>
generate_file(
args.header,
builtins,
lambda builtin: builtin.name,
lambda b: b.generate_code(experimental_features),
)
generate_file(args.docs, builtins, lambda builtin: builtin.name, lambda b: b.docs)
{builtin.documentation}
''' + (f'''This function is only available if the [{builtin.experimental_feature}](@docroot@/contributing/experimental-features.md#xp-feature-{builtin.experimental_feature}) experimental feature is enabled.
''' if builtin.experimental_feature is not None else '') + '''</dd>
''')
if __name__ == '__main__':
if __name__ == "__main__":
main()
@@ -1,58 +0,0 @@
from typing import NamedTuple
from common import cxx_literal, generate_file, load_data
KNOWN_KEYS = set([
'name',
'internalName',
])
class ExperimentalFeature(NamedTuple):
name: str
internal_name: str
description: str
def parse(datum):
unknown_keys = set(datum.keys()) - KNOWN_KEYS
if unknown_keys:
raise ValueError('unknown keys', unknown_keys)
return ExperimentalFeature(
name = datum['name'],
internal_name = datum['internalName'],
description = datum.content,
)
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('--deprecated', action='store_true', help='Generate deprecated features')
ap.add_argument('--header', help='Path of the declaration header to generate')
ap.add_argument('--impl-header', help='Path of the implementation header to generate')
ap.add_argument('--descriptions', help='Path of the description file to generate')
ap.add_argument('--shortlist', help='Path of the shortlist file to generate')
ap.add_argument('defs', help='Experimental feature definition files', nargs='+')
args = ap.parse_args()
features = load_data(args.defs, ExperimentalFeature.parse)
generate_file(args.header, features, lambda feature: feature.name, lambda feature:
f' {feature.internal_name},\n')
generate_file(args.impl_header, features, lambda feature: feature.name, lambda feature:
f''' {{
.tag = {"Dep" if args.deprecated else "Xp"}::{feature.internal_name},
.name = {cxx_literal(feature.name)},
.description = {cxx_literal(feature.description)},
}},
''')
generate_file(args.descriptions, features, lambda feature: feature.name, lambda feature:
f'''## [`{feature.name}`]{{#{"dp" if args.deprecated else "xp"}-feature-{feature.name}}}
{feature.description}
''')
generate_file(args.shortlist, features, lambda feature: feature.name, lambda feature:
f' - [`{feature.name}`](@docroot@/contributing/{"deprecated" if args.deprecated else "experimental"}-features.md#{"dp" if args.deprecated else "xp"}-feature-{feature.name})\n')
if __name__ == '__main__':
main()
+105
View File
@@ -0,0 +1,105 @@
import dataclasses
from enum import Enum
from textwrap import dedent
from typing import ClassVar, NamedTuple
from common import cxx_literal, generate_file, load_data, get_argument_parser
class FeatureTypeNames(NamedTuple):
code_tag: str
doc_tag: str
class TimelineEvent(NamedTuple):
date: str
release: str
message: str
cls: list[int]
class FeatureType(FeatureTypeNames, Enum):
experimental = FeatureTypeNames("Xp", "xp")
deprecated = FeatureTypeNames("Dep", "dp")
@dataclasses.dataclass
class ExtraFeature:
name: str
internal_name: str
documentation: str
timeline: list[TimelineEvent] = dataclasses.field(default_factory=list)
type: ClassVar[FeatureType]
@property
def code(self) -> str:
return dedent(f"""
{{
.tag = {ExtraFeature.type.code_tag}::{self.internal_name},
.name = {cxx_literal(self.name)},
.description = {cxx_literal(self.documentation)},
}},
""")
@property
def docs(self) -> str:
timeline = (
f"""
### Timeline
{
"\n ".join(
[
f"- {event.date}, {event.release}: {event.message} [{", ".join([f'[CL {cl}](https://git.lix.systems/c/lix/+/{cl})' for cl in event.cls])}]"
for event in self.timeline
]
)
}
"""
if self.timeline
else ""
)
return dedent(f"""
## [`{self.name}`]{{#{ExtraFeature.type.doc_tag}-feature-{self.name}}}
{self.documentation.replace("\n", f"\n{' ' * 3}")}
{timeline}
""")
@property
def short_docs(self) -> str:
return f" - [`{self.name}`](@docroot@/contributing/{ExtraFeature.type.name}-features.md#{ExtraFeature.type.doc_tag}-feature-{self.name})\n"
def main():
ap = get_argument_parser()
ap.add_argument("--deprecated", action="store_true", help="Generate deprecated features")
ap.add_argument("--impl-header", help="Path of the implementation header to generate")
ap.add_argument("--shortlist", help="Path of the shortlist file to generate")
args = ap.parse_args()
ExtraFeature.type = FeatureType.deprecated if args.deprecated else FeatureType.experimental
def load(**kwargs) -> ExtraFeature:
kwargs["timeline"] = [TimelineEvent(**args) for args in kwargs.get("timeline", [])]
return ExtraFeature(**kwargs)
features = load_data(args.defs, load)
generate_file(
args.header,
features,
lambda feature: feature.name,
lambda feature: f" {feature.internal_name},\n",
)
generate_file(args.impl_header, features, lambda feature: feature.name, lambda f: f.code)
generate_file(args.docs, features, lambda feature: feature.name, lambda f: f.docs)
generate_file(args.shortlist, features, lambda feature: feature.name, lambda f: f.short_docs)
if __name__ == "__main__":
main()
+136 -120
View File
@@ -1,141 +1,157 @@
from typing import List, NamedTuple, Optional
import dataclasses
from textwrap import dedent
from typing import Any
from build_experimental_features import ExperimentalFeature
from common import cxx_literal, generate_file, load_data
from common import (
cxx_literal,
generate_file,
load_data,
get_experimental_features,
get_argument_parser,
)
KNOWN_KEYS = set([
'name',
'internalName',
'platforms',
'type',
'settingType',
'default',
'defaultExpr',
'defaultText',
'aliases',
'experimentalFeature',
'deprecated',
])
class Setting(NamedTuple):
name: str
internal_name: str
description: str
platforms: Optional[List[str]]
setting_type: str
default_expr: str
default_text: str
aliases: List[str]
experimental_feature: Optional[str]
deprecated: bool
PLATFORM_WARNING = """
> **Note**
> This setting is only available on {platforms} systems.
def parse(datum):
unknown_keys = set(datum.keys()) - KNOWN_KEYS
if unknown_keys:
raise ValueError('unknown keys', unknown_keys)
default_text = f'`{nix_conf_literal(datum["default"])}`' if 'default' in datum else datum['defaultText']
if default_text == '``':
default_text = '*empty*'
return Setting(
name = datum['name'],
internal_name = datum['internalName'],
description = datum.content,
platforms = datum.get('platforms', None),
setting_type = f'Setting<{datum["type"]}>' if 'type' in datum else datum['settingType'],
default_expr = cxx_literal(datum['default']) if 'default' in datum else datum['defaultExpr'],
default_text = default_text,
aliases = datum.get('aliases', []),
experimental_feature = datum.get('experimentalFeature', None),
deprecated = datum.get('deprecated', False),
)
"""
platform_names = {
'darwin': 'Darwin',
'linux': 'Linux',
}
def nix_conf_literal(v):
if v is None:
return ''
elif isinstance(v, bool) and v == False: # 0 == False
return 'false'
elif isinstance(v, bool) and v == True: # 1 == True
return 'true'
elif isinstance(v, int):
return str(v)
elif isinstance(v, str):
return v
elif isinstance(v, list):
return ' '.join([nix_conf_literal(item) for item in v])
else:
raise NotImplementedError(f'Cannot represent {repr(v)} in nix.conf')
def indent(prefix, body):
return ''.join(['\n' if line == '' else f'{prefix}{line}\n' for line in body.split('\n')])
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('--kernel', help='Name of the kernel Lix will run on')
ap.add_argument('--header', help='Path of the header to generate')
ap.add_argument('--docs', help='Path of the documentation file to generate')
ap.add_argument('--experimental-features', help='Directory containing the experimental feature definitions')
ap.add_argument('defs', help='Setting definition files', nargs='+')
args = ap.parse_args()
settings = load_data(args.defs, Setting.parse)
experimental_feature_names = set([setting.experimental_feature for (_, setting) in settings])
experimental_feature_names.discard(None)
experimental_feature_files = [f'{args.experimental_features}/{name}.md' for name in experimental_feature_names]
experimental_features = load_data(experimental_feature_files, ExperimentalFeature.parse)
experimental_features = dict(map(lambda path_and_feature:
(path_and_feature[1].name, f'Xp::{path_and_feature[1].internal_name}'), experimental_features))
experimental_features[None] = 'std::nullopt'
generate_file(args.header, settings, lambda setting: setting.name, lambda setting:
f'''{setting.setting_type} {setting.internal_name} {{
this,
{setting.default_expr},
{cxx_literal(setting.name)},
{cxx_literal(setting.description)},
{cxx_literal(setting.aliases)},
true,
{experimental_features[setting.experimental_feature]},
{cxx_literal(setting.deprecated)}
}};
''' if setting.platforms is None or args.kernel in setting.platforms else '')
generate_file(args.docs, settings, lambda setting: setting.name, lambda setting:
f'''- <span id="conf-{setting.name}">[`{setting.name}`](#conf-{setting.name})</span>
{indent(" ", setting.description)}
''' + (f''' > **Note**
> This setting is only available on {', '.join([platform_names[platform] for platform in setting.platforms])} systems.
''' if setting.platforms is not None else '') + (f''' > **Warning**
XP_WARNING = """
> **Warning**
> This setting is part of an
> [experimental feature](@docroot@/contributing/experimental-features.md).
To change this setting, you need to make sure the corresponding experimental feature,
[`{setting.experimental_feature}`](@docroot@/contributing/experimental-features.md#xp-feature-{setting.experimental_feature}),
[`{feature}`](@docroot@/contributing/experimental-features.md#xp-feature-{feature}),
is enabled.
For example, include the following in [`nix.conf`](#):
```
extra-experimental-features = {setting.experimental_feature}
{setting.name} = ...
extra-experimental-features = {feature}
{name} = ...
```
''' if setting.experimental_feature is not None else '') + (''' > **Warning**
"""
DEPR_WARNING = """
> **Warning**
> This setting is deprecated and will be removed in a future version of Lix.
''' if setting.deprecated else '') + f''' **Default:** {setting.default_text}
"""
''' + (f''' **Deprecated alias:** {', '.join([f'`{item}`' for item in setting.aliases])}
''' if setting.aliases != [] else ''))
@dataclasses.dataclass
class Setting:
name: str
internal_name: str
documentation: str
if __name__ == '__main__':
default_text: str = ""
setting_type: str = ""
default_expr: str = ""
platforms: list[str] = dataclasses.field(default_factory=list)
aliases: list[str] = dataclasses.field(default_factory=list)
experimental_feature: str | None = None
deprecated: bool = False
default: dataclasses.InitVar[str | None] = None
type_str: dataclasses.InitVar[str | None] = None
def __post_init__(self, default: Any, type_str: str | None):
if default is not None: # is not None nor an empty String
self.default_text = f"`{nix_conf_literal(default)}`"
self.default_expr = self.default_expr or cxx_literal(default)
self.default_text = self.default_text or "*empty*"
if type_str is not None:
self.setting_type = f"Setting<{type_str}>"
def generate_code(self, experimental_features: dict[str | None, str]) -> str:
indentation = " " * 4
expr = (indent(indentation, self.default_expr) + indentation) if "\n" in self.default_expr else self.default_expr
return dedent(f"""
{self.setting_type} {self.internal_name} {{
this,
{expr},
{cxx_literal(self.name)},
{cxx_literal(self.documentation)},
{cxx_literal(self.aliases)},
true,
{experimental_features[self.experimental_feature]},
{cxx_literal(self.deprecated)}
}};
""")
@property
def docs(self) -> str:
indentation = " " * 3
platforms = [p.capitalize() for p in self.platforms]
aliases = [f"`{item}`" for item in self.aliases]
description = dedent(f"""
{indent(indentation, self.documentation)}
{indent(indentation, PLATFORM_WARNING.format(platforms=str(platforms)[1:-1])) if self.platforms else ""}
{indent(indentation, XP_WARNING.format(feature=self.experimental_feature, name=self.name)) if self.experimental_feature is not None else ""}
{indent(indentation, DEPR_WARNING) if self.deprecated else ""}
**Default:** {self.default_text}
{f"**Deprecated alias:** {str(aliases)[1:-1]}\n" if self.aliases else ""}
""")
return f'- <span id="conf-{self.name}">[`{self.name}`](#conf-{self.name})</span>' + indent(
" ", # indent by two space to make it part of the list point
description,
)
platform_names = {"darwin": "Darwin", "linux": "Linux"}
def nix_conf_literal(v: Any) -> str:
if v is None:
return ""
if v is False:
return "false"
if v is True:
return "true"
if isinstance(v, int):
return str(v)
if isinstance(v, str):
return v
if isinstance(v, list):
return " ".join([nix_conf_literal(item) for item in v])
msg = f"Cannot represent {v!r} in nix.conf"
raise NotImplementedError(msg)
def indent(prefix: str, body: str) -> str:
return "".join(["\n" if not line else f"{prefix}{line}\n" for line in body.split("\n")])
def main():
ap = get_argument_parser()
ap.add_argument("--kernel", help="Name of the kernel Lix will run on")
ap.add_argument(
"--experimental-features", help="Directory containing the experimental feature definitions"
)
args = ap.parse_args()
settings = load_data(args.defs, Setting)
experimental_features = get_experimental_features(
args.experimental_features, [s.experimental_feature for (_, s) in settings]
)
generate_file(
args.header,
settings,
lambda setting: setting.name,
lambda setting: setting.generate_code(experimental_features)
if not setting.platforms or args.kernel in setting.platforms
else "",
)
generate_file(args.docs, settings, lambda setting: setting.name, lambda setting: setting.docs)
if __name__ == "__main__":
main()
+34 -30
View File
@@ -1,4 +1,5 @@
#!@python@
# ruff: noqa: SIM112 # ignore lowercase env variable names for capnpc as we have them in lower case as arguments
import argparse
import capnp
@@ -7,58 +8,61 @@ import os
import subprocess
import sys
if lang := os.environ.get('lix_capnp_lang'):
outputs = os.environ['lix_capnp_outputs'].split()
old_cwd = os.environ['lix_capnp_old_cwd']
schema = capnp.load('@capnp_include@/capnp/schema.capnp', imports=['@capnp_include@'])
if lang := os.environ.get("lix_capnp_lang"):
outputs = os.environ["lix_capnp_outputs"].split()
old_cwd = os.environ["lix_capnp_old_cwd"]
schema = capnp.load("@capnp_include@/capnp/schema.capnp", imports=["@capnp_include@"])
request = schema.CodeGeneratorRequest.read(sys.stdin)
subprocess.run([lang], input=request.as_builder().to_bytes()).check_returncode()
base_dir = os.getcwd()
base_dir = Path.cwd()
os.chdir(old_cwd)
include = [ str(Path(p).resolve()) for p in os.environ['lix_capnp_include'].split(':') ]
include = [str(Path(p).resolve()) for p in os.environ["lix_capnp_include"].split(":")]
if depfile := os.environ['lix_capnp_depfile']:
if depfile := os.environ["lix_capnp_depfile"]:
deps = ""
for input in request.requestedFiles:
deps += " ".join(f"{input.filename}.{o}" for o in outputs)
for input_file in request.requestedFiles:
deps += " ".join(f"{input_file.filename}.{o}" for o in outputs)
deps += ":"
for dep in input.imports:
for dep in input_file.imports:
if dep.name.startswith("/"):
for candidate in (Path(i + dep.name) for i in include):
if candidate.exists():
deps += " " + str(candidate)
break
else:
raise RuntimeError("not handling relative includes")
msg = "not handling relative includes"
raise RuntimeError(msg)
deps += "\n\n"
Path(depfile).write_text(deps)
else:
parser = argparse.ArgumentParser()
parser.add_argument('--language')
parser.add_argument('--outdir')
parser.add_argument('--src-prefix')
parser.add_argument('--depfile', default="")
parser.add_argument('-I', '--include', action='append', default=['@capnp_include@'])
parser.add_argument('inputs', nargs='+')
parser.add_argument("--language")
parser.add_argument("--outdir")
parser.add_argument("--src-prefix")
parser.add_argument("--depfile", default="")
parser.add_argument("-I", "--include", action="append", default=["@capnp_include@"])
parser.add_argument("inputs", nargs="+")
args = parser.parse_args()
for infile in args.inputs:
os.environ['lix_capnp_lang'] = f"capnpc-{args.language}"
os.environ['lix_capnp_include'] = ':'.join(args.include)
os.environ['lix_capnp_depfile'] = args.depfile
os.environ['lix_capnp_old_cwd'] = os.getcwd()
os.environ["lix_capnp_lang"] = f"capnpc-{args.language}"
os.environ["lix_capnp_include"] = ":".join(args.include)
os.environ["lix_capnp_depfile"] = args.depfile
os.environ["lix_capnp_old_cwd"] = str(Path.cwd())
if args.language == "c++":
os.environ['lix_capnp_outputs'] = "c++ h"
os.environ["lix_capnp_outputs"] = "c++ h"
else:
raise RuntimeError("unknown language " + args.language)
subprocess.run([
'@capnp@',
'compile',
f'-o{sys.argv[0]}:{args.outdir}',
f'--src-prefix={args.src_prefix}',
*(f"-I{i}" for i in args.include),
infile
]).check_returncode()
subprocess.run(
[
"@capnp@",
"compile",
f"-o{sys.argv[0]}:{args.outdir}",
f"--src-prefix={args.src_prefix}",
*(f"-I{i}" for i in args.include),
infile,
]
).check_returncode()
+95 -42
View File
@@ -1,60 +1,113 @@
import argparse
import re
from collections.abc import Callable
from pathlib import Path
from typing import Any
import frontmatter
import pathlib
from collections import defaultdict
def cxx_escape_character(c):
if ord(c) >= 0x20 and ord(c) < 0x7f and c != '"' and c != '?' and c != '\\':
def cxx_escape_character(c: str) -> str:
if 0x20 <= ord(c) < 0x7F and c != '"' and c != "?" and c != "\\":
return c
elif c == '\t':
return r'\t'
elif c == '\n':
return r'\n'
elif c == '\r':
return r'\r'
elif c == '"':
return r'\"'
elif c == '?':
return r'\?'
elif c == '\\':
return r'\\'
elif ord(c) <= 0xffff:
return str.format(r'\u{:04x}', ord(c))
else:
return str.format(r'\U{:08x}', ord(c))
if c == "\t":
return r"\t"
if c == "\n":
return r"\n"
if c == "\r":
return r"\r"
if c == '"':
return r"\""
if c == "?":
return r"\?"
if c == "\\":
return r"\\"
if ord(c) <= 0xFFFF:
return str.format(r"\u{:04x}", ord(c))
return str.format(r"\U{:08x}", ord(c))
def cxx_literal(v):
def cxx_literal(v: Any) -> str:
if v is None:
return 'std::nullopt'
elif isinstance(v, bool) and v == False: # 0 == False
return 'false'
elif isinstance(v, bool) and v == True: # 1 == True
return 'true'
elif isinstance(v, int):
return "std::nullopt"
if v is False:
return "false"
if v is True:
return "true"
if isinstance(v, int):
return str(v)
elif isinstance(v, str):
return ''.join(['"', *(cxx_escape_character(c) for c in v), '"'])
elif isinstance(v, list):
return f'{{{", ".join([cxx_literal(item) for item in v])}}}'
else:
raise NotImplementedError(f'cannot represent {repr(v)} in C++')
if isinstance(v, str):
return "".join(['"', *(cxx_escape_character(c) for c in v), '"'])
if isinstance(v, list):
return f"{{{', '.join([cxx_literal(item) for item in v])}}}"
msg = f"cannot represent {v!r} in C++"
raise NotImplementedError(msg)
def load_data(defs, parse_function):
def get_experimental_features(
base_path: str, human_names: list[str | None]
) -> dict[str | None, str]:
experimental_feature_files = {
f"{base_path}/{xp_name}.md" for xp_name in human_names if xp_name is not None
}
from build_extra_features import ExtraFeature # noqa: PLC0415 # Avoid cyclic import
experimental_features_data = load_data(list(experimental_feature_files), ExtraFeature)
experimental_features: dict[str | None, str] = {
xf.name: f"Xp::{xf.internal_name}" for _, xf in experimental_features_data
}
experimental_features[None] = "std::nullopt"
return experimental_features
FIELD_RENAMES = {"type": "type_str", "content": "documentation"}
def load_data[T](defs: list[str], parse_function: type[T]) -> list[tuple[str, T]]:
data = []
for path in defs:
try:
datum = frontmatter.load(path)
data.append((path, parse_function(datum)))
datum = {
# convert camelCase to snake_case
re.sub(r"(?<=.)([A-Z])", lambda m: f"_{m.group(1).lower()}", k): v
for k, v in frontmatter.load(path).to_dict().items()
}
for post_name, field_name in FIELD_RENAMES.items():
if post_name in datum:
datum[field_name] = datum.pop(post_name)
data.append((path, parse_function(**datum)))
except Exception as e:
e.add_note(f'in {path}')
e.add_note(f"in {path}")
raise
return data
def generate_file(path, data, sort_key_function, generate_function):
def generate_file[T](
path: str | None,
data: list[T],
sort_key_function: Callable[[T], str],
generate_function: Callable[[T], str],
):
if path is not None:
with open(path, 'w') as out:
for path, datum in sorted(data, key=lambda pathAndDatum: sort_key_function(pathAndDatum[1])):
with Path(path).open("w") as out:
for path, datum in sorted(
data, key=lambda path_and_datum: sort_key_function(path_and_datum[1])
):
try:
out.write(generate_function(datum))
text = generate_function(datum)
out.write(text)
except Exception as e:
e.add_note(f'in {path}')
e.add_note(f"in {path}")
raise
def get_argument_parser() -> argparse.ArgumentParser:
ap = argparse.ArgumentParser()
ap.add_argument("--header", help="Path of the header to generate")
ap.add_argument("--docs", help="Path of the documentation file to generate")
ap.add_argument("defs", help="Builtin definition files", nargs="+")
return ap
+5 -3
View File
@@ -69,7 +69,7 @@ static std::string makeLockFilename(const std::string & storeUri) {
// This avoids issues with the escaped URI being very long and causing
// path too long errors, while also avoiding any possibility of collision
// caused by simple truncation.
auto hash = hashString(HashType::SHA256, storeUri).to_string(Base::Base32, false);
auto hash = hashString(HashType::SHA256, storeUri).to_string(HashFormat::Base32, false);
return escapeUri(storeUri).substr(0, 48) + "-" + hash.substr(0, 16);
}
@@ -405,7 +405,7 @@ kj::Promise<void> Instance::init(InitContext context)
}
kj::Promise<void> Instance::buildImpl(BuildContext context)
{
try {
if (!initialized) {
throw Error("build hook not fully initialized");
}
@@ -461,6 +461,8 @@ kj::Promise<void> Instance::buildImpl(BuildContext context)
auto ac = context.getResults().initResult().initGood().initAccept();
ac.setMachine(kj::heap<AcceptedBuild>(store, drvPath, std::move(*builder)));
} catch (...) {
RPC_FILL(context.getResults(), initResult, std::current_exception());
}
kj::Promise<void> Instance::build(BuildContext context)
@@ -527,7 +529,7 @@ kj::Promise<void> AcceptedBuild::runImpl(RunContext context)
AIO().timeoutAfter(15 * kj::MINUTES, lockFileAsync(uploadLock.get(), ltWrite))
);
if (!result) {
printError("somebody is hogging the upload lock for '%s', continuing...");
printError("somebody is hogging the upload lock for '%s', continuing...", storeUri);
}
}
+103
View File
@@ -0,0 +1,103 @@
#include "lix/libcmd/legacy.hh"
#include "lix/libstore/builtins.hh"
#include "lix/libstore/builtins/buildenv.hh"
#include "lix/libutil/async.hh"
#include "lix/libutil/error.hh"
#include "lix/libutil/file-system.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/strings.hh"
#include "lix/libutil/types.hh"
#include <string_view>
using std::literals::operator""sv;
namespace nix {
static int main_builtin_builder(AsyncIoRoot & aio, std::string programName, Strings argv)
{
logger = makeJSONLogger(*logger);
std::map<std::string, std::string> env;
auto argvIt = argv.begin();
const auto argvEnd = argv.end();
// we do not use the argument parsing functions we have in libmain here, neither
// the legacy versions nor the newer ones. the legacy version could work, but we
// want to provide two sets of arguments separated by `--` and would need rather
// unpleasant state handling to use the legacy parser. the more modern parser is
// entirely incapable of doing this for us since it's all statically configured.
const auto getArg = [&](std::string_view desc) {
if (argvIt == argvEnd) {
throw Error("expected a value for %s", desc);
}
return *argvIt++;
};
if (auto val = string2Int<int>(getArg("verbosity"))) {
verbosity = verbosityFromIntClamped(*val);
} else {
throw Error("expected a verbosity argument");
}
while (argvIt != argvEnd) {
const auto arg = getArg("option");
if (arg == "--") {
break;
} else if (!arg.starts_with("--")) {
throw Error("unexpected builtin option %s", arg);
}
auto value = unescapeNul(getArg(arg));
globalConfig.set(arg.substr(2), value);
}
while (argvIt != argvEnd) {
const auto key = getArg("builder argument");
if (!key.starts_with("--")) {
throw Error("unexpected builtin builder argument %s", key);
}
env[unescapeNul(key.substr(2))] = unescapeNul(getArg(key));
}
auto getAttr = [&](const std::string & name) {
auto i = env.find(name);
if (i == env.end()) {
throw Error("attribute '%s' missing", name);
}
return i->second;
};
const auto builder = getAttr("builder");
if (builder == "builtin:fetchurl") {
const auto outputHashMode = getAttr("outputHashMode");
const auto hash = outputHashMode == "flat" ? [&] -> std::optional<Hash> {
const auto ht = parseHashTypeOpt(getAttr("outputHashAlgo"));
return newHashAllowEmpty(getAttr("outputHash"), ht);
}()
: std::nullopt;
BuiltinFetchurl{
.storePath = getAttr("out"),
.mainUrl = getAttr("url"),
.unpack = getOr(env, "unpack", "0") == "1",
.executable = getOr(env, "executable", "0") == "1",
.hash = hash,
}
.run(aio);
} else if (builder == "builtin:buildenv") {
builtinBuildenv(getAttr("out"), tokenizeString<Strings>(getAttr("derivations")), getAttr("manifest"));
} else if (builder == "builtin:unpack-channel") {
builtinUnpackChannel(getAttr("out"), getAttr("channelName"), getAttr("src"));
} else {
throw Error("unknown builtin builder %s", builder);
}
return 0;
}
void registerLegacyBuiltinBuilder()
{
LegacyCommandRegistry::add("builtin-builder", main_builtin_builder);
}
}
+6
View File
@@ -0,0 +1,6 @@
#pragma once
///@file
namespace nix {
void registerLegacyBuiltinBuilder();
}
+8 -10
View File
@@ -4,9 +4,7 @@
#include "lix/libutil/result.hh"
#include <iostream>
using std::cout;
#include <sstream>
namespace nix {
@@ -42,31 +40,31 @@ static std::string makeNode(std::string_view id, std::string_view label,
dotQuote(id), dotQuote(label), dotQuote(colour));
}
kj::Promise<Result<void>> printDotGraph(ref<Store> store, StorePathSet && roots)
kj::Promise<Result<std::string>> formatDotGraph(ref<Store> store, StorePathSet && roots)
try {
StorePathSet workList(std::move(roots));
StorePathSet doneSet;
std::stringstream result;
cout << "digraph G {\n";
result << "digraph G {\n";
while (!workList.empty()) {
auto path = std::move(workList.extract(workList.begin()).value());
if (!doneSet.insert(path).second) continue;
cout << makeNode(std::string(path.to_string()), path.name(), "#ff0000");
result << makeNode(std::string(path.to_string()), path.name(), "#ff0000");
for (auto & p : TRY_AWAIT(store->queryPathInfo(path))->references) {
if (p != path) {
workList.insert(p);
cout << makeEdge(std::string(p.to_string()), std::string(path.to_string()));
result << makeEdge(std::string(p.to_string()), std::string(path.to_string()));
}
}
}
cout << "}\n";
co_return result::success();
result << "}\n";
co_return result.str();
} catch (...) {
co_return result::current_exception();
}
+1 -2
View File
@@ -5,6 +5,5 @@
namespace nix {
kj::Promise<Result<void>> printDotGraph(ref<Store> store, StorePathSet && roots);
kj::Promise<Result<std::string>> formatDotGraph(ref<Store> store, StorePathSet && roots);
}
+16 -18
View File
@@ -5,9 +5,7 @@
#include "lix/libutil/result.hh"
#include <iostream>
using std::cout;
#include <sstream>
namespace nix {
@@ -47,21 +45,21 @@ static std::string makeNode(const ValidPathInfo & info)
(info.path.isDerivation() ? "derivation" : "output-path"));
}
kj::Promise<Result<void>> printGraphML(ref<Store> store, StorePathSet && roots)
kj::Promise<Result<std::string>> formatGraphML(ref<Store> store, StorePathSet && roots)
try {
StorePathSet workList(std::move(roots));
StorePathSet doneSet;
std::pair<StorePathSet::iterator, bool> ret;
std::stringstream result;
cout << "<?xml version='1.0' encoding='utf-8'?>\n"
<< "<graphml xmlns='http://graphml.graphdrawing.org/xmlns'\n"
<< " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n"
<< " xsi:schemaLocation='http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd'>\n"
<< "<key id='narSize' for='node' attr.name='narSize' attr.type='long'/>"
<< "<key id='name' for='node' attr.name='name' attr.type='string'/>"
<< "<key id='type' for='node' attr.name='type' attr.type='string'/>"
<< "<graph id='G' edgedefault='directed'>\n";
result << "<?xml version='1.0' encoding='utf-8'?>\n"
<< "<graphml xmlns='http://graphml.graphdrawing.org/xmlns'\n"
<< " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n"
<< " xsi:schemaLocation='http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd'>\n"
<< "<key id='narSize' for='node' attr.name='narSize' attr.type='long'/>"
<< "<key id='name' for='node' attr.name='name' attr.type='string'/>"
<< "<key id='type' for='node' attr.name='type' attr.type='string'/>"
<< "<graph id='G' edgedefault='directed'>\n";
while (!workList.empty()) {
auto path = std::move(workList.extract(workList.begin()).value());
@@ -70,20 +68,20 @@ try {
if (ret.second == false) continue;
auto info = TRY_AWAIT(store->queryPathInfo(path));
cout << makeNode(*info);
result << makeNode(*info);
for (auto & p : info->references) {
if (p != path) {
workList.insert(p);
cout << makeEdge(path.to_string(), p.to_string());
result << makeEdge(path.to_string(), p.to_string());
}
}
}
cout << "</graph>\n";
cout << "</graphml>\n";
co_return result::success();
result << "</graph>\n";
result << "</graphml>\n";
co_return result.str();
} catch (...) {
co_return result::current_exception();
}
+1 -2
View File
@@ -5,6 +5,5 @@
namespace nix {
kj::Promise<Result<void>> printGraphML(ref<Store> store, StorePathSet && roots);
kj::Promise<Result<std::string>> formatGraphML(ref<Store> store, StorePathSet && roots);
}
+2
View File
@@ -4,6 +4,7 @@ legacy_sources = files(
# `build-remote` is not really legacy (it powers all remote builds), but it's
# not a `nix3` command.
'build-remote.cc',
'builtin-builder.cc',
'dotgraph.cc',
'graphml.cc',
'nix-build.cc',
@@ -19,6 +20,7 @@ legacy_sources = files(
legacy_headers = files(
'build-remote.hh',
'builtin-builder.hh',
'nix-build.hh',
'nix-channel.hh',
'nix-collect-garbage.hh',
+18 -13
View File
@@ -192,7 +192,11 @@ static int main_nix_build(AsyncIoRoot & aio, std::string programName, Strings ar
throw UsageError("'-p' and '-E' are mutually exclusive");
AutoDelete tmpDir(createTempDir(myName));
AutoDelete buildTopTmpDir(createTempSubdir(tmpDir, "build-top"));
// NOTE: we assume there's no `build-top` directory created inside of `tmpDir` and we have
// ownership of this.
auto buildTopTmpDir = tmpDir + "/build-top";
createDirs(buildTopTmpDir);
if (outLink.empty())
outLink = (Path) tmpDir + "/result";
@@ -209,7 +213,7 @@ static int main_nix_build(AsyncIoRoot & aio, std::string programName, Strings ar
auto autoArgsWithInNixShell = autoArgs;
if (runEnv) {
auto newArgs = evaluator->buildBindings(autoArgsWithInNixShell->size() + 1);
newArgs.alloc("inNixShell").mkBool(true);
newArgs.alloc("inNixShell") = {NewValueAs::boolean, true};
for (auto & i : *autoArgs) newArgs.insert(i);
autoArgsWithInNixShell = newArgs.finish();
}
@@ -268,8 +272,7 @@ static int main_nix_build(AsyncIoRoot & aio, std::string programName, Strings ar
if (attrPaths.empty()) attrPaths = {""};
for (auto e : exprs) {
Value vRoot;
state->eval(e, vRoot);
Value vRoot = state->eval(e);
std::function<bool(const Value & v)> takesNixShellAttr;
takesNixShellAttr = [&](const Value & v) {
@@ -352,8 +355,7 @@ static int main_nix_build(AsyncIoRoot & aio, std::string programName, Strings ar
"(import <nixpkgs> {}).bashInteractive",
CanonPath::fromCwd());
Value v;
state->eval(expr, v);
Value v = state->eval(expr);
auto drv = getDerivation(*state, v, false);
if (!drv)
@@ -434,6 +436,10 @@ static int main_nix_build(AsyncIoRoot & aio, std::string programName, Strings ar
+ 1
);
// We re-export similarly to what occurs inside of a derivation goal `NIX_LOG_FD` to stderr.
// So that stdenv hooks that logs information can be observed inside this debugging tool.
env["NIX_LOG_FD"] = "2";
// Don't use defaultTempDir() here! We want to preserve the user's TMPDIR for the shell
env["NIX_BUILD_TOP"] = env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] =
getEnvNonEmpty("TMPDIR").value_or(buildTopTmpDir);
@@ -537,13 +543,12 @@ static int main_nix_build(AsyncIoRoot & aio, std::string programName, Strings ar
printMsg(lvlChatty, "running shell: %s", concatMapStringsSep(" ", args, shellEscape));
RunningProgram proc = runProgram2(
{.program = *shell,
.searchPath = true,
.args = args,
.environment = env,
.dieWithParent = true}
);
RunningProgram proc = runProgram2({
.program = *shell,
.searchPath = true,
.args = args,
.environment = env,
});
// NOTE: we wait and return the status check immediately.
// If there's interruption, we will swallow it and wait again for termination.
+257 -214
View File
@@ -151,8 +151,7 @@ static void getAllExprs(Evaluator & state,
continue;
}
/* Load the expression on demand. */
Value vArg;
vArg.mkString(path2.canonical().abs());
Value vArg = {NewValueAs::string, path2.canonical().abs()};
if (seen.size() == maxAttrs)
throw Error("too many Nix expressions in directory '%1%'", path);
attrs.alloc(attrName
@@ -165,15 +164,13 @@ static void getAllExprs(Evaluator & state,
}
}
static void loadSourceExpr(EvalState & state, const SourcePath & path_, Value & v)
static Value loadSourceExpr(EvalState & state, const SourcePath & path_)
{
auto path = state.ctx.paths.checkSourcePath(path_);
auto st = path.stat();
if (isNixExpr(state.ctx.paths, path, st))
state.evalFile(path, v);
return state.evalFile(path);
/* The path is a directory. Put the Nix expressions in the
directory in a set, with the file name of each expression as
@@ -186,7 +183,7 @@ static void loadSourceExpr(EvalState & state, const SourcePath & path_, Value &
attrs.alloc("_combineChannels") = Value::EMPTY_LIST;
StringSet seen;
getAllExprs(state.ctx, path, seen, attrs);
v.mkAttrs(attrs);
return {NewValueAs::attrs, attrs};
}
else throw Error("path '%s' is not a directory or a Nix expression", path);
@@ -197,8 +194,7 @@ static void loadDerivations(EvalState & state, const SourcePath & nixExprPath,
std::string systemFilter, Bindings & autoArgs,
const std::string & pathPrefix, DrvInfos & elems)
{
Value vRoot;
loadSourceExpr(state, nixExprPath, vRoot);
Value vRoot = loadSourceExpr(state, nixExprPath);
Value v(findAlongAttrPath(state, pathPrefix, autoArgs, vRoot).first);
@@ -420,14 +416,12 @@ static void queryInstSources(EvalState & state,
(import ./foo.nix)' = `(import ./foo.nix).bar'. */
case srcNixExprs: {
Value vArg;
loadSourceExpr(state, *instSource.nixExprPath, vArg);
Value vArg = loadSourceExpr(state, *instSource.nixExprPath);
for (auto & i : args) {
Expr & eFun = state.ctx.parseExprFromString(i, CanonPath::fromCwd());
Value vFun, vTmp;
state.eval(eFun, vFun);
vTmp = {NewValueAs::app, state.ctx.mem, vFun, vArg};
Value vFun = state.eval(eFun);
Value vTmp = {NewValueAs::app, state.ctx.mem, vFun, vArg};
getDerivations(state, vTmp, "", *instSource.autoArgs, elems, true);
}
@@ -479,8 +473,7 @@ static void queryInstSources(EvalState & state,
}
case srcAttrPath: {
Value vRoot;
loadSourceExpr(state, *instSource.nixExprPath, vRoot);
Value vRoot = loadSourceExpr(state, *instSource.nixExprPath);
for (auto & i : args) {
Value v(findAlongAttrPath(state, i, *instSource.autoArgs, vRoot).first);
getDerivations(state, v, "", *instSource.autoArgs, elems, true);
@@ -517,8 +510,7 @@ static bool keep(EvalState & state, DrvInfo & drv)
static void setMetaFlag(EvalState & state, DrvInfo & drv,
const std::string & name, const std::string & value)
{
Value v;
v.mkString(value);
Value v = {NewValueAs::string, value};
drv.setMeta(state, name, v);
}
@@ -892,8 +884,7 @@ static bool cmpElemByName(EvalState & state, DrvInfo & a, DrvInfo & b)
typedef std::list<Strings> Table;
void printTable(Table & table)
std::string formatTable(Table & table)
{
auto nrColumns = table.size() > 0 ? table.front().size() : 0;
@@ -908,18 +899,22 @@ void printTable(Table & table)
if (j->size() > widths[column]) widths[column] = j->size();
}
std::stringstream result;
for (auto & i : table) {
Strings::iterator j;
size_t column;
for (j = i.begin(), column = 0; j != i.end(); ++j, ++column) {
std::string s = *j;
replace(s.begin(), s.end(), '\n', ' ');
cout << s;
result << s;
if (column < nrColumns - 1)
cout << std::string(widths[column] - s.size() + 2, ' ');
result << std::string(widths[column] - s.size() + 2, ' ');
}
cout << std::endl;
result << std::endl;
}
return result.str();
}
@@ -1130,209 +1125,250 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
return;
}
RunPager pager;
withPager([&](Pager & pager) {
Table table;
std::ostringstream xmlStream;
XMLWriter xml(true, xmlStream);
xml.openElement("items");
Table table;
std::ostringstream dummy;
XMLWriter xml(true, *(xmlOutput ? &cout : &dummy));
XMLOpenElement xmlRoot(xml, "items");
for (auto & i : elems) {
try {
if (i.hasFailed()) continue;
//Activity act(*logger, lvlDebug, "outputting query result '%1%'", i.attrPath);
if (globals.prebuiltOnly &&
!validPaths.count(i.queryOutPath(*state)) &&
!substitutablePaths.count(i.queryOutPath(*state)))
continue;
/* For table output. */
Strings columns;
/* For XML output. */
XMLAttrs attrs;
if (printStatus) {
auto outPath = i.queryOutPath(*state);
bool hasSubs = substitutablePaths.count(outPath);
bool isInstalled = installed.count(outPath);
bool isValid = validPaths.count(outPath);
if (xmlOutput) {
attrs["installed"] = isInstalled ? "1" : "0";
attrs["valid"] = isValid ? "1" : "0";
attrs["substitutable"] = hasSubs ? "1" : "0";
} else
columns.push_back(
(std::string) (isInstalled ? "I" : "-")
+ (isValid ? "P" : "-")
+ (hasSubs ? "S" : "-"));
}
if (xmlOutput)
attrs["attrPath"] = i.attrPath;
else if (printAttrPath)
columns.push_back(i.attrPath);
if (xmlOutput) {
auto drvName = DrvName(i.queryName(*state));
attrs["name"] = drvName.fullName;
attrs["pname"] = drvName.name;
attrs["version"] = drvName.version;
} else if (printName) {
columns.push_back(i.queryName(*state));
}
if (compareVersions) {
/* Compare this element against the versions of the
same named packages in either the set of available
elements, or the set of installed elements. !!!
This is O(N * M), should be O(N * lg M). */
std::string version;
VersionDiff diff = compareVersionAgainstSet(*state, i, otherElems, version);
char ch;
switch (diff) {
case cvLess: ch = '>'; break;
case cvEqual: ch = '='; break;
case cvGreater: ch = '<'; break;
case cvUnavail: ch = '-'; break;
default: abort();
for (auto & i : elems) {
try {
if (i.hasFailed()) {
continue;
}
if (xmlOutput) {
if (diff != cvUnavail) {
attrs["versionDiff"] = ch;
attrs["maxComparedVersion"] = version;
// Activity act(*logger, lvlDebug, "outputting query result '%1%'", i.attrPath);
if (globals.prebuiltOnly && !validPaths.count(i.queryOutPath(*state))
&& !substitutablePaths.count(i.queryOutPath(*state)))
{
continue;
}
/* For table output. */
Strings columns;
/* For XML output. */
XMLAttrs attrs;
if (printStatus) {
auto outPath = i.queryOutPath(*state);
bool hasSubs = substitutablePaths.count(outPath);
bool isInstalled = installed.count(outPath);
bool isValid = validPaths.count(outPath);
if (xmlOutput) {
attrs["installed"] = isInstalled ? "1" : "0";
attrs["valid"] = isValid ? "1" : "0";
attrs["substitutable"] = hasSubs ? "1" : "0";
} else {
columns.push_back(
(std::string) (isInstalled ? "I" : "-") + (isValid ? "P" : "-")
+ (hasSubs ? "S" : "-")
);
}
} else {
auto column = (std::string) "" + ch + " " + version;
if (diff == cvGreater && shouldANSI(StandardOutputStream::Stdout))
column = ANSI_RED + column + ANSI_NORMAL;
columns.push_back(column);
}
}
if (xmlOutput) {
if (i.querySystem(*state) != "") attrs["system"] = i.querySystem(*state);
}
else if (printSystem)
columns.push_back(i.querySystem(*state));
if (printDrvPath) {
auto drvPath = i.queryDrvPath(*state);
if (xmlOutput) {
if (drvPath) attrs["drvPath"] = store.printStorePath(*drvPath);
} else
columns.push_back(drvPath ? store.printStorePath(*drvPath) : "-");
}
if (xmlOutput)
attrs["outputName"] = i.queryOutputName(*state);
if (printOutPath && !xmlOutput) {
DrvInfo::Outputs outputs = i.queryOutputs(*state);
std::string s;
for (auto & j : outputs) {
if (!s.empty()) s += ';';
if (j.first != "out") { s += j.first; s += "="; }
s += store.printStorePath(*j.second);
attrs["attrPath"] = i.attrPath;
} else if (printAttrPath) {
columns.push_back(i.attrPath);
}
columns.push_back(s);
}
if (printDescription) {
auto descr = i.queryMetaString(*state, "description");
if (xmlOutput) {
if (descr != "") attrs["description"] = descr;
} else
columns.push_back(descr);
}
if (xmlOutput) {
XMLOpenElement item(xml, "item", attrs);
DrvInfo::Outputs outputs = i.queryOutputs(*state, printOutPath);
for (auto & j : outputs) {
XMLAttrs attrs2;
attrs2["name"] = j.first;
if (j.second)
attrs2["path"] = store.printStorePath(*j.second);
xml.writeEmptyElement("output", attrs2);
auto drvName = DrvName(i.queryName(*state));
attrs["name"] = drvName.fullName;
attrs["pname"] = drvName.name;
attrs["version"] = drvName.version;
} else if (printName) {
columns.push_back(i.queryName(*state));
}
if (printMeta) {
StringSet metaNames = i.queryMetaNames(*state);
for (auto & j : metaNames) {
if (compareVersions) {
/* Compare this element against the versions of the
same named packages in either the set of available
elements, or the set of installed elements. !!!
This is O(N * M), should be O(N * lg M). */
std::string version;
VersionDiff diff = compareVersionAgainstSet(*state, i, otherElems, version);
char ch;
switch (diff) {
case cvLess:
ch = '>';
break;
case cvEqual:
ch = '=';
break;
case cvGreater:
ch = '<';
break;
case cvUnavail:
ch = '-';
break;
default:
abort();
}
if (xmlOutput) {
if (diff != cvUnavail) {
attrs["versionDiff"] = ch;
attrs["maxComparedVersion"] = version;
}
} else {
auto column = (std::string) "" + ch + " " + version;
if (diff == cvGreater && shouldANSI(StandardOutputStream::Stdout)) {
column = ANSI_RED + column + ANSI_NORMAL;
}
columns.push_back(column);
}
}
if (xmlOutput) {
if (i.querySystem(*state) != "") {
attrs["system"] = i.querySystem(*state);
}
} else if (printSystem) {
columns.push_back(i.querySystem(*state));
}
if (printDrvPath) {
auto drvPath = i.queryDrvPath(*state);
if (xmlOutput) {
if (drvPath) {
attrs["drvPath"] = store.printStorePath(*drvPath);
}
} else {
columns.push_back(drvPath ? store.printStorePath(*drvPath) : "-");
}
}
if (xmlOutput) {
attrs["outputName"] = i.queryOutputName(*state);
}
if (printOutPath && !xmlOutput) {
DrvInfo::Outputs outputs = i.queryOutputs(*state);
std::string s;
for (auto & j : outputs) {
if (!s.empty()) {
s += ';';
}
if (j.first != "out") {
s += j.first;
s += "=";
}
s += store.printStorePath(*j.second);
}
columns.push_back(s);
}
if (printDescription) {
auto descr = i.queryMetaString(*state, "description");
if (xmlOutput) {
if (descr != "") {
attrs["description"] = descr;
}
} else {
columns.push_back(descr);
}
}
if (xmlOutput) {
XMLOpenElement item(xml, "item", attrs);
DrvInfo::Outputs outputs = i.queryOutputs(*state, printOutPath);
for (auto & j : outputs) {
XMLAttrs attrs2;
attrs2["name"] = j;
Value * v = i.queryMeta(*state, j);
if (!v)
printError(
"derivation '%s' has invalid meta attribute '%s'",
i.queryName(*state), j);
else {
if (v->type() == nString) {
attrs2["type"] = "string";
attrs2["value"] = v->str();
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nInt) {
attrs2["type"] = "int";
attrs2["value"] = fmt("%1%", v->integer());
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nFloat) {
attrs2["type"] = "float";
attrs2["value"] = fmt("%1%", v->fpoint());
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nBool) {
attrs2["type"] = "bool";
attrs2["value"] = v->boolean() ? "true" : "false";
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nList) {
attrs2["type"] = "strings";
XMLOpenElement m(xml, "meta", attrs2);
for (auto & elem : v->listItems()) {
if (elem.type() != nString) {
continue;
attrs2["name"] = j.first;
if (j.second) {
attrs2["path"] = store.printStorePath(*j.second);
}
xml.writeEmptyElement("output", attrs2);
}
if (printMeta) {
StringSet metaNames = i.queryMetaNames(*state);
for (auto & j : metaNames) {
XMLAttrs attrs2;
attrs2["name"] = j;
Value * v = i.queryMeta(*state, j);
if (!v) {
printError(
"derivation '%s' has invalid meta attribute '%s'", i.queryName(*state), j
);
} else {
if (v->type() == nString) {
attrs2["type"] = "string";
attrs2["value"] = v->str();
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nInt) {
attrs2["type"] = "int";
attrs2["value"] = fmt("%1%", v->integer());
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nFloat) {
attrs2["type"] = "float";
attrs2["value"] = fmt("%1%", v->fpoint());
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nBool) {
attrs2["type"] = "bool";
attrs2["value"] = v->boolean() ? "true" : "false";
xml.writeEmptyElement("meta", attrs2);
} else if (v->type() == nList) {
attrs2["type"] = "strings";
XMLOpenElement m(xml, "meta", attrs2);
for (auto & elem : v->listItems()) {
if (elem.type() != nString) {
continue;
}
XMLAttrs attrs3;
attrs3["value"] = elem.str();
xml.writeEmptyElement("string", attrs3);
}
} else if (v->type() == nAttrs) {
attrs2["type"] = "strings";
XMLOpenElement m(xml, "meta", attrs2);
Bindings & attrs = *v->attrs();
for (auto & i : attrs) {
const Attr & a(*attrs.get(i.name));
if (a.value.type() != nString) {
continue;
}
XMLAttrs attrs3;
attrs3["type"] = globals.state->symbols[i.name];
attrs3["value"] = a.value.str();
xml.writeEmptyElement("string", attrs3);
}
XMLAttrs attrs3;
attrs3["value"] = elem.str();
xml.writeEmptyElement("string", attrs3);
}
} else if (v->type() == nAttrs) {
attrs2["type"] = "strings";
XMLOpenElement m(xml, "meta", attrs2);
Bindings & attrs = *v->attrs();
for (auto &i : attrs) {
const Attr & a(*attrs.get(i.name));
if (a.value.type() != nString) {
continue;
}
XMLAttrs attrs3;
attrs3["type"] = globals.state->symbols[i.name];
attrs3["value"] = a.value.str();
xml.writeEmptyElement("string", attrs3);
}
}
}
}
} else {
table.push_back(columns);
}
} else
table.push_back(columns);
cout.flush();
cout.flush();
} catch (AssertionError & e) {
printMsg(lvlTalkative, "skipping derivation named '%1%' which gives an assertion failure", i.queryName(*state));
} catch (Error & e) {
e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName(*state));
throw;
} catch (AssertionError & e) {
printMsg(
lvlTalkative,
"skipping derivation named '%1%' which gives an assertion failure",
i.queryName(*state)
);
} catch (Error & e) {
e.addTrace(nullptr, "while querying the derivation named '%1%'", i.queryName(*state));
throw;
}
}
}
if (!xmlOutput) printTable(table);
// </items>
xml.closeElement();
if (!xmlOutput) {
pager << formatTable(table);
} else {
pager << xmlStream.str();
}
});
}
static void opSwitchProfile(Globals & globals, Strings opFlags, Strings opArgs)
{
if (opFlags.size() > 0)
@@ -1383,20 +1419,27 @@ static void opListGenerations(Globals & globals, Strings opFlags, Strings opArgs
auto [gens, curGen] = findGenerations(globals.profile);
RunPager pager;
for (auto & i : gens) {
tm t;
if (!localtime_r(&i.creationTime, &t)) throw Error("cannot convert time");
logger->cout("%|4| %|4|-%|02|-%|02| %|02|:%|02|:%|02| %||",
i.number,
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec,
i.number == curGen ? "(current)" : "");
}
withPager([&](Pager & pager) {
for (auto & i : gens) {
tm t;
if (!localtime_r(&i.creationTime, &t)) {
throw Error("cannot convert time");
}
pager << fmt(
"%|4| %|4|-%|02|-%|02| %|02|:%|02|:%|02| %||\n",
i.number,
t.tm_year + 1900,
t.tm_mon + 1,
t.tm_mday,
t.tm_hour,
t.tm_min,
t.tm_sec,
i.number == curGen ? "(current)" : ""
);
}
});
}
static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opArgs)
{
if (opFlags.size() > 0)
+2 -3
View File
@@ -34,8 +34,7 @@ void processExpr(EvalState & state, const Strings & attrPaths,
return;
}
Value vRoot;
state.eval(e, vRoot);
Value vRoot = state.eval(e);
for (auto & i : attrPaths) {
Value v(findAlongAttrPath(state, i, autoArgs, vRoot).first);
@@ -47,7 +46,7 @@ void processExpr(EvalState & state, const Strings & attrPaths,
if (autoArgs.empty())
vRes = v;
else
state.autoCallFunction(autoArgs, v, vRes, noPos);
vRes = state.autoCallFunction(autoArgs, v, noPos);
if (output == okRaw)
std::cout << *state.coerceToString(noPos, vRes, context, "while generating the nix-instantiate output", StringCoercionMode::Strict);
// We intentionally don't output a newline here. The default PS1 for Bash in NixOS starts with a newline
+100 -77
View File
@@ -25,7 +25,9 @@
#include <iostream>
#include <algorithm>
#include <ostream>
#include <ranges>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
@@ -288,6 +290,7 @@ try {
graph. Topological sorting is used to keep the tree relatively
flat. */
static void printTree(
std::ostream & ostream,
std::shared_ptr<Store> store,
AsyncIoRoot & aio,
const StorePath & path,
@@ -297,11 +300,11 @@ static void printTree(
)
{
if (!done.insert(path).second) {
cout << fmt("%s%s [...]\n", firstPad, store->printStorePath(path));
ostream << fmt("%s%s [...]\n", firstPad, store->printStorePath(path));
return;
}
cout << fmt("%s%s\n", firstPad, store->printStorePath(path));
ostream << fmt("%s%s\n", firstPad, store->printStorePath(path));
auto info = aio.blockOn(store->queryPathInfo(path));
@@ -315,6 +318,7 @@ static void printTree(
for (const auto &[n, i] : enumerate(sorted)) {
bool last = n + 1 == sorted.size();
printTree(
ostream,
store,
aio,
i,
@@ -373,17 +377,15 @@ opQuery(std::shared_ptr<Store> store, AsyncIoRoot & aio, Strings opFlags, String
if (!query) query = qOutputs;
RunPager pager;
switch (*query) {
withPager([&](Pager & pager) {
switch (*query) {
case qOutputs: {
for (auto & i : opArgs) {
auto outputs = aio.blockOn(
maybeUseOutputs(store, store->followLinksToStorePath(i), true, forceRealise)
);
for (auto & outputPath : outputs)
cout << fmt("%1%\n", store->printStorePath(outputPath));
auto outputs =
aio.blockOn(maybeUseOutputs(store, store->followLinksToStorePath(i), true, forceRealise));
for (auto & outputPath : outputs) {
pager << fmt("%1%\n", store->printStorePath(outputPath));
}
}
break;
}
@@ -394,54 +396,55 @@ opQuery(std::shared_ptr<Store> store, AsyncIoRoot & aio, Strings opFlags, String
case qReferrersClosure: {
StorePathSet paths;
for (auto & i : opArgs) {
auto ps = aio.blockOn(maybeUseOutputs(
store, store->followLinksToStorePath(i), useOutput, forceRealise
));
auto ps = aio.blockOn(
maybeUseOutputs(store, store->followLinksToStorePath(i), useOutput, forceRealise)
);
for (auto & j : ps) {
if (query == qRequisites) {
aio.blockOn(store->computeFSClosure(j, paths, false, includeOutputs));
}
else if (query == qReferences) {
for (auto & p : aio.blockOn(store->queryPathInfo(j))->references)
} else if (query == qReferences) {
for (auto & p : aio.blockOn(store->queryPathInfo(j))->references) {
paths.insert(p);
}
else if (query == qReferrers) {
}
} else if (query == qReferrers) {
StorePathSet tmp;
aio.blockOn(store->queryReferrers(j, tmp));
for (auto & i : tmp)
for (auto & i : tmp) {
paths.insert(i);
}
else if (query == qReferrersClosure)
}
} else if (query == qReferrersClosure) {
aio.blockOn(store->computeFSClosure(j, paths, true));
}
}
}
auto sorted = aio.blockOn(store->topoSortPaths(paths));
for (StorePaths::reverse_iterator i = sorted.rbegin();
i != sorted.rend(); ++i)
cout << fmt("%s\n", store->printStorePath(*i));
for (StorePaths::reverse_iterator i = sorted.rbegin(); i != sorted.rend(); ++i) {
pager << fmt("%s\n", store->printStorePath(*i));
}
break;
}
case qDeriver:
for (auto & i : opArgs) {
auto info = aio.blockOn(store->queryPathInfo(store->followLinksToStorePath(i)));
cout << fmt("%s\n", info->deriver ? store->printStorePath(*info->deriver) : "unknown-deriver");
pager << fmt(
"%s\n", info->deriver ? store->printStorePath(*info->deriver) : "unknown-deriver"
);
}
break;
case qValidDerivers: {
StorePathSet result;
for (auto & i : opArgs) {
auto derivers =
aio.blockOn(store->queryValidDerivers(store->followLinksToStorePath(i)));
auto derivers = aio.blockOn(store->queryValidDerivers(store->followLinksToStorePath(i)));
for (const auto & i : derivers) {
result.insert(i);
}
}
auto sorted = aio.blockOn(store->topoSortPaths(result));
for (StorePaths::reverse_iterator i = sorted.rbegin();
i != sorted.rend(); ++i)
cout << fmt("%s\n", store->printStorePath(*i));
for (StorePaths::reverse_iterator i = sorted.rbegin(); i != sorted.rend(); ++i) {
pager << fmt("%s\n", store->printStorePath(*i));
}
break;
}
@@ -450,95 +453,112 @@ opQuery(std::shared_ptr<Store> store, AsyncIoRoot & aio, Strings opFlags, String
auto path = aio.blockOn(useDeriver(store, store->followLinksToStorePath(i)));
Derivation drv = aio.blockOn(store->derivationFromPath(path));
StringPairs::iterator j = drv.env.find(bindingName);
if (j == drv.env.end())
throw Error("derivation '%s' has no environment binding named '%s'",
store->printStorePath(path), bindingName);
cout << fmt("%s\n", j->second);
if (j == drv.env.end()) {
throw Error(
"derivation '%s' has no environment binding named '%s'",
store->printStorePath(path),
bindingName
);
}
pager << fmt("%s\n", j->second);
}
break;
case qHash:
case qSize:
for (auto & i : opArgs) {
for (auto & j : aio.blockOn(maybeUseOutputs(
store, store->followLinksToStorePath(i), useOutput, forceRealise
)))
for (auto & j : aio.blockOn(
maybeUseOutputs(store, store->followLinksToStorePath(i), useOutput, forceRealise)
))
{
auto info = aio.blockOn(store->queryPathInfo(j));
if (query == qHash) {
assert(info->narHash.type == HashType::SHA256);
cout << fmt("%s\n", info->narHash.to_string(Base::Base32, true));
} else if (query == qSize)
cout << fmt("%d\n", info->narSize);
pager << fmt("%s\n", info->narHash.to_string(HashFormat::Base32));
} else if (query == qSize) {
pager << fmt("%d\n", info->narSize);
}
}
}
break;
case qTree: {
StorePathSet done;
for (auto & i : opArgs)
printTree(store, aio, store->followLinksToStorePath(i), "", "", done);
for (auto & i : opArgs) {
std::stringstream tmp;
printTree(tmp, store, aio, store->followLinksToStorePath(i), "", "", done);
pager << tmp.str();
}
break;
}
case qGraph: {
StorePathSet roots;
for (auto & i : opArgs)
for (auto & j : aio.blockOn(maybeUseOutputs(
store, store->followLinksToStorePath(i), useOutput, forceRealise
)))
for (auto & i : opArgs) {
for (auto & j : aio.blockOn(
maybeUseOutputs(store, store->followLinksToStorePath(i), useOutput, forceRealise)
))
{
roots.insert(j);
}
aio.blockOn(printDotGraph(ref<Store>::unsafeFromPtr(store), std::move(roots)));
}
pager << aio.blockOn(formatDotGraph(ref<Store>::unsafeFromPtr(store), std::move(roots)));
break;
}
case qGraphML: {
StorePathSet roots;
for (auto & i : opArgs)
for (auto & j : aio.blockOn(maybeUseOutputs(
store, store->followLinksToStorePath(i), useOutput, forceRealise
)))
for (auto & i : opArgs) {
for (auto & j : aio.blockOn(
maybeUseOutputs(store, store->followLinksToStorePath(i), useOutput, forceRealise)
))
{
roots.insert(j);
}
aio.blockOn(printGraphML(ref<Store>::unsafeFromPtr(store), std::move(roots)));
}
pager << aio.blockOn(formatGraphML(ref<Store>::unsafeFromPtr(store), std::move(roots)));
break;
}
case qResolve: {
for (auto & i : opArgs)
cout << fmt("%s\n", store->printStorePath(store->followLinksToStorePath(i)));
for (auto & i : opArgs) {
pager << fmt("%s\n", store->printStorePath(store->followLinksToStorePath(i)));
}
break;
}
case qRoots: {
StorePathSet args;
for (auto & i : opArgs)
for (auto & p : aio.blockOn(maybeUseOutputs(
store, store->followLinksToStorePath(i), useOutput, forceRealise
)))
for (auto & i : opArgs) {
for (auto & p : aio.blockOn(
maybeUseOutputs(store, store->followLinksToStorePath(i), useOutput, forceRealise)
))
{
args.insert(p);
}
}
StorePathSet referrers;
aio.blockOn(store->computeFSClosure(
args, referrers, true, settings.gcKeepOutputs, settings.gcKeepDerivations));
args, referrers, true, settings.gcKeepOutputs, settings.gcKeepDerivations
));
auto & gcStore = require<GcStore>(*store);
Roots roots = aio.blockOn(gcStore.findRoots(false));
for (auto & [target, links] : roots)
if (referrers.find(target) != referrers.end())
for (auto & link : links)
cout << fmt("%1% -> %2%\n", link, gcStore.printStorePath(target));
for (auto & [target, links] : roots) {
if (referrers.find(target) != referrers.end()) {
for (auto & link : links) {
pager << fmt("%1% -> %2%\n", link, gcStore.printStorePath(target));
}
}
}
break;
}
default:
abort();
}
}
});
}
static void
@@ -574,15 +594,16 @@ opReadLog(std::shared_ptr<Store> store, AsyncIoRoot & aio, Strings opFlags, Stri
auto & logStore = require<LogStore>(*store);
RunPager pager;
for (auto & i : opArgs) {
auto path = logStore.followLinksToStorePath(i);
auto log = aio.blockOn(logStore.getBuildLog(path));
if (!log)
throw Error("build log of derivation '%s' is not available", logStore.printStorePath(path));
std::cout << *log;
}
withPager([&](Pager & pager) {
for (auto & i : opArgs) {
auto path = logStore.followLinksToStorePath(i);
auto log = aio.blockOn(logStore.getBuildLog(path));
if (!log) {
throw Error("build log of derivation '%s' is not available", logStore.printStorePath(path));
}
pager << *log;
}
});
}
static void
@@ -856,10 +877,12 @@ opVerifyPath(std::shared_ptr<Store> store, AsyncIoRoot & aio, Strings opFlags, S
aio.blockOn(aio.blockOn(store->narFromPath(path))->drainInto(sink));
auto current = sink.finish();
if (current.first != info->narHash) {
printError("path '%s' was modified! expected hash '%s', got '%s'",
printError(
"path '%s' was modified! expected hash '%s', got '%s'",
store->printStorePath(path),
info->narHash.to_string(Base::SRI, true),
current.first.to_string(Base::SRI, true));
info->narHash.to_string(),
current.first.to_string()
);
status = 1;
}
}
+24 -19
View File
@@ -46,24 +46,30 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
auto attrs = state.ctx.buildBindings(7 + outputs.size());
attrs.alloc(state.ctx.s.type).mkString("derivation");
attrs.alloc(state.ctx.s.name).mkString(i.queryName(state));
attrs.alloc(state.ctx.symbols.sym_type) = {NewValueAs::string, "derivation"};
attrs.alloc(state.ctx.symbols.sym_name) = {NewValueAs::string, i.queryName(state)};
auto system = i.querySystem(state);
if (!system.empty())
attrs.alloc(state.ctx.s.system).mkString(system);
attrs.alloc(state.ctx.s.outPath).mkString(state.ctx.store->printStorePath(i.queryOutPath(state)));
attrs.alloc(state.ctx.symbols.sym_system) = {NewValueAs::string, system};
attrs.alloc(state.ctx.symbols.sym_outPath) = {
NewValueAs::string, state.ctx.store->printStorePath(i.queryOutPath(state))
};
if (drvPath)
attrs.alloc(state.ctx.s.drvPath).mkString(state.ctx.store->printStorePath(*drvPath));
attrs.alloc(state.ctx.symbols.sym_drvPath) = {
NewValueAs::string, state.ctx.store->printStorePath(*drvPath)
};
// Copy each output meant for installation.
auto & vOutputs = attrs.alloc(state.ctx.s.outputs);
auto & vOutputs = attrs.alloc(state.ctx.symbols.sym_outputs);
auto outputsList = state.ctx.mem.newList(outputs.size());
vOutputs = {NewValueAs::list, outputsList};
for (const auto & [m, j] : enumerate(outputs)) {
outputsList->elems[m].mkString(j.first);
outputsList->elems[m] = {NewValueAs::string, j.first};
auto outputAttrs = state.ctx.buildBindings(2);
outputAttrs.alloc(state.ctx.s.outPath).mkString(state.ctx.store->printStorePath(*j.second));
attrs.alloc(j.first).mkAttrs(outputAttrs);
outputAttrs.alloc(state.ctx.symbols.sym_outPath) = {
NewValueAs::string, state.ctx.store->printStorePath(*j.second)
};
attrs.alloc(j.first) = {NewValueAs::attrs, outputAttrs};
/* This is only necessary when installing store paths, e.g.,
`nix-env -i /nix/store/abcd...-foo'. */
@@ -81,9 +87,9 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
meta.insert(state.ctx.symbols.create(j), *v);
}
attrs.alloc(state.ctx.s.meta).mkAttrs(meta);
attrs.alloc(state.ctx.symbols.sym_meta) = {NewValueAs::attrs, meta};
manifest->elems[n++].mkAttrs(attrs);
manifest->elems[n++] = {NewValueAs::attrs, attrs};
if (drvPath) references.insert(*drvPath);
}
@@ -97,18 +103,17 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
str.str(), references));
/* Get the environment builder expression. */
Value envBuilder;
state.eval(state.ctx.parseExprFromString(
#include "buildenv.nix.gen.hh"
, CanonPath::root), envBuilder);
Value envBuilder = state.eval(state.ctx.parseExprFromString(
#include "buildenv.nix.gen.hh"
, CanonPath::root
));
/* Construct a Nix expression that calls the user environment
builder with the manifest as argument. */
auto attrs = state.ctx.buildBindings(3);
state.ctx.paths.mkStorePathString(manifestFile, attrs.alloc("manifest"));
attrs.insert(state.ctx.symbols.create("derivations"), vManifest);
Value args;
args.mkAttrs(attrs);
Value args = {NewValueAs::attrs, attrs};
Value topLevel{NewValueAs::app, state.ctx.mem, envBuilder, args};
@@ -116,9 +121,9 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
debug("evaluating user environment builder");
state.forceValue(topLevel, noPos);
NixStringContext context;
const Attr & aDrvPath(*topLevel.attrs()->get(state.ctx.s.drvPath));
const Attr & aDrvPath(*topLevel.attrs()->get(state.ctx.symbols.sym_drvPath));
auto topLevelDrv = state.coerceToStorePath(aDrvPath.pos, aDrvPath.value, context, "");
const Attr & aOutPath(*topLevel.attrs()->get(state.ctx.s.outPath));
const Attr & aOutPath(*topLevel.attrs()->get(state.ctx.symbols.sym_outPath));
auto topLevelOut = state.coerceToStorePath(aOutPath.pos, aOutPath.value, context, "");
/* Realise the resulting store expression. */
+5 -2
View File
@@ -20,8 +20,7 @@ DrvInfos queryInstalled(EvalState & state, const Path & userEnv)
throw Error("profile '%s' is incompatible with 'nix-env'; please use 'nix profile' instead", userEnv);
auto manifestFile = userEnv + "/manifest.nix";
if (pathExists(manifestFile)) {
Value v;
state.evalFile(CanonPath(manifestFile), v);
Value v = state.evalFile(CanonPath(manifestFile));
Bindings & bindings(*state.ctx.mem.allocBindings(0));
getDerivations(state, v, "", bindings, elems, false);
}
@@ -99,6 +98,10 @@ void ProfileElement::updateStorePaths(
for (auto & output : bfd.outputs) {
storePaths.insert(output.second);
}
if (settings.envKeepDerivations) {
storePaths.insert(bfd.drvPath.path);
}
},
},
buildable.raw()
+2 -6
View File
@@ -15,8 +15,6 @@ namespace nix {
extern std::string programPath;
extern char * * savedArgv;
class EvalState;
struct Pos;
class Store;
@@ -173,7 +171,7 @@ struct RawInstallablesCommand : virtual Args, SourceExprCommand
std::vector<FlakeRef> getFlakeRefsForCompletion() override;
private:
protected:
std::vector<std::string> rawInstallables;
};
@@ -222,13 +220,11 @@ struct MixOperateOnOptions : virtual Args
*/
struct BuiltPathsCommand : InstallablesCommand, virtual MixOperateOnOptions
{
private:
protected:
bool recursive = false;
bool all = false;
protected:
Realise realiseMode = Realise::Derivation;
public:
+2 -4
View File
@@ -185,11 +185,9 @@ Bindings * MixEvalArgs::getAutoArgs(Evaluator & state)
for (auto & i : autoArgs) {
Value v;
if (i.second[0] == 'E')
state.evalLazily(
state.parseExprFromString(i.second.substr(1), CanonPath::fromCwd()), v
);
v = state.evalLazily(state.parseExprFromString(i.second.substr(1), CanonPath::fromCwd()));
else
v.mkString(((std::string_view) i.second).substr(1));
v = {NewValueAs::string, ((std::string_view) i.second).substr(1)};
res.insert(state.symbols.create(i.first), v);
}
return res.finish();
+76
View File
@@ -0,0 +1,76 @@
#pragma once
///@file
#include <string_view>
#include <type_traits>
#include <utility>
#include <optional>
#include <ranges>
#include "lix/libutil/args.hh"
namespace nix::cli {
template<typename Enum>
struct enum_cli_traits;
template<typename Enum>
constexpr std::string_view toString(Enum value)
{
for (const auto & [name, val] : enum_cli_traits<Enum>::values) {
if (val == value) {
return name;
}
}
std::terminate();
}
template<typename Enum>
std::optional<Enum> fromString(std::string_view str)
{
for (const auto & [name, val] : enum_cli_traits<Enum>::values) {
if (name == str) {
return val;
}
}
return std::nullopt;
}
template<typename Enum>
void completeAmongEnumChoices(AddCompletions & completions, size_t, std::string_view prefix)
{
for (const auto & [name, _] : enum_cli_traits<Enum>::values) {
if (name.starts_with(prefix)) {
completions.add(name);
}
}
}
template<typename Enum>
Enum parseEnumArg(std::string text)
{
auto valueOpt = fromString<Enum>(text);
if (valueOpt) {
return *valueOpt;
} else {
auto names = std::ranges::views::keys(enum_cli_traits<Enum>::values)
| std::ranges::to<std::set<std::string>>();
auto suggestions = Suggestions::bestMatches(names, text);
throw UsageError(suggestions, "'%s' is not a recognised '%s'", text, enum_cli_traits<Enum>::typeName);
}
}
template<typename Enum>
std::optional<Enum> parseOptionalEnumArg(std::string text)
{
auto target = fromString<Enum>(text);
if (!target && text != "") {
auto names = std::ranges::views::keys(enum_cli_traits<Enum>::values) | std::ranges::to<std::set>();
auto suggestions = Suggestions::bestMatches(names, text);
throw UsageError(suggestions, "'%s' is not a recognised '%s'", text, enum_cli_traits<Enum>::typeName);
}
return target;
}
}
-2
View File
@@ -7,8 +7,6 @@
#include "lix/libexpr/flake/flake.hh"
#include "lix/libexpr/eval-cache.hh"
#include <nlohmann/json.hpp>
namespace nix {
std::vector<std::string> InstallableFlake::getActualAttrPaths()
+6 -9
View File
@@ -219,8 +219,7 @@ void SourceExprCommand::completeInstallable(EvalState & state, AddCompletions &
state.aio.blockOn(lookupFileArg(*evaluator, *file)).unwrap()
));
Value root;
state.eval(e, root);
Value root = state.eval(e);
auto autoArgs = getAutoArgs(*evaluator);
@@ -237,8 +236,7 @@ void SourceExprCommand::completeInstallable(EvalState & state, AddCompletions &
auto [v1, pos] = findAlongAttrPath(state, prefix_, *autoArgs, root);
state.forceValue(v1, pos);
Value v2;
state.autoCallFunction(*autoArgs, v1, v2, pos);
Value v2 = state.autoCallFunction(*autoArgs, v1, pos);
if (v2.type() == nAttrs) {
for (auto & i : *v2.attrs()) {
@@ -411,8 +409,7 @@ ref<eval_cache::EvalCache> openEvalCache(
if (getEnv("NIX_ALLOW_EVAL").value_or("1") == "0")
throw Error("not everything is cached, but evaluation is not allowed");
Value vFlake;
flake::callFlake(state, *lockedFlake, vFlake);
Value vFlake = flake::callFlake(state, *lockedFlake);
state.forceAttrs(vFlake, noPos, "while parsing cached flake data");
@@ -453,13 +450,13 @@ Installables SourceExprCommand::parseInstallables(
if (file == "-") {
auto & e = evaluator->parseStdin();
state.eval(e, vFile);
vFile = state.eval(e);
}
else if (file)
state.evalFile(state.aio.blockOn(lookupFileArg(*evaluator, *file)).unwrap(), vFile);
vFile = state.evalFile(state.aio.blockOn(lookupFileArg(*evaluator, *file)).unwrap());
else {
auto & e = evaluator->parseExprFromString(*expr, CanonPath::fromCwd());
state.eval(e, vFile);
vFile = state.eval(e);
}
for (auto & s : ss) {
+17 -3
View File
@@ -5,18 +5,32 @@
#include <functional>
#include <list>
#include <map>
#include <span>
#include <string>
namespace nix {
typedef std::function<int(AsyncIoRoot &, std::string, std::list<std::string>)> MainFunction;
struct LegacyCommandRegistry
{
using LegacyCommandMap = std::map<std::string, MainFunction>;
typedef std::function<int(AsyncIoRoot &, std::string, std::list<std::string>)> MainFunction;
typedef std::function<
int(AsyncIoRoot &, std::string, std::list<std::string>, std::span<char *>)>
RawMainFunction;
using LegacyCommandMap = std::map<std::string, RawMainFunction>;
static LegacyCommandMap * commands;
static void add(const std::string & name, MainFunction fun)
{
addWithRaw(
name,
[fun](AsyncIoRoot & aio, std::string name, std::list<std::string> args, std::span<char *>) {
return fun(aio, name, args);
}
);
}
static void addWithRaw(const std::string & name, RawMainFunction fun)
{
if (!commands) commands = new LegacyCommandMap;
(*commands)[name] = fun;
+1 -3
View File
@@ -5,6 +5,4 @@ includedir=@includedir@
Name: Lix (libcmd)
Description: Lix Package Manager (libcmd)
Version: @PACKAGE_VERSION@
Requires: lix-base lix-util lix-store
Requires.private: lix-fetchers lix-expr lix-main @BOEHM_IF_FOUND@ libeditline lowdown ncurses
Libs: -L${libdir} @LIBLIX_DOC_IF_STATIC@ -llixcmd
Requires: lix
+3 -62
View File
@@ -1,4 +1,4 @@
libcmd_sources = files(
liblix_sources += files(
'built-path.cc',
'cmd-profiles.cc',
'command.cc',
@@ -21,6 +21,7 @@ libcmd_headers = files(
'command.hh',
'common-eval-args.hh',
'editor-for.hh',
'enum-traits.hh',
'installable-attr-path.hh',
'installable-derived-path.hh',
'installable-flake.hh',
@@ -32,68 +33,8 @@ libcmd_headers = files(
'repl.hh',
)
libcmd_generated_headers = [
liblix_generated_headers += [
gen_header.process('repl-overlays.nix', preserve_path_from: meson.current_source_dir()),
]
libcmd = library(
'lixcmd',
libcmd_generated_headers,
libcmd_sources,
dependencies : [
liblixutil,
liblixstore,
liblixfetchers,
liblixexpr,
liblixmain,
liblix_doc,
boehm,
editline,
kj,
lowdown,
ncurses,
nlohmann_json,
],
# '../..' for self references like "lix/libcmd/*.hh"
include_directories : [ '../..' ],
cpp_pch : cpp_pch,
install : true,
# FIXME(Qyriad): is this right?
install_rpath : libdir,
)
install_headers(libcmd_headers, subdir : 'lix/libcmd', preserve_path : true)
custom_target(
command : [ 'cp', '@INPUT@', '@OUTPUT@' ],
input : libcmd_generated_headers,
output : '@PLAINNAME@',
install : true,
install_dir : includedir / 'lix/libcmd',
)
liblixcmd = declare_dependency(
include_directories : include_directories('../..'),
dependencies : [
liblixutil,
liblixstore,
kj,
],
link_with : libcmd,
)
meson.override_dependency('lix-cmd', liblixcmd)
# FIXME: not using the pkg-config module because it creates way too many deps
# while meson migration is in progress, and we want to not include boost here
configure_file(
input : 'lix-cmd.pc.in',
output : 'lix-cmd.pc',
install_dir : libdir / 'pkgconfig',
configuration : {
'prefix' : prefix,
'libdir' : libdir,
'includedir' : includedir,
'PACKAGE_VERSION' : meson.project_version(),
'BOEHM_IF_FOUND' : boehm.found() ? 'bdw-gc' : '',
'LIBLIX_DOC_IF_STATIC' : is_static ? '-llix_doc' : '',
},
)
+1 -1
View File
@@ -48,7 +48,7 @@ char ** copyCompletions(const StringSet& possible)
if (vp) {
while (--ac >= 0)
free(vp[ac]);
free(vp);
free(static_cast<void *>(vp));
}
throw Error("allocation failure");
}
+1 -1
View File
@@ -46,7 +46,7 @@ public:
*
* This function logs but ignores errors from readline's write_history().
*/
virtual void writeHistory();
void writeHistory();
virtual ~ReadlineLikeInteracter() override;
};
+906 -450
View File
File diff suppressed because it is too large Load Diff
+86
View File
@@ -0,0 +1,86 @@
#include "common.hh"
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <format>
#include <sched.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
LIBEXEC_HELPER(0)
static int waitFor(pid_t child)
{
int status;
while (true) {
if (waitpid(child, &status, 0) == -1) {
if (errno != EINTR) {
DIE_UNLESS_SYS("waitpid()", -1);
}
} else if (WIFEXITED(status)) {
return WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
die(std::format("child died with signal {}", WTERMSIG(status)));
} else {
die(std::format("child exited {}", status));
}
}
}
int helperMain(const char * name, std::span<char *> args) noexcept
{
size_t stackSize = 1ul * 1024 * 1024;
auto stack = static_cast<char *>(
mmap(0, stackSize, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0)
);
if (stack == MAP_FAILED) {
die(std::format("mmap(): {}", strerror(errno)));
}
const bool haveUserNS = [&] {
auto child = clone([](void *) { return 0; }, stack + stackSize, CLONE_NEWUSER | SIGCHLD, nullptr);
if (child == -1) {
printf("user %s\n", strerror(errno));
return false;
} else if (auto status = waitFor(child)) {
die(std::format("userns check child failed unexpectedly with status {}", status));
} else {
printf("user\n");
return true;
}
}();
{
auto child = clone(
[](void *) {
/* Make sure we don't remount the parent's /proc. */
if (mount(0, "/", 0, MS_PRIVATE | MS_REC, 0) == -1) {
return 1;
}
/* Test whether we can remount /proc. The kernel disallows
this if /proc is not fully visible, i.e. if there are
filesystems mounted on top of files inside /proc. See
https://lore.kernel.org/lkml/87tvsrjai0.fsf@xmission.com/T/. */
if (mount("none", "/proc", "proc", 0, 0) == -1) {
return 2;
}
return 0;
},
stack + stackSize,
CLONE_NEWNS | CLONE_NEWPID | (haveUserNS ? CLONE_NEWUSER : 0) | SIGCHLD,
nullptr
);
if (child == -1) {
printf("mount-pid %s\n", strerror(errno));
} else if (waitFor(child) != 0) {
printf("mount-pid failed to remount /proc\n");
} else {
printf("mount-pid\n");
}
}
return 0;
}
+103
View File
@@ -0,0 +1,103 @@
#pragma once
///@file common setup/utility header for libexec helpers
#include <cctype>
#include <cerrno>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <format> // IWYU pragma: keep
#include <limits>
#include <span>
#include <string> // IWYU pragma: keep
#include <string_view>
#include <type_traits>
#include <unistd.h>
/// file descriptor of the error reporting pipe. anything written to this pipe
/// will be treated as a fatal error message regardless of helper exit status.
/// an empty line (a single `\n` byte) will be treated as successful startup,
/// any errors encountered later can be retrieved by the parent in due course.
inline int ERR_PIPE;
inline void writeErrPipe(std::string_view msg)
{
while (!msg.empty()) {
if (auto wrote = write(ERR_PIPE, msg.data(), msg.size()); wrote >= 0) {
msg.remove_prefix(size_t(wrote));
} else {
break;
}
}
}
/// immediately terminate helper execution with a fatal error.
[[noreturn]]
inline void die(std::string_view msg)
{
writeErrPipe(msg);
exit(252);
}
/// converts an argument to an integer or dies with a message.
template<typename T, size_t N>
requires std::is_integral_v<T>
T argToInt(const char (&argName)[N], const char * str)
{
// this should really just wrap std::from_chars, but macos doesn't have it.
for (const auto c : std::string_view(str)) {
if (c != '-' && !std::isdigit(c)) {
die(std::format("invalid {} argument", argName));
}
}
char * end = nullptr;
const auto tmp = [&] {
if constexpr (std::is_signed_v<T>) {
return std::strtoimax(str, &end, 10); // NOLINT(lix-unsafe-c-calls): str is a C string
} else {
return std::strtoumax(str, &end, 10); // NOLINT(lix-unsafe-c-calls): str is a C string
}
}();
if (!end || *end || tmp < std::numeric_limits<T>::min() || tmp > std::numeric_limits<T>::max()) {
die(std::format("invalid {} argument", argName));
}
return tmp;
}
/// check syscall result and immediately terminate with a message on failure.
#define DIE_UNLESS_SYS(name, expr) \
([&] { \
if ((expr) == -1) { \
die(std::format("{}: {}", name, strerror(errno))); \
} \
}())
/// declare the TU expanding this as a libexec helper with at least `expectedArgs`
/// arguments. more arguments may be passed, fewer args will be treated as a fatal
/// error and reported immediately. a valid ERR_PIPE pipe must be passed as as the
/// first argument and will be set to close-on-exec to not pass it on to children.
#define LIBEXEC_HELPER(expectedArgs) \
int main(int argc, char * argv[]) \
{ \
if (argc < (expectedArgs) + 2) { \
_exit(254); \
} \
\
try { \
/* NOTE: we purposely accept imperfect conversion, only errors are fatal. \
if our parent messes this up we have *much* bigger problems than this. */ \
ERR_PIPE = std::stoi(argv[1]); \
} catch (...) { \
_exit(253); \
} \
\
DIE_UNLESS_SYS("error pipe fcntl", fcntl(ERR_PIPE, F_SETFD, FD_CLOEXEC)); \
return helperMain(argv[0], {argv + 2, argv + argc}); \
}
int helperMain(const char * name, std::span<char *> args) noexcept;
+60
View File
@@ -0,0 +1,60 @@
#include "common.hh"
#include <charconv>
#include <cstring>
#include <format>
#include <signal.h>
#include <unistd.h>
#if __APPLE__
#include <sys/syscall.h>
#endif
LIBEXEC_HELPER(1)
int helperMain(const char * name, std::span<char *> args) noexcept
{
std::string_view uidArg = args[0];
uid_t uid;
if (auto res = std::from_chars(uidArg.begin(), uidArg.end(), uid);
res.ptr != uidArg.end() || res.ec != std::errc())
{
die("invalid uid argument");
}
/* The system call kill(-1, sig) sends the signal `sig' to all
users to which the current process can send signals. So we
switch to that uid and send a mass kill once we've done so. */
if (setuid(uid) == -1) {
die(std::format("setuid(): {}", strerror(errno)));
}
while (true) {
#ifdef __APPLE__
/* OSX's kill syscall takes a third parameter that, among
other things, determines if kill(-1, signo) affects the
calling process. In the OSX libc, it's set to true,
which means "follow POSIX", which we don't want here */
if (syscall(SYS_kill, -1, SIGKILL, false) == 0) {
break;
}
#else
if (kill(-1, SIGKILL) == 0) {
break;
}
#endif
if (errno == ESRCH || errno == EPERM) {
break; /* no more processes */
}
if (errno != EINTR) {
die(std::format("cannot kill processes for uid {}: {}", uid, strerror(errno)));
}
}
/* !!! We should really do some check to make sure that there are
no processes left running under `uid', but there is no portable
way to do so (I think). The most reliable way may be `ps -eo
uid | grep -q $uid'. */
return 0;
}
+90
View File
@@ -0,0 +1,90 @@
#include "launch-builder.hh"
#include "lix/libstore/build/request.capnp.h"
#include "lix/libutil/rpc.hh"
#include <cstdlib>
#include <spawn.h>
#include <string_view>
#include <sys/sysctl.h>
#include <unistd.h>
namespace nix {
/* This definition is undocumented but depended upon by all major browsers. */
extern "C" int sandbox_init_with_parameters(
const char * profile, uint64_t flags, const char * const parameters[], char ** errorbuf
);
bool prepareChildSetup(build::Request::Reader request)
{
return true;
}
void finishChildSetup(build::Request::Reader request)
{
const auto config = request.getPlatform().getDarwin();
/* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try
different mechanisms to find temporary directories, so we want to open up a broader place for them
to put their files, if needed. */
auto globalTmpDir = rpc::to<std::string>(config.getGlobalTempDir());
/* They don't like trailing slashes on subpath directives */
if (globalTmpDir.back() == '/') {
globalTmpDir.pop_back();
}
if (auto env = getenv("_NIX_TEST_NO_SANDBOX"); env && env != std::string_view("1")) {
std::vector<const char *> sandboxArgs;
sandboxArgs.push_back("_NIX_BUILD_TOP");
sandboxArgs.push_back(config.getTempDir().cStr());
sandboxArgs.push_back("_GLOBAL_TMP_DIR");
sandboxArgs.push_back(globalTmpDir.c_str());
if (config.getAllowLocalNetworking()) {
sandboxArgs.push_back("_ALLOW_LOCAL_NETWORKING");
sandboxArgs.push_back("1");
}
sandboxArgs.push_back(nullptr);
// NOLINTNEXTLINE(lix-unsafe-c-calls): all of these are env names or paths
if (sandbox_init_with_parameters(config.getSandboxProfile().cStr(), 0, sandboxArgs.data(), nullptr)) {
writeFull(STDERR_FILENO, "failed to configure sandbox\n");
_exit(1);
}
}
}
[[noreturn]]
void execBuilder(build::Request::Reader request)
{
const auto config = request.getPlatform().getDarwin();
posix_spawnattr_t attrp;
if (posix_spawnattr_init(&attrp)) {
throw SysError("failed to initialize builder");
}
if (posix_spawnattr_setflags(&attrp, POSIX_SPAWN_SETEXEC)) {
throw SysError("failed to initialize builder");
}
const auto platform = rpc::to<std::string_view>(config.getPlatform());
if (platform == "aarch64-darwin") {
// Unset kern.curproc_arch_affinity so we can escape Rosetta
int affinity = 0;
sysctlbyname("kern.curproc_arch_affinity", nullptr, nullptr, &affinity, sizeof(affinity));
cpu_type_t cpu = CPU_TYPE_ARM64;
posix_spawnattr_setbinpref_np(&attrp, 1, &cpu, nullptr);
} else if (platform == "x86_64-darwin") {
cpu_type_t cpu = CPU_TYPE_X86_64;
posix_spawnattr_setbinpref_np(&attrp, 1, &cpu, nullptr);
}
ExecRequest req{request};
posix_spawn(nullptr, req.builder.c_str(), nullptr, &attrp, req.args.data(), req.envs.data());
throw SysError(errno, std::format("running {}", req.builder));
}
}
+24
View File
@@ -0,0 +1,24 @@
#include "launch-builder.hh"
#include "lix/libstore/build/request.capnp.h"
#include <format>
#include <string>
#include <unistd.h>
namespace nix {
bool prepareChildSetup(build::Request::Reader config)
{
return true;
}
void finishChildSetup(build::Request::Reader config) {}
void execBuilder(build::Request::Reader config)
{
ExecRequest req{config};
execve(req.builder.data(), req.args.data(), req.envs.data());
throw SysError("running %s", req.builder);
}
}
+446
View File
@@ -0,0 +1,446 @@
#include "launch-builder.hh"
#include "lix/libstore/build/request.capnp.h"
#include "lix/libutil/rpc.hh"
#include <cassert>
#include <csignal>
#include <filesystem>
#include <format>
#include <kj/io.h>
#include <net/if.h>
#include <netinet/in.h>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
#if HAVE_SECCOMP
#include <linux/filter.h>
#include <sys/syscall.h>
#include <seccomp.h>
#endif
namespace fs = std::filesystem;
namespace nix {
// TODO dedup with libutil
static void setPersonality(std::string_view system)
{
/* Change the personality to 32-bit if we're doing an
i686-linux build on an x86_64-linux machine. */
struct utsname utsbuf;
uname(&utsbuf);
if ((system == "i686-linux"
&& (std::string_view(SYSTEM) == "x86_64-linux"
|| (!strcmp(utsbuf.sysname, "Linux") && !strcmp(utsbuf.machine, "x86_64"))))
|| system == "armv7l-linux" || system == "armv6l-linux" || system == "armv5tel-linux")
{
if (personality(PER_LINUX32) == -1) {
throw SysError("cannot set 32-bit personality");
}
}
/* Disable address space randomization for improved
determinism. */
int cur = personality(0xffffffff);
if (cur != -1) {
personality(cur | ADDR_NO_RANDOMIZE);
}
}
bool pathExists(const fs::path & path)
{
return fs::exists(fs::symlink_status(path));
}
void bindPath(const fs::path & source, const fs::path & target, bool optional = false)
{
debug("bind mounting %1% to %2%", source, target);
auto bindMount = [&]() {
if (mount(source.c_str(), target.c_str(), "", MS_BIND | MS_REC, 0) == -1) {
throw SysError("bind mount from %1% to %2% failed", source, target);
}
};
auto st = fs::symlink_status(source);
if (st.type() == fs::file_type::not_found) {
if (optional) {
return;
} else {
throw SysError("getting attributes of path %1%", source);
}
}
if (st.type() == fs::file_type::directory) {
fs::create_directories(target);
bindMount();
} else if (st.type() == fs::file_type::symlink) {
// Symlinks can (apparently) not be bind-mounted, so just copy it
fs::create_directories(target.parent_path());
fs::copy_symlink(source, target);
} else {
fs::create_directories(target.parent_path());
if (kj::AutoCloseFd file{open(target.c_str(), O_RDWR | O_CREAT, 0644)}; file == nullptr) {
throw SysError("could not create %s", target);
}
bindMount();
}
}
bool prepareChildSetup(build::Request::Reader request)
{
auto config = request.getPlatform().getLinux();
// Set the NO_NEW_PRIVS prctl flag.
// This both makes loading seccomp filters work for unprivileged users,
// and is an additional security measure in its own right.
if (prctl(PR_SET_NO_NEW_PRIVS, 1L, 0L, 0L, 0L) == -1) {
throw SysError("PR_SET_NO_NEW_PRIVS failed");
}
#if HAVE_SECCOMP
if (config.hasSeccompFilters()) {
const auto seccompBPF = config.getSeccompFilters();
const auto entries = seccompBPF.size() / sizeof(struct sock_filter);
assert(entries <= std::numeric_limits<unsigned short>::max());
struct sock_fprog fprog = {
.len = static_cast<unsigned short>(entries),
// the kernel does not actually write to the filter, and doesn't care about alignment
.filter = const_cast<struct sock_filter *>(
reinterpret_cast<const struct sock_filter *>(seccompBPF.begin())
),
};
if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &fprog) != 0) {
throw SysError("unable to load seccomp BPF program");
}
}
#endif
KJ_DEFER(setPersonality(rpc::to<std::string_view>(config.getPlatform())));
if (!config.hasSandbox()) {
return true;
}
auto sandbox = config.getSandbox();
// NOLINTBEGIN(lix-unsafe-c-calls): we trust the parent that all sandbox config is correct.
// no strings in the linux sandbox config can be set by normal users or derivation authors,
// except (in single-user instances) storeDir and chrootRootDir, which must be valid paths.
//
// NOLINTBEGIN(lix-foreign-exceptions): they're all properly caught by the builder main fn.
const fs::path chrootRootDir{rpc::to<std::string_view>(sandbox.getChrootRootDir())};
if (sandbox.getPrivateNetwork()) {
/* Initialise the loopback interface. */
kj::AutoCloseFd fd(socket(PF_INET, SOCK_DGRAM, IPPROTO_IP));
if (fd == nullptr) {
throw SysError("cannot open IP socket");
}
struct ifreq ifr;
strcpy(ifr.ifr_name, "lo");
ifr.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING;
if (ioctl(fd.get(), SIOCSIFFLAGS, &ifr) == -1) {
throw SysError("cannot set loopback interface flags");
}
}
/* Set the hostname etc. to fixed values. */
char hostname[] = "localhost";
if (sethostname(hostname, sizeof(hostname)) == -1) {
throw SysError("cannot set host name");
}
char domainname[] = "(none)"; // kernel default
if (setdomainname(domainname, sizeof(domainname)) == -1) {
throw SysError("cannot set domain name");
}
/* Make all filesystems private. This is necessary
because subtrees may have been mounted as "shared"
(MS_SHARED). (Systemd does this, for instance.) Even
though we have a private mount namespace, mounting
filesystems on top of a shared subtree still propagates
outside of the namespace. Making a subtree private is
local to the namespace, though, so setting MS_PRIVATE
does not affect the outside world. */
const fs::path storeDir{rpc::to<std::string>(sandbox.getStoreDir())};
const auto chrootStoreDir = chrootRootDir / storeDir.relative_path();
if (mount(0, "/", 0, MS_PRIVATE | MS_REC, 0) == -1) {
throw SysError("unable to make '/' private");
}
/* Bind-mount chroot directory to itself, to treat it as a
different filesystem from /, as needed for pivot_root. */
if (mount(chrootRootDir.c_str(), chrootRootDir.c_str(), "", MS_BIND, 0) == -1) {
throw SysError("unable to bind mount %1%", chrootRootDir);
}
/* Bind-mount the sandbox's Nix store onto itself so that
we can mark it as a "shared" subtree, allowing bind
mounts made in *this* mount namespace to be propagated
into the child namespace created by the
unshare(CLONE_NEWNS) call below.
Marking chrootRootDir as MS_SHARED causes pivot_root()
to fail with EINVAL. Don't know why. */
if (mount(chrootStoreDir.c_str(), chrootStoreDir.c_str(), "", MS_BIND, 0) == -1) {
throw SysError("unable to bind mount the Nix store");
}
if (mount("", chrootStoreDir.c_str(), "", MS_SHARED, 0) == -1) {
throw SysError("unable to make %s shared", chrootStoreDir);
}
bool devMounted = false;
bool devPtsMounted = false;
/* Bind-mount all the directories from the "host"
filesystem that we want in the chroot
environment. */
for (auto path : sandbox.getPaths()) {
const fs::path source{rpc::to<std::string_view>(path.getSource())};
const fs::path target{rpc::to<std::string_view>(path.getTarget())};
devMounted |= target == "/dev";
devPtsMounted |= target == "/dev/pts";
if (source == "/proc") {
continue; // backwards compatibility
}
#if HAVE_EMBEDDED_SANDBOX_SHELL
if (source == "__embedded_sandbox_shell__") {
static unsigned char sh[] = {
#include "embedded-sandbox-shell.gen.hh"
};
const fs::path dst = chrootRootDir / target.relative_path();
fs::create_directories(dst.parent_path());
writeFile(dst, std::string_view((const char *) sh, sizeof(sh)));
fs::permissions(dst, fs::perms(0555));
} else
#endif
bindPath(source, chrootRootDir / target.relative_path(), path.getOptional());
}
/* Set up a nearly empty /dev, unless the user asked to
bind-mount the host /dev. */
if (!devMounted) {
const auto bind = [&](fs::path item) { bindPath(item, chrootRootDir / item.relative_path()); };
fs::create_directories(chrootRootDir / "dev/shm");
fs::create_directories(chrootRootDir / "dev/pts");
bind("/dev/full");
if (sandbox.getWantsKvm() && pathExists("/dev/kvm")) {
bind("/dev/kvm");
}
bind("/dev/null");
bind("/dev/random");
bind("/dev/tty");
bind("/dev/urandom");
bind("/dev/zero");
fs::create_symlink("/proc/self/fd", chrootRootDir / "dev/fd");
fs::create_symlink("/proc/self/fd/0", chrootRootDir / "dev/stdin");
fs::create_symlink("/proc/self/fd/1", chrootRootDir / "dev/stdout");
fs::create_symlink("/proc/self/fd/2", chrootRootDir / "dev/stderr");
}
/* Bind a new instance of procfs on /proc. */
fs::create_directories(chrootRootDir / "proc");
if (mount("none", (chrootRootDir / "proc").c_str(), "proc", 0, 0) == -1) {
throw SysError("mounting /proc");
}
/* Mount sysfs on /sys. */
if (request.hasCredentials() && request.getCredentials().getUidCount() != 1) {
fs::create_directories(chrootRootDir / "sys");
if (mount("none", (chrootRootDir / "sys").c_str(), "sysfs", 0, 0) == -1) {
throw SysError("mounting /sys");
}
}
/* Mount a new tmpfs on /dev/shm to ensure that whatever
the builder puts in /dev/shm is cleaned up automatically. */
if (pathExists("/dev/shm")
&& mount("none", (chrootRootDir / "dev/shm").c_str(), "tmpfs", 0, sandbox.getSandboxShmFlags().cStr())
== -1)
{
throw SysError("mounting /dev/shm");
}
/* Mount a new devpts on /dev/pts. Note that this
requires the kernel to be compiled with
CONFIG_DEVPTS_MULTIPLE_INSTANCES=y (which is the case
if /dev/ptx/ptmx exists). */
if (pathExists("/dev/pts/ptmx") && !pathExists(chrootRootDir / "dev/ptmx") && !devPtsMounted) {
if (mount("none", (chrootRootDir / "dev/pts").c_str(), "devpts", 0, "newinstance,mode=0620") == 0) {
fs::create_symlink("/dev/pts/ptmx", chrootRootDir / "dev/ptmx");
/* Make sure /dev/pts/ptmx is world-writable. With some
Linux versions, it is created with permissions 0. */
fs::permissions(chrootRootDir / "dev/pts/ptmx", fs::perms(0666));
} else {
if (errno != EINVAL) {
throw SysError("mounting /dev/pts");
}
bindPath("/dev/pts", chrootRootDir / "dev/pts");
bindPath("/dev/ptmx", chrootRootDir / "dev/ptmx");
}
}
/* Make /etc unwritable */
if (!sandbox.getUseUidRange()) {
fs::permissions(chrootRootDir / "etc", fs::perms(0555));
}
/* The comment below is now outdated. Recursive Nix has been removed.
* So there's no need to make path appear in the sandbox.
* TODO(Raito): cleanup before a merge.
*/
/* Unshare this mount namespace. This is necessary because
pivot_root() below changes the root of the mount
namespace. This means that the call to setns() in
addDependency() would hide the host's filesystem,
making it impossible to bind-mount paths from the host
Nix store into the sandbox. Therefore, we save the
pre-pivot_root namespace in
sandboxMountNamespace. Since we made /nix/store a
shared subtree above, this allows addDependency() to
make paths appear in the sandbox. */
if (unshare(CLONE_NEWNS) == -1) {
throw SysError("unsharing mount namespace");
}
/* Creating a new cgroup namespace is independent of whether we enabled the cgroup experimental feature.
* We always create a new cgroup namespace from a sandboxing perspective. */
/* Unshare the cgroup namespace. This means
/proc/self/cgroup will show the child's cgroup as '/'
rather than whatever it is in the parent. */
if (unshare(CLONE_NEWCGROUP) == -1) {
throw SysError("unsharing cgroup namespace");
}
/* Do the chroot(). */
if (chdir(chrootRootDir.c_str()) == -1) {
throw SysError("cannot change directory to %1%", chrootRootDir);
}
if (mkdir("real-root", 0) == -1) {
throw SysError("cannot create real-root directory");
}
if (syscall(SYS_pivot_root, ".", "real-root") == -1) {
throw SysError("cannot pivot old root directory onto %1%", chrootRootDir / "real-root");
}
if (chroot(".") == -1) {
throw SysError("cannot change root directory to %1%", chrootRootDir);
}
if (umount2("real-root", MNT_DETACH) == -1) {
throw SysError("cannot unmount real root filesystem");
}
if (rmdir("real-root") == -1) {
throw SysError("cannot remove real-root directory");
}
/* Switch to the sandbox uid/gid in the user namespace,
which corresponds to the build user or calling user in
the parent namespace. */
if (setgid(sandbox.getGid()) == -1) {
throw SysError("setgid failed");
}
if (setuid(sandbox.getUid()) == -1) {
throw SysError("setuid failed");
}
if (sandbox.hasWaitForInterface()) {
// wait for the pasta interface to appear. pasta can't signal us when
// it's done setting up the namespace, so we have to wait for a while
kj::AutoCloseFd fd(socket(PF_INET, SOCK_DGRAM, IPPROTO_IP));
if (fd == nullptr) {
throw SysError("cannot open IP socket");
}
struct ifreq ifr;
strncpy(ifr.ifr_name, sandbox.getWaitForInterface().cStr(), sizeof(ifr.ifr_name));
// wait two minutes for the interface to appear. if it does not do so
// we are either grossly overloaded, or pasta startup failed somehow.
static constexpr int SINGLE_WAIT_US = 1000;
static constexpr int TOTAL_WAIT_US = 120'000'000;
for (unsigned tries = 0;; tries++) {
if (tries > TOTAL_WAIT_US / SINGLE_WAIT_US) {
throw std::runtime_error(
"sandbox network setup timed out, please check daemon logs for possible error output."
);
} else if (ioctl(fd.get(), SIOCGIFFLAGS, &ifr) == 0) {
if ((ifr.ifr_ifru.ifru_flags & IFF_UP) != 0) {
break;
}
} else if (errno == ENODEV) {
usleep(SINGLE_WAIT_US);
} else {
throw SysError("cannot get loopback interface flags");
}
}
}
// NOLINTEND(lix-foreign-exceptions)
// NOLINTEND(lix-unsafe-c-calls)
return false;
}
void finishChildSetup(build::Request::Reader request)
{
// clear all capabilities when not running as root in the sandbox.
// we always clear ambient capabilities because they survive exec.
if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0L, 0L, 0L) == -1) {
throw SysError("clearing ambient caps");
}
if (!request.getPlatform().getLinux().getSandbox().getUseUidRange()) {
static constexpr uint32_t LINUX_CAPABILITY_VERSION_3 = 0x20080522;
static constexpr uint32_t LINUX_CAPABILITY_U32S_3 = 2;
struct user_cap_header_struct
{
uint32_t version;
int pid;
} hdr = {LINUX_CAPABILITY_VERSION_3, 0};
struct user_cap_data_struct
{
uint32_t effective;
uint32_t permitted;
uint32_t inheritable;
} data[LINUX_CAPABILITY_U32S_3] = {};
if (syscall(SYS_capset, &hdr, data)) {
throw SysError("couldn't set capabilities");
}
}
if (prctl(PR_SET_PDEATHSIG, SIGKILL) == -1) {
throw SysError("setting death signal");
}
if (getppid() != request.getPlatform().getLinux().getParentPid()) {
raise(SIGKILL);
}
}
[[noreturn]]
void execBuilder(build::Request::Reader request)
{
ExecRequest req{request};
execve(req.builder.data(), req.args.data(), req.envs.data());
throw SysError("running %s", req.builder);
}
}
+225
View File
@@ -0,0 +1,225 @@
#include "launch-builder.hh"
#include "lix/libstore/build/request.capnp.h"
#include "lix/libutil/rpc.hh"
#include <capnp/message.h>
#include <capnp/serialize.h>
#include <csignal>
#include <cstdint>
#include <exception>
#include <fcntl.h>
#include <filesystem>
#include <grp.h>
#include <limits>
#include <sys/resource.h>
#include <unistd.h>
#include <vector>
namespace nix {
bool printDebugLogs = false;
static void requireCString(const char * context, const std::string & s)
{
if (s.contains('\0')) {
std::string p{s};
for (auto pos = p.find('\0'); pos != p.npos; pos = p.find('\0')) {
p.replace(pos, 1, "");
}
// NOLINTNEXTLINE(lix-foreign-exceptions)
throw std::runtime_error(std::format("derivation {} {} contains NUL bytes", context, p));
}
}
ExecRequest::ExecRequest(build::Request::Reader request)
{
const auto fill = [](auto context, auto & strings, auto & pointers, auto from) {
strings.reserve(from.size());
for (auto arg : from) {
strings.push_back(rpc::to<std::string>(arg));
requireCString(context, strings.back());
pointers.push_back(strings.back().data());
}
pointers.push_back(nullptr);
};
builder = rpc::to<std::string>(request.getBuilder());
requireCString("derivation builder", builder);
fill("derivation argument", argsStorage, args, request.getArgs());
fill("derivation environment entry", envsStorage, envs, request.getEnvironment());
}
void writeFull(int fd, std::string_view data)
{
while (!data.empty()) {
const auto wrote = ::write(fd, data.data(), data.size());
if (wrote < 0) {
throw SysError("write()");
} else {
data.remove_prefix(size_t(wrote));
}
}
}
static void closeExtraFDs()
{
constexpr int MAX_KEPT_FD = 2;
static_assert(std::max({STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO}) == MAX_KEPT_FD);
// Both Linux and FreeBSD support close_range.
#if __linux__ || __FreeBSD__
auto closeRange = [](unsigned int first, unsigned int last, int flags) -> int {
// musl does not have close_range as of 2024-08-10
// patch: https://www.openwall.com/lists/musl/2024/08/01/9
#if HAVE_CLOSE_RANGE
return close_range(first, last, flags);
#else
return syscall(SYS_close_range, first, last, flags);
#endif
};
// first try to close_range everything we don't care about. if this
// returns an error with these parameters we're running on a kernel
// that does not implement close_range (i.e. pre 5.9) and fall back
// to the old method. we should remove that though, in some future.
if (closeRange(3, ~0U, 0) == 0) {
return;
}
#endif
#if __linux__
try {
for (auto & s : std::filesystem::directory_iterator("/proc/self/fd")) {
auto fd = std::stoi(s.path().filename().c_str());
if (fd > MAX_KEPT_FD) {
debug("closing leaked FD %d", fd);
close(fd);
}
}
return;
} catch (std::exception &) { // NOLINT(lix-foreign-exceptions): that's what std::filesystem throws
}
#endif
int maxFD = 0;
maxFD = sysconf(_SC_OPEN_MAX);
for (int fd = MAX_KEPT_FD + 1; fd < maxFD; ++fd) {
close(fd); /* ignore result */
}
}
}
int main(int argc, char * argv[])
{
using namespace nix;
if (argc < 1) {
return 255;
}
bool sendException = true;
try {
capnp::MallocMessageBuilder buf;
capnp::readMessageCopyFromFd(
STDIN_FILENO, buf, {.traversalLimitInWords = std::numeric_limits<uint64_t>::max()}
);
auto request = buf.getRoot<build::Request>().asReader();
printDebugLogs = request.getDebug();
{
sigset_t set;
sigemptyset(&set);
if (sigprocmask(SIG_SETMASK, &set, nullptr)) {
throw SysError("failed to unmask signals");
}
}
/* Put the child in a separate session (and thus a separate
process group) so that it has no controlling terminal (meaning
that e.g. ssh cannot open /dev/tty) and it doesn't receive
terminal signals. */
if (setsid() == -1) {
throw SysError("creating a new session");
}
/* Dup stderr to stdout. */
if (dup2(STDERR_FILENO, STDOUT_FILENO) == -1) {
throw SysError("cannot dup stderr into stdout");
}
const bool setUser = prepareChildSetup(request);
// NOLINTNEXTLINE(lix-unsafe-c-calls): we trust the parent here
if (chdir(rpc::to<std::string>(request.getWorkingDir()).c_str()) == -1) {
throw SysError("changing into %s", rpc::to<std::string>(request.getWorkingDir()));
}
/* Disable core dumps by default. */
struct rlimit limit = {0, RLIM_INFINITY};
if (request.getEnableCoreDumps()) {
limit.rlim_cur = RLIM_INFINITY;
}
setrlimit(RLIMIT_CORE, &limit);
// FIXME: set other limits to deterministic values?
/* If we are running in `build-users' mode, then switch to the
user we allocated above. Make sure that we drop all root
privileges. Note that above we have closed all file
descriptors except std*, so that's safe. Also note that
setuid() when run as root sets the real, effective and
saved UIDs. */
if (setUser && request.hasCredentials()) {
auto creds = request.getCredentials();
/* Preserve supplementary groups of the build user, to allow
admins to specify groups such as "kvm". */
std::vector<gid_t> gids;
std::copy(
creds.getSupplementaryGroups().begin(),
creds.getSupplementaryGroups().end(),
std::back_inserter(gids)
);
if (setgroups(gids.size(), gids.data()) == -1) {
throw SysError("cannot set supplementary groups of build user");
}
if (setgid(creds.getGid()) == -1 || getgid() != creds.getGid() || getegid() != creds.getGid()) {
throw SysError("setgid failed");
}
if (setuid(creds.getUid()) == -1 || getuid() != creds.getUid() || geteuid() != creds.getUid()) {
throw SysError("setuid failed");
}
}
finishChildSetup(request);
/* Close all other file descriptors. */
closeExtraFDs();
// Reroute stdin to /dev/null. closing the setup socket fd also signals
// successful setup of the builder, all other errors must go to stderr.
kj::AutoCloseFd fdDevNull{open("/dev/null", O_RDWR | O_CLOEXEC)};
if (fdDevNull == nullptr) {
throw SysError("cannot open /dev/null");
}
if (dup2(fdDevNull.get(), STDIN_FILENO) == -1) {
throw SysError("cannot dup null device into stdin");
}
sendException = false;
execBuilder(request);
} catch (std::exception & e) { // NOLINT(lix-foreign-exceptions)
if (sendException) {
capnp::MallocMessageBuilder builder;
auto error = builder.getRoot<build::SetupResponse>();
RPC_FILL(error, setFatalError, e.what());
capnp::writeMessageToFd(STDIN_FILENO, builder);
} else {
writeFull(STDERR_FILENO, e.what());
}
return 1;
}
}
+79
View File
@@ -0,0 +1,79 @@
#pragma once
///@file
#include "lix/libstore/build/request.capnp.h"
#include "lix/libutil/rpc.hh"
#include <boost/format.hpp>
#include <capnp/message.h>
#include <capnp/serialize.h>
#include <cstring>
#include <exception>
#include <memory>
#include <string>
#include <string_view>
#include <unistd.h>
#include <vector>
namespace nix {
bool prepareChildSetup(nix::build::Request::Reader request);
void finishChildSetup(nix::build::Request::Reader request);
[[noreturn]]
void execBuilder(nix::build::Request::Reader request);
// silence the foreign exception lint for this helper
class BaseException : public std::exception
{};
class SysError : public BaseException
{
private:
std::shared_ptr<std::string> msg;
public:
explicit SysError(auto fmt, const auto &... args) : SysError(errno, fmt, args...) {}
SysError(int error, auto fmt, const auto &... args)
{
const auto errstr = strerror(error);
auto format = boost::format(fmt);
((format % args), ...);
msg = std::make_shared<std::string>(format.str() + ": " + errstr);
}
const char * what() const noexcept override
{
return msg->c_str();
}
};
struct ExecRequest
{
std::string builder;
std::vector<std::string> argsStorage, envsStorage;
std::vector<char *> args, envs;
ExecRequest(nix::build::Request::Reader request);
};
void writeFull(int fd, std::string_view data);
extern bool printDebugLogs;
inline void printDebugLog(auto fmt, const auto &... args)
{
auto format = boost::format(fmt);
((format % args), ...);
capnp::MallocMessageBuilder builder;
auto log = builder.getRoot<build::SetupResponse>();
RPC_FILL(log, setLogLine, format.str());
capnp::writeMessageToFd(STDIN_FILENO, builder);
}
#define debug(msg, ...) \
do { \
if (::nix::printDebugLogs) { \
printDebugLog(msg, __VA_ARGS__); \
} \
} while (0)
}
+66
View File
@@ -0,0 +1,66 @@
if is_linux
check_namespace_support = executable(
'check-namespace-support',
files('check-namespace-support.cc'),
install : true,
install_dir : libexecdir / 'lix',
)
endif
kill_user = executable(
'kill-user',
files('kill-user.cc'),
install : true,
install_dir : libexecdir / 'lix',
)
if is_linux
launch_builder_impl = 'linux'
elif is_darwin
launch_builder_impl = 'darwin'
else
launch_builder_impl = 'fallback'
endif
launch_builder = executable(
'launch-builder',
files(
'launch-builder.cc',
f'launch-builder-@launch_builder_impl@.cc',
),
liblix_generated_headers,
include_directories : [ '../..' ],
dependencies : [
capnp,
],
install : true,
install_dir : libexecdir / 'lix',
)
run_build_hook = executable(
'run-build-hook',
files('run-build-hook.cc'),
install : true,
install_dir : libexecdir / 'lix',
)
run_diff_hook = executable(
'run-diff-hook',
files('run-diff-hook.cc'),
install : true,
install_dir : libexecdir / 'lix',
)
run_pager = executable(
'run-pager',
files('run-pager.cc'),
install : true,
install_dir : libexecdir / 'lix',
)
unix_bind_connect = executable(
'unix-bind-connect',
files('unix-bind-connect.cc'),
install : true,
install_dir : libexecdir / 'lix',
)
+17
View File
@@ -0,0 +1,17 @@
#include "common.hh"
#include <unistd.h>
LIBEXEC_HELPER(2)
int helperMain(const char * name, std::span<char *> args) noexcept
{
DIE_UNLESS_SYS("chdir", chdir("/"));
DIE_UNLESS_SYS("setsid", setsid());
static_assert(STDIN_FILENO == 0);
DIE_UNLESS_SYS("close(stdin)", close(STDIN_FILENO));
DIE_UNLESS_SYS("stdin = open(/dev/null)", open("/dev/null", O_RDWR));
execv(args[0], args.subspan(1).data());
die("exec failed");
}
+27
View File
@@ -0,0 +1,27 @@
#include "common.hh"
#include <grp.h>
using std::literals::operator""sv;
LIBEXEC_HELPER(3)
int helperMain(const char * name, std::span<char *> args) noexcept
{
const auto uid = args[0];
const auto gid = args[1];
const auto hook = args.subspan(2);
DIE_UNLESS_SYS("chdir", chdir("/"));
if (gid != "-"sv) {
DIE_UNLESS_SYS("setgid", setgid(argToInt<gid_t>("gid", gid)));
/* Drop all other groups if we're setgid. */
DIE_UNLESS_SYS("setgroups", setgroups(0, 0));
}
if (uid != "-"sv) {
DIE_UNLESS_SYS("setuid", setuid(argToInt<uid_t>("uid", uid)));
}
execvp(hook[0], hook.data());
die("exec failed");
}
+19
View File
@@ -0,0 +1,19 @@
#include "common.hh"
LIBEXEC_HELPER(0)
int helperMain(const char * name, std::span<char *> args) noexcept
{
auto pager = args.empty() ? nullptr : args[0];
if (!getenv("LESS")) {
setenv("LESS", "FRSXMK", 1);
}
if (pager) {
execl("/bin/sh", "sh", "-c", pager, nullptr);
}
execlp("pager", "pager", nullptr);
execlp("less", "less", nullptr);
execlp("more", "more", nullptr);
die("could not find a pager to run, please set PAGER or NIX_PAGER");
}
+34
View File
@@ -0,0 +1,34 @@
#include "common.hh"
#include <sys/socket.h>
#include <sys/un.h>
LIBEXEC_HELPER(4)
int helperMain(const char *, std::span<char *> args) noexcept
{
int socket = argToInt<int>("socket", args[0]);
std::string_view method = args[1];
const auto dir = args[2];
const auto name = args[3];
DIE_UNLESS_SYS("chdir", chdir(dir));
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
if (auto nameLen = strlen(name); nameLen + 1 >= sizeof(addr.sun_path)) {
die(std::format("socket path {}/{} is too long", dir, name));
} else {
memcpy(addr.sun_path, name, nameLen + 1);
}
if (method == "bind") {
DIE_UNLESS_SYS("bind", bind(socket, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)));
} else if (method == "connect") {
DIE_UNLESS_SYS("connect", connect(socket, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)));
} else {
die(std::format("invalid method %s", method));
}
return 0;
}
+1 -3
View File
@@ -83,9 +83,7 @@ findAlongAttrPath(EvalState & state, const std::string & attrPath, Bindings & au
auto attrIndex = string2Int<unsigned int>(attr);
/* Evaluate the expression. */
Value vNew;
state.autoCallFunction(autoArgs, v, vNew, pos);
v = vNew;
v = state.autoCallFunction(autoArgs, v, pos);
state.forceValue(v, noPos);
/* It should evaluate to either a set or an expression,
-9
View File
@@ -41,13 +41,4 @@ void Bindings::sort()
{
if (size_) std::sort(begin(), end());
}
Value & Value::mkAttrs(BindingsBuilder & bindings)
{
mkAttrs(bindings.finish());
return *this;
}
}
+1 -3
View File
@@ -121,7 +121,6 @@ public:
private:
Bindings * bindings;
EvalMemory & mem;
SymbolTable & symbols;
Size capacity;
@@ -129,9 +128,8 @@ public:
// needed by std::back_inserter
using value_type = Attr;
BindingsBuilder(EvalMemory & mem, SymbolTable & symbols, Bindings * bindings, Size capacity)
BindingsBuilder(SymbolTable & symbols, Bindings * bindings, Size capacity)
: bindings(bindings)
, mem(mem)
, symbols(symbols)
, capacity(capacity)
{
+1 -1
View File
@@ -42,7 +42,7 @@ struct AttrDb
Path cacheDir = getCacheDir() + "/nix/eval-cache-v5";
createDirs(cacheDir);
Path dbPath = cacheDir + "/" + fingerprint.to_string(Base::Base16, false) + ".sqlite";
Path dbPath = cacheDir + "/" + fingerprint.to_string(HashFormat::Base16, false) + ".sqlite";
state->db = SQLite(dbPath);
state->db.isCache();
+728
View File
@@ -0,0 +1,728 @@
#include "eval.hh"
#include "primops.hh"
#include "gc-small-vector.hh"
/// This file contains all implementations of `Expr::eval`, and some other helper functions defined by
/// `Expr` subtypes. Note that some of the evaluation helper functions on `EvalState` that do the heavy
/// lifting are not in this file but kept in `eval.cc`. In the future, more logic from here will be factored
/// out into helpers over at `eval.cc` until this file contains a readable and high-level implementation of
/// the evaluator.
namespace nix {
/* Create a thunk for the delayed computation of the given expression
in the given environment. But if the expression is a variable,
then look it up right away. This significantly reduces the number
of thunks allocated. */
Value Expr::maybeThunk(EvalState & state, Env & env)
{
state.ctx.stats.nrThunks++;
return {NewValueAs::thunk, state.ctx.mem, env, *this};
}
Value ExprVar::maybeThunk(EvalState & state, Env & env)
{
Value * v = state.lookupVar(&env, *this, true);
/* The value might not be initialised in the environment yet.
In that case, ignore it. */
if (v && !v->isInvalid()) {
state.ctx.stats.nrAvoided++;
return *v;
}
return Expr::maybeThunk(state, env);
}
Value ExprLiteral::maybeThunk(EvalState & state, Env & env)
{
state.ctx.stats.nrAvoided++;
return v;
}
Value ExprList::maybeThunk(EvalState & state, Env & env)
{
if (elems.empty()) {
return Value::EMPTY_LIST;
}
return Expr::maybeThunk(state, env);
}
Value Expr::eval(EvalState & state, Env & env)
{
abort();
}
Value ExprLiteral::eval(EvalState & state, Env & env)
{
return this->v;
}
Value ExprInheritFrom::eval(EvalState & state, Env & env)
{
Value & v2 = env.values[displ];
state.forceValue(v2, pos);
return v2;
}
Env * ExprAttrs::buildInheritFromEnv(EvalState & state, Env & up)
{
Env & inheritEnv = state.ctx.mem.allocEnv(inheritFromExprs->size());
inheritEnv.up = &up;
Displacement displ = 0;
for (auto & from : *inheritFromExprs) {
inheritEnv.values[displ++] = from->maybeThunk(state, up);
}
return &inheritEnv;
}
Value ExprSet::eval(EvalState & state, Env & env)
{
Bindings::Size capacity = attrs.size() + dynamicAttrs.size();
Value v = {NewValueAs::attrs, state.ctx.buildBindings(capacity).finish()};
auto dynamicEnv = &env;
if (recursive) {
/* Create a new environment that contains the attributes in
this `rec'. */
Env & env2(state.ctx.mem.allocEnv(attrs.size()));
env2.up = &env;
dynamicEnv = &env2;
Env * inheritEnv = inheritFromExprs ? buildInheritFromEnv(state, env2) : nullptr;
ExprAttrs::AttrDefs::iterator overrides = attrs.find(state.ctx.symbols.sym___overrides);
bool hasOverrides = overrides != attrs.end();
/* The recursive attributes are evaluated in the new
environment, while the inherited attributes are evaluated
in the original environment. */
Displacement displ = 0;
for (auto & i : attrs) {
Value vAttr;
if (hasOverrides && i.second.kind != ExprAttrs::AttrDef::Kind::Inherited) {
vAttr = {
NewValueAs::thunk,
state.ctx.mem,
*i.second.chooseByKind(&env2, &env, inheritEnv),
*i.second.e
};
state.ctx.stats.nrThunks++;
} else {
vAttr = i.second.e->maybeThunk(state, *i.second.chooseByKind(&env2, &env, inheritEnv));
}
env2.values[displ++] = vAttr;
v.attrs()->push_back(Attr(i.first, vAttr, i.second.pos));
}
/* If the rec contains an attribute called `__overrides', then
evaluate it, and add the attributes in that set to the rec.
This allows overriding of recursive attributes, which is
otherwise not possible. (You can use the // operator to
replace an attribute, but other attributes in the rec will
still reference the original value, because that value has
been substituted into the bodies of the other attributes.
Hence we need __overrides.) */
if (hasOverrides) {
Value & vOverrides = (*v.attrs())[overrides->second.displ].value;
state.forceAttrs(vOverrides, noPos, "while evaluating the `__overrides` attribute");
Bindings * newBnds = state.ctx.mem.allocBindings(capacity + vOverrides.attrs()->size());
for (auto & i : *v.attrs()) {
newBnds->push_back(i);
}
for (auto & i : *vOverrides.attrs()) {
ExprAttrs::AttrDefs::iterator j = attrs.find(i.name);
if (j != attrs.end()) {
(*newBnds)[j->second.displ] = i;
env2.values[j->second.displ] = i.value;
} else {
newBnds->push_back(i);
}
}
newBnds->sort();
v = {NewValueAs::attrs, newBnds};
}
}
else {
Env * inheritEnv = inheritFromExprs ? buildInheritFromEnv(state, env) : nullptr;
for (auto & i : attrs) {
v.attrs()->push_back(Attr(
i.first,
i.second.e->maybeThunk(state, *i.second.chooseByKind(&env, &env, inheritEnv)),
i.second.pos
));
}
}
/* Dynamic attrs apply *after* rec and __overrides. */
for (auto & i : dynamicAttrs) {
/* Before evaluating dynamic attrs, we blackhole the output attrset and only restore it after the operation.
* This is to avoid exposing the partially constructed set as a value, see
* http://github.com/NixOS/nix/issues/7012. Any accesses to the output attrset will thus infrec.
*/
Value vBackup = v;
Value nameVal;
{
KJ_DEFER(v = vBackup);
v = Value{NewValueAs::blackhole};
nameVal = i.nameExpr->eval(state, *dynamicEnv);
state.forceValue(nameVal, i.pos);
if (nameVal.type() == nNull) {
continue;
}
state.forceStringNoCtx(nameVal, i.pos, "while evaluating the name of a dynamic attribute");
}
auto nameSym = state.ctx.symbols.create(nameVal.str());
auto j = v.attrs()->get(nameSym);
if (j) {
state.ctx.errors
.make<EvalError>(
"dynamic attribute '%1%' already defined at %2%",
state.ctx.symbols[nameSym],
state.ctx.positions[j->pos]
)
.atPos(i.pos)
.withFrame(env, *this)
.debugThrow();
}
i.valueExpr->setName(nameSym);
/* Keep sorted order so find can catch duplicates */
v.attrs()->push_back(Attr(nameSym, i.valueExpr->maybeThunk(state, *dynamicEnv), i.pos));
v.attrs()->sort(); // FIXME: inefficient
}
v.attrs()->pos = pos;
return v;
}
Value ExprLet::eval(EvalState & state, Env & env)
{
/* Create a new environment that contains the attributes in this
`let'. */
Env & env2(state.ctx.mem.allocEnv(attrs.size()));
env2.up = &env;
Env * inheritEnv = inheritFromExprs ? buildInheritFromEnv(state, env2) : nullptr;
/* The recursive attributes are evaluated in the new environment,
while the inherited attributes are evaluated in the original
environment. */
Displacement displ = 0;
for (auto & i : attrs) {
env2.values[displ++] = i.second.e->maybeThunk(state, *i.second.chooseByKind(&env2, &env, inheritEnv));
}
return body->eval(state, env2);
}
Value ExprList::eval(EvalState & state, Env & env)
{
auto result = state.ctx.mem.newList(elems.size());
Value v = {NewValueAs::list, result};
for (auto && [n, v2] : enumerate(result->span())) {
v2 = elems[n]->maybeThunk(state, env);
}
return v;
}
Value ExprVar::eval(EvalState & state, Env & env)
{
Value * v2 = state.lookupVar(&env, *this, false);
try {
state.forceValue(*v2, pos);
} catch (Error & e) {
/* `name` can be invalid if we are an ExprInheritFrom */
if (name) {
e.addTrace(state.ctx.positions[getPos()], "while evaluating %s", state.ctx.symbols[name]);
}
throw;
}
return *v2;
}
Value ExprWith::eval(EvalState & state, Env & env)
{
Env & env2(state.ctx.mem.allocEnv(1));
env2.up = &env;
env2.values[0] = attrs->maybeThunk(state, env);
return body->eval(state, env2);
}
Value ExprIf::eval(EvalState & state, Env & env)
{
Value vCond = cond->eval(state, env);
return (state.checkBool(vCond, env, *cond) ? *then : *else_).eval(state, env);
}
Value ExprAssert::eval(EvalState & state, Env & env)
{
Value vCond = cond->eval(state, env);
if (!state.checkBool(vCond, env, *cond)) {
state.ctx.errors.make<AssertionError>("assertion failed")
.atPos(pos)
.withFrame(env, *this)
.debugThrow();
}
return body->eval(state, env);
}
Value ExprOpNot::eval(EvalState & state, Env & env)
{
Value vInner = e->eval(state, env);
return {NewValueAs::boolean, !state.checkBool(vInner, env, *e)};
}
Value ExprOpEq::eval(EvalState & state, Env & env)
{
Value v1 = e1->eval(state, env);
Value v2 = e2->eval(state, env);
return {NewValueAs::boolean, state.eqValues(v1, v2, pos, "while testing two values for equality")};
}
Value ExprOpNEq::eval(EvalState & state, Env & env)
{
Value v1 = e1->eval(state, env);
Value v2 = e2->eval(state, env);
return {NewValueAs::boolean, !state.eqValues(v1, v2, pos, "while testing two values for inequality")};
}
Value ExprOpAnd::eval(EvalState & state, Env & env)
{
Value v1 = e1->eval(state, env);
/* Explicitly short-circuit */
if (!state.checkBool(v1, env, *e1)) {
return {NewValueAs::boolean, false};
}
Value v2 = e2->eval(state, env);
return {NewValueAs::boolean, state.checkBool(v2, env, *e2)};
}
Value ExprOpOr::eval(EvalState & state, Env & env)
{
Value v1 = e1->eval(state, env);
/* Explicitly short-circuit */
if (state.checkBool(v1, env, *e1)) {
return {NewValueAs::boolean, true};
}
Value v2 = e2->eval(state, env);
return {NewValueAs::boolean, state.checkBool(v2, env, *e2)};
}
Value ExprOpImpl::eval(EvalState & state, Env & env)
{
Value v1 = e1->eval(state, env);
/* Explicitly short-circuit (ex falso quodlibet) */
if (!state.checkBool(v1, env, *e1)) {
return {NewValueAs::boolean, true};
}
Value v2 = e2->eval(state, env);
return {NewValueAs::boolean, state.checkBool(v2, env, *e2)};
}
Value ExprOpUpdate::eval(EvalState & state, Env & env)
{
Value v1 = e1->eval(state, env);
state.checkAttrs(v1, env, *e1);
Value v2 = e2->eval(state, env);
state.checkAttrs(v2, env, *e2);
state.ctx.stats.nrOpUpdates++;
if (v1.attrs()->size() == 0) {
return v2;
}
if (v2.attrs()->size() == 0) {
return v1;
}
auto attrs = state.ctx.buildBindings(v1.attrs()->size() + v2.attrs()->size());
/* Merge the sets, preferring values from the second set. Make
sure to keep the resulting vector in sorted order. */
Bindings::iterator i = v1.attrs()->begin();
Bindings::iterator j = v2.attrs()->begin();
while (i != v1.attrs()->end() && j != v2.attrs()->end()) {
if (i->name == j->name) {
attrs.insert(*j);
++i;
++j;
} else if (i->name < j->name) {
attrs.insert(*i++);
} else {
attrs.insert(*j++);
}
}
while (i != v1.attrs()->end()) {
attrs.insert(*i++);
}
while (j != v2.attrs()->end()) {
attrs.insert(*j++);
}
Value v = {NewValueAs::attrs, attrs.alreadySorted()};
state.ctx.stats.nrOpUpdateValuesCopied += v.attrs()->size();
return v;
}
Value ExprOpConcatLists::eval(EvalState & state, Env & env)
{
state.ctx.stats.nrListConcats++;
/* We don't call into `concatLists` as that loses the position information of the expressions. */
Value v1 = e1->eval(state, env);
state.checkList(v1, env, *e1);
Value v2 = e2->eval(state, env);
state.checkList(v2, env, *e2);
size_t l1 = v1.listSize(), l2 = v2.listSize(), len = l1 + l2;
if (l1 == 0) {
return v2;
} else if (l2 == 0) {
return v1;
} else {
auto list = state.ctx.mem.newList(len);
auto out = list->elems;
std::copy(v1.listElems(), v1.listElems() + l1, out);
std::copy(v2.listElems(), v2.listElems() + l2, out + l1);
return {NewValueAs::list, list};
}
}
Value ExprConcatStrings::eval(EvalState & state, Env & env)
{
NixStringContext context;
std::vector<BackedStringView> s;
size_t sSize = 0;
NixInt n{0};
NixFloat nf = 0;
bool first = !isInterpolation;
ValueType firstType = nString;
const auto str = [&] {
std::string result;
result.reserve(sSize);
for (const auto & part : s) {
result += *part;
}
return result;
};
/* build a gc'd value string directly instead of going through str()
and mkString to save an allocation and copy */
const auto gcStr = [&] {
auto result = Value::Str::gcAlloc(sSize);
char * tmp = result->contents;
for (const auto & part : s) {
memcpy(tmp, part->data(), part->size());
tmp += part->size();
}
return result;
};
// List of returned strings. References to these Values must NOT be persisted.
SmallTemporaryValueVector<conservativeStackReservation> values(es.size());
Value * vTmpP = values.data();
for (auto & [i_pos, i] : es) {
Value & vTmp = *vTmpP++;
vTmp = i->eval(state, env);
/* If the first element is a path, then the result will also
be a path, we don't copy anything (yet - that's done later,
since paths are copied when they are used in a derivation),
and none of the strings are allowed to have contexts. */
if (first) {
firstType = vTmp.type();
}
if (firstType == nInt) {
if (vTmp.type() == nInt) {
auto newN = n + vTmp.integer();
if (auto checked = newN.valueChecked(); checked.has_value()) {
n = NixInt(*checked);
} else {
state.ctx.errors
.make<EvalError>("integer overflow in adding %1% + %2%", n, vTmp.integer())
.atPos(i_pos)
.debugThrow();
}
} else if (vTmp.type() == nFloat) {
// Upgrade the type from int to float;
firstType = nFloat;
nf = n.value;
nf += vTmp.fpoint();
} else {
state.ctx.errors.make<EvalError>("cannot add %1% to an integer", showType(vTmp))
.atPos(i_pos)
.withFrame(env, *this)
.debugThrow();
}
} else if (firstType == nFloat) {
if (vTmp.type() == nInt) {
nf += vTmp.integer().value;
} else if (vTmp.type() == nFloat) {
nf += vTmp.fpoint();
} else {
state.ctx.errors.make<EvalError>("cannot add %1% to a float", showType(vTmp))
.atPos(i_pos)
.withFrame(env, *this)
.debugThrow();
}
} else {
if (s.empty()) {
s.reserve(es.size());
}
/* If we are coercing inside of an interpolation, we may allow slightly more comfort by coercing
* things like integers. */
auto coercionMode = isInterpolation && featureSettings.isEnabled(Xp::CoerceIntegers)
? StringCoercionMode::Interpolation
: StringCoercionMode::Strict;
/* skip canonization of first path, which would only be not
canonized in the first place if it's coming from a ./${foo} type
path */
auto part = state.coerceToString(
i_pos,
vTmp,
context,
"while evaluating a path segment",
coercionMode,
firstType == nString,
!first
);
sSize += part->size();
s.emplace_back(std::move(part));
}
first = false;
}
if (firstType == nInt) {
return {NewValueAs::integer, n};
} else if (firstType == nFloat) {
return {NewValueAs::floating, nf};
} else if (firstType == nPath) {
if (!context.empty()) {
state.ctx.errors
.make<EvalError>("a string that refers to a store path cannot be appended to a path")
.atPos(pos)
.withFrame(env, *this)
.debugThrow();
}
return {NewValueAs::path, CanonPath(canonPath(str()))};
} else {
return {NewValueAs::string, gcStr(), context};
}
}
Value ExprPos::eval(EvalState & state, Env & env)
{
Value v;
state.mkPos(v, pos);
return v;
}
Value ExprBlackHole::eval(EvalState & state, Env & env)
{
state.ctx.errors.make<InfiniteRecursionError>("infinite recursion encountered").debugThrow();
}
Value ExprDebugFrame::eval(EvalState & state, Env & env)
{
auto dts = makeDebugTraceStacker(state, *inner, env, state.ctx.positions[pos], message);
return inner->eval(state, env);
}
/** Returns `nullptr` if we should be using a default instead. */
Attr const *
ExprSelect::selectSingleAttr(EvalState & state, Env & env, AttrName const & attrName, Value & vCurrent)
{
Symbol const attrSym = getName(attrName, state, env);
try {
state.forceValue(vCurrent, pos);
} catch (Error & e) {
// clang-format off
e.addTrace(state.ctx.positions[attrName.pos], HintFmt(
"while evaluating an expression to select '%s' on it", state.ctx.symbols[attrSym]
));
// clang-format on
throw;
}
if (vCurrent.type() != nAttrs) {
// If we have an `or` provided default, then it doesn't have to be an attrset.
// Let the caller know there's no attr value here.
if (def != nullptr) {
return nullptr;
}
// Otherwise, we must type error.
// clang-format off
state.ctx.errors.make<TypeError>(
"expected a set but found %s: %s",
showType(vCurrent),
ValuePrinter(state, vCurrent, errorPrintOptions)
).addTrace(
attrName.pos,
HintFmt("while selecting '%s'", state.ctx.symbols[attrSym])
).debugThrow();
// clang-format on
}
// Now that we know it's an attrset, we can actually look for the name.
auto const attrIt = vCurrent.attrs()->get(attrSym);
if (!attrIt) {
// Again if we have an `or` provided default, then missing attr is not an error.
if (def != nullptr) {
return nullptr;
}
// Otherwise, we collect all attr names and throw an attr missing error.
std::set<std::string> const allAttrNames = *vCurrent.attrs()
| std::views::transform([&state](auto const & attr) {
return std::string{state.ctx.symbols[attr.name]};
})
| std::ranges::to<std::set>();
auto suggestions = Suggestions::bestMatches(allAttrNames, state.ctx.symbols[attrSym]);
state.ctx.errors.make<EvalError>("attribute '%s' missing", state.ctx.symbols[attrSym])
.atPos(attrName.pos)
.withSuggestions(suggestions)
.withFrame(env, *this)
.debugThrow();
}
// If we made it here, then we successfully found the attribute.
// Return it to our caller!
return attrIt;
}
Value ExprSelect::eval(EvalState & state, Env & env)
{
// Position for the current attrset Value in this select chain.
PosIdx posCurrent;
// Position for the current selector in this select chain.
PosIdx posCurrentSyntax;
Value baseSelectee;
try {
// Evaluate the original thing we're selecting on.
baseSelectee = e->eval(state, env);
} catch (Error & e) {
// clang-format off
e.addTrace(state.ctx.positions[getPos()], HintFmt(
"while evaluating an expression to select '%s' on it",
showAttrPath(state.ctx.symbols, attrPath)
));
// clang-format on
throw;
}
try {
// With the original selectee evaluated, we'll walk the selection path starting
// with the evaluated original selectee.
std::reference_wrapper<Value> curSelectee = std::ref(baseSelectee);
for (AttrName const & attrName : attrPath) {
state.ctx.stats.nrLookups++;
// Select `attrName` on `curSelectee`.
auto const attr = selectSingleAttr(state, env, attrName, curSelectee.get());
if (!attr) {
// Use default.
try {
return this->def->eval(state, env);
} catch (Error & err) {
err.addTrace(
state.ctx.positions[this->def->pos],
"while evaluating fallback for missing attribute '%s'",
state.ctx.symbols[getName(attrName, state, env)]
);
throw;
}
}
// The selection worked. If we have another iteration, then we use `attr->value`
// as the thing to select on. If this is the last iteration, then `attr->value`
// is the final value this ExprSelect evaluated to.
curSelectee = std::ref(attr->value);
posCurrent = attr->pos;
posCurrentSyntax = attrName.pos;
if (state.ctx.stats.countCalls) {
state.ctx.stats.attrSelects[posCurrent]++;
}
}
state.forceValue(curSelectee.get(), posCurrent ? posCurrent : posCurrentSyntax);
return curSelectee.get();
} catch (Error & err) {
auto const & lastPos = state.ctx.positions[posCurrent];
if (lastPos && !std::get_if<Pos::Hidden>(&lastPos.origin)) {
err.addTrace(lastPos, "while evaluating the attribute '%s'", showAttrPath(state, env, attrPath));
}
throw;
}
}
Value ExprOpHasAttr::eval(EvalState & state, Env & env)
{
Value vTmp = e->eval(state, env);
Value * vAttrs = &vTmp;
for (auto & i : attrPath) {
state.forceValue(*vAttrs, getPos());
const Attr * j;
auto name = getName(i, state, env);
if (vAttrs->type() != nAttrs || (j = vAttrs->attrs()->get(name)) == nullptr) {
return {NewValueAs::boolean, false};
} else {
vAttrs = &j->value;
}
}
return {NewValueAs::boolean, true};
}
Value ExprLambda::eval(EvalState & state, Env & env)
{
return {NewValueAs::lambda, state.ctx.mem, env, *this};
}
Value ExprCall::eval(EvalState & state, Env & env)
{
Value vFun = fun->eval(state, env);
// Empirical arity of Nixpkgs lambdas by regex e.g. ([a-zA-Z]+:(\s|(/\*.*\/)|(#.*\n))*){5}
// 2: over 4000
// 3: about 300
// 4: about 60
// 5: under 10
// This excluded attrset lambdas (`{...}:`). Contributions of mixed lambdas appears insignificant at ~150
// total.
SmallValueVector<4> vArgs(args.size());
for (size_t i = 0; i < args.size(); ++i) {
vArgs[i] = args[i]->maybeThunk(state, env);
}
return state.callFunction(vFun, vArgs, pos);
}
}
+145 -20
View File
@@ -20,11 +20,21 @@ inline Value::Value(app_t, EvalMemory & mem, Value & lhs, Value & rhs)
}
inline Value::Value(app_t, EvalMemory & mem, Value & lhs, std::span<Value> args)
: Value(app_t{}, mem, lhs, args, {})
{
auto app = static_cast<Value::App *>(mem.allocBytes(sizeof(Value::App) + args.size_bytes()));
}
inline Value::Value(
app_t, EvalMemory & mem, const Value & lhs, std::span<Value> baseArgs, std::span<Value> moreArgs
)
{
auto app = static_cast<Value::App *>(
mem.allocBytes(sizeof(Value::App) + baseArgs.size_bytes() + moreArgs.size_bytes())
);
app->_left = lhs;
app->_n = args.size();
std::copy(args.begin(), args.end(), app->_args);
app->_n = baseArgs.size() + moreArgs.size();
std::copy(baseArgs.begin(), baseArgs.end(), app->_args);
std::copy(moreArgs.begin(), moreArgs.end(), app->_args + baseArgs.size());
raw = tag(tApp, app);
}
@@ -100,6 +110,85 @@ Env & EvalMemory::allocEnv(size_t size)
return *env;
}
/* The overloaded versions of `checkType` exist because of non-unified error handling
* The variant which takes an Expression is required because of debug frames (`withFrames`).
* Ideally, at some point in the future, we'd implement debug frames that are not tied to the expression and
* env and then unify both `checkType` functions into one. Then the argument forwarding overloading hack done
* for the other functions below will be removable again.
*/
[[gnu::always_inline]]
void EvalState::checkType(Value & v, ValueType vType, Env & env, Expr & e)
{
if (v.type() != vType) {
ctx.errors
.make<TypeError>(
"expected %1% but found %2%: %3%",
Uncolored(vType),
showType(v),
ValuePrinter(*this, v, errorPrintOptions)
)
.atPos(e.getPos())
.withFrame(env, e)
.debugThrow();
}
}
[[gnu::always_inline]]
void EvalState::checkType(Value & v, ValueType vType)
{
if (v.type() != vType) {
ctx.errors
.make<TypeError>(
"expected %1% but found %2%: %3%",
Uncolored(vType),
showType(v),
ValuePrinter(*this, v, errorPrintOptions)
)
.debugThrow();
}
}
template<typename... Args>
[[gnu::always_inline]]
bool EvalState::checkBool(Value & v, Args &&... errorArgs)
{
checkType(v, nBool, std::forward<Args>(errorArgs)...);
return v.boolean();
}
template<typename... Args>
[[gnu::always_inline]]
NixInt EvalState::checkInt(Value & v, Args &&... errorArgs)
{
checkType(v, nInt, std::forward<Args>(errorArgs)...);
return v.integer();
}
template<typename... Args>
[[gnu::always_inline]]
NixFloat EvalState::checkFloat(Value & v, Args &&... errorArgs)
{
if (v.type() == nInt) {
return v.integer().value;
}
checkType(v, nFloat, std::forward<Args>(errorArgs)...);
return v.fpoint();
}
template<typename... Args>
[[gnu::always_inline]]
void EvalState::checkList(Value & v, Args &&... errorArgs)
{
checkType(v, nList, std::forward<Args>(errorArgs)...);
}
template<typename... Args>
[[gnu::always_inline]]
Bindings * EvalState::checkAttrs(Value & v, Args &&... errorArgs)
{
checkType(v, nAttrs, std::forward<Args>(errorArgs)...);
return v.attrs();
}
[[gnu::always_inline]]
void EvalState::forceValue(Value & v, const PosIdx pos)
@@ -114,7 +203,7 @@ void EvalState::forceValue(Value & v, const PosIdx pos)
Expr & expr = *thunk.expr;
thunk = Value::blackHole;
try {
expr.eval(*this, *env, v);
v = expr.eval(*this, *env);
thunk.resolve(v);
} catch (...) {
thunk = backup;
@@ -130,7 +219,7 @@ void EvalState::forceValue(Value & v, const PosIdx pos)
auto target = app.target();
if (!target.isPrimOp() || target.primOp()->arity <= app.totalArgs()) {
auto tmp = v.app().left();
callFunction(tmp, v.app().args(), v, pos);
v = callFunction(tmp, v.app().args(), pos);
app.resolve(v);
}
}
@@ -138,15 +227,14 @@ void EvalState::forceValue(Value & v, const PosIdx pos)
}
[[gnu::always_inline]]
inline void EvalState::forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx)
inline Bindings * EvalState::forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx)
{
forceValue(v, pos);
if (v.type() != nAttrs) {
ctx.errors.make<TypeError>(
"expected a set but found %1%: %2%",
showType(v),
ValuePrinter(*this, v, errorPrintOptions)
).withTrace(pos, errorCtx).debugThrow();
try {
forceValue(v, pos);
return checkAttrs(v);
} catch (Error & e) {
e.addTrace(ctx.positions[pos], errorCtx);
throw;
}
}
@@ -154,15 +242,52 @@ inline void EvalState::forceAttrs(Value & v, const PosIdx pos, std::string_view
[[gnu::always_inline]]
inline void EvalState::forceList(Value & v, const PosIdx pos, std::string_view errorCtx)
{
forceValue(v, pos);
if (!v.isList()) {
ctx.errors.make<TypeError>(
"expected a list but found %1%: %2%",
showType(v),
ValuePrinter(*this, v, errorPrintOptions)
).withTrace(pos, errorCtx).debugThrow();
try {
forceValue(v, pos);
checkList(v);
} catch (Error & e) {
e.addTrace(ctx.positions[pos], errorCtx);
throw;
}
}
inline Value * EvalState::lookupVar(Env * env, const ExprVar & var, bool noEval)
{
for (auto l = var.level; l; --l, env = env->up)
;
if (!var.fromWith) {
return &env->values[var.displ];
}
// This early exit defeats the `maybeThunk` optimization for variables from `with`,
// The added complexity of handling this appears to be similarly in cost, or
// the cases where applicable were insignificant in the first place.
if (noEval) {
return nullptr;
}
auto * fromWith = var.fromWith;
while (1) {
forceAttrs(
env->values[0], fromWith->pos, "while evaluating the first subexpression of a with expression"
);
auto j = env->values[0].attrs()->get(var.name);
if (j) {
if (ctx.stats.countCalls) {
ctx.stats.attrSelects[j->pos]++;
}
return &j->value;
}
if (!fromWith->parentWith) {
ctx.errors.make<UndefinedVarError>("undefined variable '%1%'", ctx.symbols[var.name])
.atPos(var.pos)
.withFrame(*env, var)
.debugThrow();
}
for (size_t l = fromWith->prevWith; l; --l, env = env->up)
;
fromWith = fromWith->parentWith;
}
}
}
-2
View File
@@ -95,8 +95,6 @@ const std::string & EvalSettings::getCurrentSystem()
EvalSettings evalSettings;
static GlobalConfig::Register rEvalSettings(&evalSettings);
Path getNixDefExpr()
{
return settings.useXDGBaseDirectories
+1 -1
View File
@@ -14,7 +14,7 @@ struct EvalSettings : Config
static std::string resolvePseudoUrl(std::string_view url);
#include "libexpr-settings.gen.inc"
#include "lix/libexpr/libexpr-settings.gen.inc"
/**
* Implements the `eval-system` vs `system` defaulting logic
+90 -931
View File
File diff suppressed because it is too large Load Diff
+46 -36
View File
@@ -80,6 +80,9 @@ void copyContext(const Value & v, NixStringContext & context);
std::string printValue(EvalState & state, Value & v);
std::ostream & operator << (std::ostream & os, const ValueType t);
Symbol getName(const AttrName & name, EvalState & state, Env & env);
std::string showAttrPath(EvalState & state, Env & env, const AttrPath & attrPath);
/**
* Initialise the evaluator (including Boehm GC, if applicable).
@@ -163,20 +166,6 @@ public:
}
};
struct StaticSymbols
{
const Symbol outPath, drvPath, type, meta, name, value, system, overrides, outputs, outputName,
ignoreNulls, file, line, column, functor, toString, right, wrong, structuredAttrs,
allowedReferences, allowedRequisites, disallowedReferences, disallowedRequisites, maxSize,
maxClosureSize, builder, args, contentAddressed, impure, outputHash, outputHashAlgo,
outputHashMode, recurseForDerivations, description, self, startSet, operator_, key,
path, prefix, outputSpecified;
const Expr::AstSymbols exprSymbols;
explicit StaticSymbols(SymbolTable & symbols);
};
class EvalMemory
{
static constexpr size_t CACHES = 8;
@@ -216,7 +205,7 @@ public:
BindingsBuilder buildBindings(SymbolTable & symbols, size_t capacity)
{
return BindingsBuilder(*this, symbols, allocBindings(capacity), capacity);
return BindingsBuilder(symbols, allocBindings(capacity), capacity);
}
const Statistics getStats() const { return stats; }
@@ -491,9 +480,8 @@ class Evaluator
EvalState * activeEval = nullptr;
public:
SymbolTable symbols;
NixSymbolTable symbols;
PosTable positions;
const StaticSymbols s;
EvalMemory mem;
EvalRuntimeCaches caches;
EvalPaths paths;
@@ -566,7 +554,7 @@ public:
/**
* Creates a thunk that will evaluate the given expression when forced.
*/
void evalLazily(Expr & e, Value & v);
Value evalLazily(Expr & e);
/** If debugging is enabled, returns the next trace. Otherwise, std::nullopt. */
std::optional<DebugTrace const *> nextDebugTrace() const;
@@ -658,24 +646,14 @@ public:
/**
* Evaluate an expression read from the given file to normal form.
*/
void evalFile(const SourcePath & path, Value & v);
Value evalFile(const SourcePath & path);
void resetFileCache();
/**
* Evaluate an expression to normal form
*
* @param [out] v The resulting is stored here.
*/
void eval(Expr & e, Value & v);
/**
* Evaluation the expression, then verify that it has the expected
* type.
*/
inline bool evalBool(Env & env, Expr & e);
inline void evalAttrs(Env & env, Expr & e, Value & v);
inline void evalList(Env & env, Expr & e, Value & v);
Value eval(Expr & e);
/**
* If `v` is a thunk, enter it and overwrite `v` with the result
@@ -700,7 +678,7 @@ public:
NixFloat forceFloat(Value & v, const PosIdx pos, std::string_view errorCtx);
bool forceBool(Value & v, const PosIdx pos, std::string_view errorCtx);
void forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx);
inline Bindings * forceAttrs(Value & v, const PosIdx pos, std::string_view errorCtx);
inline void forceList(Value & v, const PosIdx pos, std::string_view errorCtx);
/**
* @param v either lambda or primop
@@ -710,6 +688,19 @@ public:
std::string_view forceString(Value & v, NixStringContext & context, const PosIdx pos, std::string_view errorCtx);
std::string_view forceStringNoCtx(Value & v, const PosIdx pos, std::string_view errorCtx);
inline void checkType(Value & v, ValueType vType, Env & env, Expr & e);
inline void checkType(Value & v, ValueType vType);
template<typename... Args>
bool checkBool(Value & v, Args &&... errorArgs);
template<typename... Args>
NixInt checkInt(Value & v, Args &&... errorArgs);
template<typename... Args>
NixFloat checkFloat(Value & v, Args &&... errorArgs);
template<typename... Args>
void checkList(Value & v, Args &&... errorArgs);
template<typename... Args>
Bindings * checkAttrs(Value & v, Args &&... errorArgs);
/**
* Realise the given context, and return a mapping from the placeholders
* used to construct the associated value to their final store path
@@ -796,18 +787,18 @@ public:
bool isFunctor(Value & fun);
void callFunction(Value & fun, std::span<Value> args, Value & vRes, const PosIdx pos);
Value callFunction(Value & fun, std::span<Value> args, const PosIdx pos);
void callFunction(Value & fun, Value & arg, Value & vRes, const PosIdx pos)
Value callFunction(Value & fun, Value & arg, const PosIdx pos)
{
callFunction(fun, {&arg, 1}, vRes, pos);
return callFunction(fun, {&arg, 1}, pos);
}
/**
* Automatically call a function for which each argument has a
* default value or has a binding in the `args` map.
*/
void autoCallFunction(Bindings & args, Value & fun, Value & res, PosIdx pos);
Value autoCallFunction(Bindings & args, Value & fun, PosIdx pos);
void mkPos(Value & v, PosIdx pos);
@@ -871,7 +862,26 @@ std::string showType(const Value & v);
static constexpr std::string_view corepkgsPrefix{"/__corepkgs__/"};
// In C++, template functions need to be defined in the header :/
template<typename... Args>
DebugState::TraceFrame makeDebugTraceStacker(
EvalState & state, Expr & expr, Env & env, std::shared_ptr<Pos> && pos, const Args &... formatArgs
)
{
auto trace = state.ctx.debug->addTrace(
DebugTrace{
.pos = std::move(pos),
.expr = expr,
.env = env,
.hint = HintFmt(formatArgs...),
.isError = false,
}
);
if (state.ctx.debug->stop && state.ctx.debug->errorCallback) {
state.ctx.debug->onEvalError(nullptr, env, expr);
}
return trace;
}
}
#include "lix/libexpr/eval-inline.hh" // IWYU pragma: keep
+76 -29
View File
@@ -1,4 +1,5 @@
#include "lix/libexpr/flake/flake.hh"
#include "lix/libutil/fmt.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/json.hh"
#include "lix/libutil/users.hh"
@@ -29,19 +30,28 @@ static void writeTrustedList(const TrustedList & trustedList)
writeFile(path, JSON(trustedList).dump());
}
static bool askForSetting(
static bool batchAskForSetting(
bool & negativeTrustOverride,
TrustedList & trustedList,
const std::string & name,
const std::string & valueS)
std::map<std::string, std::string> & untrustedSettings)
{
bool trusted = false;
printWarning("The following settings require your decision:");
for (const auto & [name, valueS] : untrustedSettings) {
// FIXME: filter ANSI escapes, newlines, \r, etc.
logger->cout("- %s = %s", name, valueS);
}
// FIXME: filter ANSI escapes, newlines, \r, etc.
auto reply = logger->ask(fmt("Do you want to allow configuration setting '%s' to be set to '" ANSI_RED "%s" ANSI_NORMAL "'?\nThis may allow the flake to gain root, see the nix.conf manual page (" ANSI_BOLD "y" ANSI_NORMAL "es/" ANSI_BOLD "n" ANSI_NORMAL "o/" ANSI_BOLD "N" ANSI_NORMAL "o to all) ", name, valueS)).value_or('n');
auto reply = logger
->ask(
fmt("Do you want to allow configuration settings to be applied?\nThis may allow the "
"flake to gain root, see the nix.conf manual page (" ANSI_BOLD "y" ANSI_NORMAL
"es for now/" ANSI_BOLD "A" ANSI_NORMAL "llow always/" ANSI_BOLD "n" ANSI_NORMAL
"o/" ANSI_BOLD "N" ANSI_NORMAL "o to all) ")
)
.value_or('n');
if (reply == 'N') {
printTaggedWarning("Rejecting all untrusted nix.conf entries");
printWarning("Rejecting all untrusted nix.conf entries");
printTaggedWarning(
"you can set '%s' to '%b' to automatically reject configuration options supplied by "
"flakes",
@@ -49,25 +59,59 @@ static bool askForSetting(
false
);
negativeTrustOverride = true;
} else {
if (std::tolower(reply) == 'y') {
trusted = true;
} else {
printTaggedWarning(
"you can set '%s' to '%b' to automatically reject configuration options supplied "
"by flakes",
"accept-flake-config",
false
);
return false;
}
if (reply == 'y' || reply == 'A') {
auto alwaysAllow = reply == 'A';
for (const auto & [name, valueS] : untrustedSettings) {
if (alwaysAllow) {
trustedList[name][valueS] = true;
}
globalConfig.set(name, valueS);
}
if (std::tolower(logger->ask(fmt("do you want to permanently (in %s) mark this value as %s? (y/N) ", trustedListPath(), trusted ? "trusted": "untrusted" )).value_or('n')) == 'y') {
trustedList[name][valueS] = trusted;
if (alwaysAllow) {
writeTrustedList(trustedList);
}
return true;
} else {
printTaggedWarning(
"you can set '%s' to '%b' to automatically reject configuration options supplied "
"by flakes",
"accept-flake-config",
false
);
}
auto didTrustedListChange = false;
for (const auto & [name, valueS] : untrustedSettings) {
auto individualReply = logger
->ask(
fmt("Do you want to allow setting '%s = %s'? (" ANSI_BOLD
"y" ANSI_NORMAL "es for now/" ANSI_BOLD "A" ANSI_NORMAL
"llow always/" ANSI_BOLD "n" ANSI_NORMAL "o for now) ",
name,
valueS)
)
.value_or('n');
if (individualReply == 'y' || individualReply == 'A') {
if (individualReply == 'A') {
trustedList[name][valueS] = true;
didTrustedListChange = true;
}
globalConfig.set(name, valueS);
}
}
return trusted;
if (didTrustedListChange) {
writeTrustedList(trustedList);
}
return false;
}
void ConfigFile::apply()
@@ -77,8 +121,11 @@ void ConfigFile::apply()
// Allows to ignore all subsequent settings from this file.
bool negativeTrustOverride = false;
for (auto & [name, value] : settings) {
std::map<std::string, std::string> untrustedSettings;
TrustedList trustedList = readTrustedList();
for (auto & [name, value] : settings) {
auto baseName = name.starts_with("extra-") ? std::string(name, 6) : name;
// FIXME: Move into libutil/config.cc.
@@ -90,11 +137,12 @@ void ConfigFile::apply()
else if (auto* b = std::get_if<Explicit<bool>>(&value))
valueS = b->t ? "true" : "false";
else if (auto ss = std::get_if<std::vector<std::string>>(&value))
valueS = concatStringsSep(" ", *ss); // FIXME: evil
valueS = concatStringsSep(" ", *ss); // FIXME: evil
else
assert(false);
bool trusted = whitelist.count(baseName);
if (!trusted) {
switch (nix::fetchSettings.acceptFlakeConfig.get()) {
case AcceptFlakeConfig::True: {
@@ -102,21 +150,16 @@ void ConfigFile::apply()
break;
}
case AcceptFlakeConfig::Ask: {
auto trustedList = readTrustedList();
auto tlname = get(trustedList, name);
if (auto saved = tlname ? get(*tlname, valueS) : nullptr) {
trusted = *saved;
printInfo("Using saved setting for '%s = %s' from ~/.local/share/nix/trusted-settings.json.", name, valueS);
} else {
if (negativeTrustOverride) {
trusted = false;
} else {
trusted = askForSetting(negativeTrustOverride, trustedList, name, valueS);
}
untrustedSettings[name] = valueS;
}
break;
}
case nix::AcceptFlakeConfig::False: {
case AcceptFlakeConfig::False: {
trusted = false;
break;
};
@@ -135,6 +178,10 @@ void ConfigFile::apply()
);
}
}
if (!untrustedSettings.empty()) {
batchAskForSetting(negativeTrustOverride, trustedList, untrustedSettings);
}
}
}
+47 -46
View File
@@ -331,10 +331,9 @@ static Flake getFlake(
state.ctx.errors.make<EvalError>("file '%s' must be an attribute set", resolvedFlakeFile).debugThrow();
}
Value vInfo;
state.eval(flakeExpr, vInfo);
Value vInfo = state.eval(flakeExpr);
if (auto description = vInfo.attrs()->get(state.ctx.s.description)) {
if (auto description = vInfo.attrs()->get(state.ctx.symbols.sym_description)) {
expectType(state, nString, description->value, description->pos);
flake.description = description->value.str();
}
@@ -367,7 +366,7 @@ static Flake getFlake(
flake.resolvedRef = resolvedRef;
}
if (auto outputs = vInfo.attrs()->get(state.ctx.s.outputs)) {
if (auto outputs = vInfo.attrs()->get(state.ctx.symbols.sym_outputs)) {
expectType(state, nFunction, outputs->value, outputs->pos);
if (outputs->value.isLambda()) {
@@ -376,19 +375,19 @@ static Flake getFlake(
pattern)
{
for (auto & formal : pattern->formals) {
if (formal.name != state.ctx.s.self)
if (formal.name != state.ctx.symbols.sym_self) {
flake.inputs.emplace(
state.ctx.symbols[formal.name],
FlakeInput{
.ref = parseFlakeRef(std::string(state.ctx.symbols[formal.name]))
}
FlakeInput{.ref = parseFlakeRef(std::string(state.ctx.symbols[formal.name]))}
);
}
}
}
}
} else
} else {
throw Error("flake '%s' lacks attribute 'outputs'", lockedRef);
}
auto sNixConfig = state.ctx.symbols.create("nixConfig");
@@ -457,12 +456,16 @@ static Flake getFlake(
}
for (auto & attr : *vInfo.attrs()) {
if (attr.name != state.ctx.s.description &&
attr.name != sInputs &&
attr.name != state.ctx.s.outputs &&
attr.name != sNixConfig)
throw Error("flake '%s' has an unsupported attribute '%s', at %s",
lockedRef, state.ctx.symbols[attr.name], state.ctx.positions[attr.pos]);
if (attr.name != state.ctx.symbols.sym_description && attr.name != sInputs
&& attr.name != state.ctx.symbols.sym_outputs && attr.name != sNixConfig)
{
throw Error(
"flake '%s' has an unsupported attribute '%s', at %s",
lockedRef,
state.ctx.symbols[attr.name],
state.ctx.positions[attr.pos]
);
}
}
return flake;
@@ -937,43 +940,34 @@ LockedFlake lockFlake(
}
}
void callFlake(EvalState & state,
const LockedFlake & lockedFlake,
Value & vRes)
Value callFlake(EvalState & state, const LockedFlake & lockedFlake)
{
Value vLocks;
Value vRootSrc;
Value vRootSubdir;
Value vTmp1;
Value vTmp2;
vLocks.mkString(lockedFlake.lockFile.to_string());
vLocks = {NewValueAs::string, lockedFlake.lockFile.to_string()};
emitTreeAttrs(
Value vRootSrc = emitTreeAttrs(
state.ctx,
*lockedFlake.flake.sourceInfo,
lockedFlake.flake.lockedRef.input,
vRootSrc,
false,
lockedFlake.flake.forceDirty
);
vRootSubdir.mkString(lockedFlake.flake.lockedRef.subdir);
vRootSubdir = {NewValueAs::string, lockedFlake.flake.lockedRef.subdir};
if (!state.ctx.caches.vCallFlake) {
state.ctx.caches.vCallFlake = allocRootValue({});
state.eval(
state.ctx.parseExprFromString(
*state.ctx.caches.vCallFlake = state.eval(state.ctx.parseExprFromString(
#include "call-flake.nix.gen.hh"
, CanonPath::root
),
*state.ctx.caches.vCallFlake
);
, CanonPath::root
));
}
state.callFunction(*state.ctx.caches.vCallFlake, vLocks, vTmp1, noPos);
state.callFunction(vTmp1, vRootSrc, vTmp2, noPos);
state.callFunction(vTmp2, vRootSubdir, vRes, noPos);
Value vTmp1 = state.callFunction(*state.ctx.caches.vCallFlake, vLocks, noPos);
Value vTmp2 = state.callFunction(vTmp1, vRootSrc, noPos);
return state.callFunction(vTmp2, vRootSubdir, noPos);
}
void prim_getFlake(EvalState & state, Value * * args, Value & v)
@@ -983,15 +977,19 @@ void prim_getFlake(EvalState & state, Value * * args, Value & v)
if (evalSettings.pureEval && !flakeRef.input.isLocked())
throw Error("cannot call 'getFlake' on unlocked flake reference '%s' (use --impure to override)", flakeRefS);
callFlake(state,
lockFlake(state, flakeRef,
LockFlags {
v = callFlake(
state,
lockFlake(
state,
flakeRef,
LockFlags{
.updateLockFile = false,
.writeLockFile = false,
.useRegistries = !evalSettings.pureEval && fetchSettings.useRegistries,
.allowUnlocked = !evalSettings.pureEval,
}),
v);
}
)
);
}
void prim_parseFlakeRef(
@@ -1006,13 +1004,16 @@ void prim_parseFlakeRef(
for (const auto & [key, value] : attrs) {
auto s = state.ctx.symbols.create(key);
auto & vv = binds.alloc(s);
std::visit(overloaded {
[&vv](const std::string & value) { vv.mkString(value); },
[&vv](const uint64_t & value) { vv.mkInt(value); },
[&vv](const Explicit<bool> & value) { vv.mkBool(value.t); }
}, value);
std::visit(
overloaded{
[&vv](const std::string & value) { vv = {NewValueAs::string, value}; },
[&vv](const uint64_t & value) { vv = {NewValueAs::integer, NixInt::Inner(value)}; },
[&vv](const Explicit<bool> & value) { vv = {NewValueAs::boolean, value.t}; }
},
value
);
}
v.mkAttrs(binds);
v = {NewValueAs::attrs, binds};
}
void prim_flakeRefToString(
@@ -1050,7 +1051,7 @@ void prim_flakeRefToString(
}
}
auto flakeRef = FlakeRef::fromAttrs(attrs);
v.mkString(flakeRef.to_string());
v = {NewValueAs::string, flakeRef.to_string()};
}
}
+4 -9
View File
@@ -199,19 +199,14 @@ LockedFlake lockFlake(
const FlakeRef & flakeRef,
const LockFlags & lockFlags);
void callFlake(
EvalState & state,
const LockedFlake & lockedFlake,
Value & v);
Value callFlake(EvalState & state, const LockedFlake & lockedFlake);
}
void emitTreeAttrs(
Value emitTreeAttrs(
Evaluator & state,
const fetchers::Tree & tree,
const fetchers::Input & input,
Value & v,
bool emptyRevFallback = false,
bool forceDirty = false);
bool forceDirty = false
);
}
+10
View File
@@ -7,6 +7,8 @@
#include "lix/libfetchers/fetchers.hh"
#include "lix/libfetchers/registry.hh"
#include <cerrno>
namespace nix {
#if 0
@@ -150,6 +152,14 @@ std::pair<FlakeRef, std::string> parseFlakeRefWithFragment(
throw BadURL("could not find a flake.nix file");
}
try {
path = absPath(path, std::nullopt, true);
} catch (SysError & e) {
if (e.errNo != ENOENT && e.errNo != ENOTDIR) {
throw;
}
}
if (!S_ISDIR(lstat(path).st_mode))
throw BadURL("path '%s' is not a flake (because it's not a directory)", path);
+3 -3
View File
@@ -191,9 +191,9 @@ LockFile LockFile::read(const Path & path)
}
try {
return LockFile(json::parse(readFile(path)), path);
} catch (json::ParseError &json_parse_error) {
json_parse_error.addTrace(nullptr, "while parsing the lock file at %s", path);
throw;
} catch (json::JSONError & json_parse_error) {
json_parse_error.addTrace(nullptr, "while parsing the lock file at %s", path);
throw;
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
libexpr_generated_headers += custom_target(
liblix_generated_headers += custom_target(
command : [ 'bash', '-c', 'echo \'R"__NIX_STR(\' | cat - @INPUT@ && echo \')__NIX_STR"\'' ],
input : 'call-flake.nix',
output : '@PLAINNAME@.gen.hh',
+12 -13
View File
@@ -64,7 +64,7 @@ try {
std::string DrvInfo::queryName(EvalState & state)
{
if (name == "" && attrs) {
auto i = attrs->get(state.ctx.s.name);
auto i = attrs->get(state.ctx.symbols.sym_name);
if (!i) {
state.ctx.errors.make<TypeError>("derivation name missing").debugThrow();
}
@@ -79,7 +79,7 @@ std::string DrvInfo::queryName(EvalState & state)
std::string DrvInfo::querySystem(EvalState & state)
{
if (system == "" && attrs) {
auto i = attrs->get(state.ctx.s.system);
auto i = attrs->get(state.ctx.symbols.sym_system);
system = !i
? "unknown"
: state.forceStringNoCtx(
@@ -93,7 +93,7 @@ std::string DrvInfo::querySystem(EvalState & state)
std::optional<StorePath> DrvInfo::queryDrvPath(EvalState & state)
{
if (!drvPath && attrs) {
auto i = attrs->get(state.ctx.s.drvPath);
auto i = attrs->get(state.ctx.symbols.sym_drvPath);
NixStringContext context;
if (!i) {
drvPath = {std::nullopt};
@@ -121,7 +121,7 @@ StorePath DrvInfo::requireDrvPath(EvalState & state)
StorePath DrvInfo::queryOutPath(EvalState & state)
{
if (!outPath && attrs) {
auto i = attrs->get(state.ctx.s.outPath);
auto i = attrs->get(state.ctx.symbols.sym_outPath);
NixStringContext context;
if (i) {
outPath = state.coerceToStorePath(
@@ -150,7 +150,7 @@ void DrvInfo::fillOutputs(EvalState & state, bool withPaths)
return;
}
const Attr * outputs = this->attrs->get(state.ctx.s.outputs);
const Attr * outputs = this->attrs->get(state.ctx.symbols.sym_outputs);
if (outputs == nullptr) {
fillDefault();
return;
@@ -183,7 +183,7 @@ void DrvInfo::fillOutputs(EvalState & state, bool withPaths)
state.forceAttrs(out->value, outputs->pos, errMsg);
// ...and evaluate its `outPath` attribute.
const Attr * outPath = out->value.attrs()->get(state.ctx.s.outPath);
const Attr * outPath = out->value.attrs()->get(state.ctx.symbols.sym_outPath);
if (outPath == nullptr) {
continue;
// FIXME: throw error?
@@ -222,7 +222,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(EvalState & state, bool withPaths, bool o
// output by its attribute, e.g. `pkgs.lix.dev`, which (lol?) sets the magic
// attribute `outputSpecified = true`, and changes the `outputName` attr to the
// explicitly selected-into output.
if (const Attr * outSpecAttr = attrs->get(state.ctx.s.outputSpecified)) {
if (const Attr * outSpecAttr = attrs->get(state.ctx.symbols.sym_outputSpecified)) {
bool outputSpecified = state.forceBool(
outSpecAttr->value,
outSpecAttr->pos,
@@ -264,7 +264,7 @@ DrvInfo::Outputs DrvInfo::queryOutputs(EvalState & state, bool withPaths, bool o
std::string DrvInfo::queryOutputName(EvalState & state)
{
if (outputName == "" && attrs) {
auto i = attrs->get(state.ctx.s.outputName);
auto i = attrs->get(state.ctx.symbols.sym_outputName);
outputName = i ? state.forceStringNoCtx(
i->value, noPos, "while evaluating the output name of a derivation"
)
@@ -278,7 +278,7 @@ Bindings * DrvInfo::getMeta(EvalState & state)
{
if (meta) return meta;
if (!attrs) return 0;
auto a = attrs->get(state.ctx.s.meta);
auto a = attrs->get(state.ctx.symbols.sym_meta);
if (!a) {
return 0;
}
@@ -310,7 +310,7 @@ bool DrvInfo::checkMeta(EvalState & state, Value & v)
return true;
}
else if (v.type() == nAttrs) {
auto i = v.attrs()->get(state.ctx.s.outPath);
auto i = v.attrs()->get(state.ctx.symbols.sym_outPath);
if (i) {
return false;
}
@@ -451,8 +451,7 @@ static void getDerivations(EvalState & state, Value & vIn, PosIdx pos,
DrvInfos & drvs, Done & done,
bool ignoreAssertionFailures)
{
Value v;
state.autoCallFunction(autoArgs, vIn, v, pos);
Value v = state.autoCallFunction(autoArgs, vIn, pos);
bool shouldRecurse = getDerivation(state, v, pathPrefix, drvs, ignoreAssertionFailures);
if (!shouldRecurse) {
@@ -524,7 +523,7 @@ static void getDerivations(EvalState & state, Value & vIn, PosIdx pos,
`recurseForDerivations = true' attribute. */
if (attr->value.type() == nAttrs) {
const Attr * recurseForDrvs =
attr->value.attrs()->get(state.ctx.s.recurseForDerivations);
attr->value.attrs()->get(state.ctx.symbols.sym_recurseForDerivations);
if (recurseForDrvs == nullptr) {
continue;
}
+6 -6
View File
@@ -43,7 +43,7 @@ class JSONSax : nlohmann::json_sax<JSON> {
auto attrs2 = state.ctx.buildBindings(attrs.size());
for (auto & i : attrs)
attrs2.insert(i.first, i.second);
parent->value().mkAttrs(attrs2.alreadySorted());
parent->value() = {NewValueAs::attrs, attrs2.alreadySorted()};
return std::move(parent);
}
void add() override
@@ -101,14 +101,14 @@ public:
bool boolean(bool val) override
{
rs->value().mkBool(val);
rs->value() = {NewValueAs::boolean, val};
rs->add();
return true;
}
bool number_integer(number_integer_t val) override
{
rs->value().mkInt(val);
rs->value() = {NewValueAs::integer, val};
rs->add();
return true;
}
@@ -121,21 +121,21 @@ public:
return number_float(static_cast<number_float_t>(val_), "");
}
NixInt::Inner val = val_;
rs->value().mkInt(val);
rs->value() = {NewValueAs::integer, val};
rs->add();
return true;
}
bool number_float(number_float_t val, const string_t & s) override
{
rs->value().mkFloat(val);
rs->value() = {NewValueAs::floating, val};
rs->add();
return true;
}
bool string(string_t & val) override
{
rs->value().mkString(val);
rs->value() = {NewValueAs::string, val};
rs->add();
return true;
}
+1 -3
View File
@@ -5,6 +5,4 @@ includedir=@includedir@
Name: Lix libexpr
Description: Lix Package Manager (libexpr)
Version: @PACKAGE_VERSION@
# dependencies on boost is omitted since it is optional (only required by some headers)
Requires: lix-base lix-util lix-store lix-fetchers @BOEHM_IF_FOUND@
Libs: -L${libdir} -llixexpr
Requires: lix
+8 -89
View File
@@ -1,8 +1,8 @@
libexpr_generated_headers = [
liblix_generated_headers += [
gen_header.process('primops/derivation.nix', preserve_path_from : meson.current_source_dir()),
]
foreach header : [ 'imported-drv-to-derivation.nix', 'fetchurl.nix' ]
libexpr_generated_headers += custom_target(
liblix_generated_headers += custom_target(
command : [ 'bash', '-c', 'echo \'R"__NIX_STR(\' | cat - @INPUT@ && echo \')__NIX_STR"\'' ],
input : header,
output : '@PLAINNAME@.gen.hh',
@@ -31,9 +31,10 @@ libexpr_setting_definitions = files(
'settings/restrict-eval.md',
'settings/trace-function-calls.md',
'settings/trace-verbose.md',
'settings/warn-import-from-derivation.md',
# keep-sorted end
)
libexpr_settings_header = custom_target(
liblix_generated_headers += custom_target(
command : [
python.full_path(),
'@SOURCE_ROOT@/lix/code-generation/build_settings.py',
@@ -173,7 +174,7 @@ builtins_gen = custom_target(
'builtins.md',
],
)
register_builtins_header = builtins_gen[0]
liblix_generated_headers += builtins_gen[0]
builtins_md = builtins_gen[1]
builtin_constant_definitions = files(
@@ -204,15 +205,16 @@ builtin_constants_gen = custom_target(
'builtin-constants.md',
],
)
register_builtin_constants_header = builtin_constants_gen[0]
liblix_generated_headers += builtin_constants_gen[0]
builtin_constants_md = builtin_constants_gen[1]
libexpr_sources = files(
liblix_sources += files(
# keep-sorted start
'attr-path.cc',
'attr-set.cc',
'eval-cache.cc',
'eval-error.cc',
'eval-expr.cc',
'eval-settings.cc',
'eval.cc',
'flake/config.cc',
@@ -277,91 +279,8 @@ libexpr_headers = files(
# keep-sorted end
)
dependencies = [
liblixutil,
liblixstore,
liblixfetchers,
boehm,
boost,
kj,
nlohmann_json,
toml11,
]
libexpr_temp = library(
is_static ? 'lixexpr_temp' : 'lixexpr',
libexpr_sources,
libexpr_settings_header,
libexpr_generated_headers,
register_builtins_header,
register_builtin_constants_header,
dependencies : dependencies,
# for shared.hh
include_directories : [
'../libmain',
],
cpp_pch : cpp_pch,
install : not is_static,
# FIXME(Qyriad): is this right?
install_rpath : libdir,
)
# FIXME: remove when https://git.lix.systems/lix-project/lix/issues/359 is fixed.
# FIXME: replace by prelink when https://github.com/mesonbuild/meson/pull/14846 is widely available.
if is_static
libexpr_prelink = custom_target(
'lixexpr-prelink',
output : 'lixexpr-prelink.o',
input : libexpr_temp,
command : [
cxx.cmd_array(),
'-r',
'-o',
'@OUTPUT@',
is_darwin ? '-Wl,-force_load' : '-Wl,--whole-archive',
'@INPUT@',
],
)
libexpr = library(
'lixexpr',
[libexpr_prelink],
dependencies : dependencies,
install : true,
)
else
libexpr = libexpr_temp
endif
install_headers(
libexpr_headers,
subdir : 'lix/libexpr',
preserve_path : true,
)
liblixexpr = declare_dependency(
include_directories : include_directories('../..'),
sources : libexpr_settings_header,
dependencies : [
liblixutil,
liblixfetchers,
boehm,
boost,
],
link_with : libexpr,
)
meson.override_dependency('lix-expr', liblixexpr)
# FIXME: not using the pkg-config module because it creates way too many deps
# while meson migration is in progress, and we want to not include boost here
configure_file(
input : 'lix-expr.pc.in',
output : 'lix-expr.pc',
install_dir : libdir / 'pkgconfig',
configuration : {
'prefix' : prefix,
'libdir' : libdir,
'includedir' : includedir,
'PACKAGE_VERSION' : meson.project_version(),
'BOEHM_IF_FOUND' : boehm.found() ? 'bdw-gc' : '',
},
)
+3 -2
View File
@@ -2,6 +2,7 @@
#include "lix/libexpr/eval.hh"
#include "lix/libexpr/symbol-table.hh"
#include "lix/libexpr/print.hh"
#include "lix/libutil/json.hh"
#include <cstdlib>
#include <sstream>
@@ -43,12 +44,12 @@ static JSON stringToJSON(std::string_view s)
// hot, so the extra memory allocation and encoding is not worth avoiding
(void) value.dump();
return value;
} catch (nlohmann::json::type_error & e) { // NOLINT(lix-foreign-exceptions)
} catch (json::JSONError & e) {
if (e.id == 316) {
// invalid utf8 in string! serialize as byte array instead
return s | std::ranges::to<std::vector<unsigned char>>();
} else {
throw; // NOLINT(lix-foreign-exceptions)
throw;
}
}
}

Some files were not shown because too many files have changed in this diff Show More