Skip to content

Flakes UX: make it easy to evaluate an arbitrary expression in a context of a flake #5567

Open

Description

@balsoft

This is a design discussion issue, so feel free to give as much feedback and criticism as you like.

Preamble

In ye olde days of nix-shell, it was possible to easily evaluate expressions in the context of nixpkgs. Something like this:

nix-shell -p 'python3.withPackages (ps: with ps; [ numpy scipy ])'

Drops you into a shell in which there's a python3 executable with numpy and scipy available. This is really useful for ad-hoc scripting. You could also do something like

nix-shell -p 'hello.overrideAttrs (_: { src = ./.; })'

It was also possible to add alias p='nix-shell -p' to save some typing.

The flexibility is endless -- and all just a few keystrokes away!

Current situation

It is possible to do something similar with new, flaky interface:

nix shell --impure --expr 'with builtins.getFlake "nixpkgs"; with legacyPackages.${builtins.currentPlatform}; python3.withPackages (ps: with ps; [ numpy scipy ])'

However, this is a chore to do, and I'd much rather just run pip install numpy scipy and deal with all the usual stateful package management issues than type this monstrosity every time I need to try a python package.

Proposal

Add a way to easily evaluate expressions "in the context of" a flake, meaning with the top-level attributes and {packages,legacyPackages}.${currentPlatform} of that flake available in scope.

Possible implementations

I came up with three different ideas, all of which have some advantages and drawbacks.

(my current favourite) Allow flake fragments to be arbitrary expressions

Example: nix shell 'nixpkgs#(python3.withPackages (ps: with ps; [ numpy scipy ]))'

This feels like a natural extension of the already-existing flake-fragment-as-attrpath interpretation. It shouldn't be too difficult to implement, and doesn't break compatibility. It does however introduce some potential complexity to newcomers.

With alias p='nix shell' it is possible to do p 'nixpkgs#python3.withPackages (...)' , and some more keystrokes could be saved with a registry entry n -> nixpkgs: p 'n#python3.withPackages (...)'

Add a new flag, like --with

Example: nix shell --with nixpkgs 'python3.withPackages (ps: with ps; [ numpy scipy ])'

This plays nicely with Nix' with keyword. It implies that some expression will be evaluated with some additional context.

Aliasing p='nix shell --with nixpkgs' can give experience identical to the status quo -- p 'python3.withPackages (...)'

Change the behaviour of --expr

Example: nix shell --expr nixpkgs 'python3.withPackages (ps: with ps; [ numpy scipy ])'

This breaks compatibility, but may be nicer than --with since --expr was not very usable with flakes anyways and it's not nice to have a lot of useless flags around.

Activity

  1. Radvendii commented on Nov 15, 2021

    @Radvendii
  2. thufschmitt commented on Nov 17, 2021

    @thufschmitt
    Member

    I’m a big fan of the overall idea, that’s something I want to have available reasonably frequently, and it’s always a pain. I’m not sure what the UX should be though:

    • The nixpkgs#(expression) syntax would make a lot of sense if the Nix language had a x.(expr) syntax (like what OCaml has for modules), but it doesnt, (and for good reasons imho). So it’s a bit confusing. (and to be pedantic, it’s reusing some already valid syntax: nixpkgs#(foo) will evaluate to the (foo) field of nixpkgs)
    • --with <flakeref> sounds nice, but since it only makes sense with --expr, which isn’t very clean
    • --expr <flakeref> <expr> isn’t really viable, because part of the point of --expr is to make it possible to use the nix command with non-flake things.

    A fourth way could be to have a --expr-with <flakeref> <expr> flag. But it’s not utterly pretty either.

  3. balsoft commented on Nov 17, 2021

    @balsoft
    MemberAuthor

    My --with flag suggestion is actually --with <flakeref> <expr>, so like your --expr-with suggestion. But having --with <flakeref> --expr <expr> is also a possible solution.

    The nixpkgs#(expression) syntax would make a lot of sense if the Nix language had a x.(expr) syntax

    I think the installables syntax is already different from usual Nix syntax. E.g. <flakeref>#<attrpath> will not evaluate to the same thing in actual Nix language as it does in the attributes, so I think some syntactic liberty could be allowed. But I also see your point, because it can be even more confusing for newcomers if there's even more strange syntax to learn and understand.

  4. added
    UX
    on Nov 17, 2021
  5. Radvendii commented on Nov 18, 2021

    @Radvendii
    Contributor

    and to be pedantic, it’s reusing some already valid syntax: nixpkgs#(foo) will evaluate to the (foo) field of nixpkgs

    As far as I understand it, this evaluates to the same thing in the existing and proposed cases. It's like the difference between (with foo; bar) and (foo.bar)

  6. thufschmitt commented on Nov 18, 2021

    @thufschmitt
    Member

    and to be pedantic, it’s reusing some already valid syntax: nixpkgs#(foo) will evaluate to the (foo) field of nixpkgs

    As far as I understand it, this evaluates to the same thing in the existing and proposed cases. It's like the difference between (with foo; bar) and (foo.bar)

    Not exactly. Current nixpkgs#(foo) is (builtins.getFlake "nixpkgs").[Search path Magic]."(foo)" while with this proposal it would be (builtins.getFlake "nixpkgs").[Search path Magic].foo (so the attr name is different).
    But that’s really nitpicking because that’s a really small edge-case (and the syntax is officially unstable anyways)

  7. edolstra commented on Nov 18, 2021

    @edolstra
    Member

    For the new UI, we have to careful about adding features that are not discoverable or have a steep learning curve. For instance, in the example

    nix shell --expr nixpkgs 'python3.withPackages (ps: with ps; [ numpy scipy ])'
    

    it's not obvious how a user would discover the existence of python3.withPackages or figure out that they need to write (ps: ...).

    There's also the issue of cacheability. Currently we can cache flake output attributes like nixpkgs#pythonPackages.foo, but not arbitrary expressions like the above.

  8. zimbatm commented on Nov 18, 2021

    @zimbatm
    Member

    If we can translate CLI arguments to function calls, it's possible to build functions that work for common cases. This assumes some cooperation between nixpkgs and the nix CLI.

    Eg: nix apply nixpkgs#python3.with --packages numpy,scipy

    Could map to (builtins.getFlake "nixpkgs).legacyPackages.${builtins.currentSystem}.python3.with { packages = "numpy,scipy"; }

    It makes me think of httpie since they also try to convert CLI to JSON data structures: https://httpie.io/docs#non-string-json-fields

  9. nixos-discourse commented on Nov 25, 2021

    @nixos-discourse

    This issue has been mentioned on NixOS Discourse. There might be relevant details there:

    https://discourse.nixos.org/t/tweag-nix-dev-update-22/16251/1

  10. bmabsout commented on Dec 10, 2021

    @bmabsout

    I recently wanted to do the exact same thing as @balsoft, and I did the exact same workaround. I didn't know whether it was supported natively or not so here's what I tried (What I intuitively thought would work): nix shell nixpkgs/nixos-21.11#python39 --expr "withPackages (p: [p.numpy])" I expected python39's attributes to be in scope for the expression but it wasn't

  11. nixos-discourse commented on Dec 13, 2021

    @nixos-discourse

    This issue has been mentioned on NixOS Discourse. There might be relevant details there:

    https://discourse.nixos.org/t/nix-shell-for-python-packages/16575/4

  12. moved this to To discuss in Nix UXon Dec 16, 2021
  13. 22 remaining items

  14. viperML commented on Oct 26, 2023

    @viperML

    Thanks for the writeup @iFreilicht , LGTM . Personally I think --apply would be more meaningful than --expr, which has already an use. And as you said, perhaps having a different flag with the behaviour of the --expr examples, could be useful.

    nix profile install is a non-obvious case, but should work as well

    I would be concerned about the manifest.json, which follows a schema that might need to be updated. The schema is used to properly update the packages by referencing the same flakeref used to install it, so any --apply should be stored too. Personally I can live without nix profile --apply for the time being :)

    $ nix profile install nixpkgs#python3 --profile ./test_profile
    
    $ jq . ./test_profile/manifest.json
    {
      "elements": [
        {
          "active": true,
          "attrPath": "legacyPackages.aarch64-linux.python3",
          "originalUrl": "flake:nixpkgs",
          "outputs": null,
          "priority": 5,
          "storePaths": [
            "/nix/store/idpjrasbr9n8kij11s5mphrw770sf13s-python3-3.10.12"
          ],
          "url": "path:/nix/store/xjviahzwa7x51vl51kc3c1k1n1jmhpd5-source?lastModified=1697059129&narHash=sha256-9NJcFF9CEYPvHJ5ckE8kvINvI84SZZ87PvqMbH6pro0%3D&rev=5e4c2ada4fcd54b99d56d7bd62f384511a7e2593"
        }
      ],
      "version": 2
    }
    
  15. iFreilicht commented on Oct 26, 2023

    @iFreilicht
    Contributor

    I would be concerned about the manifest.json, which follows a schema that might need to be updated.

    The manifest format already supports store paths with barely any additional info. For example, I compiled nix locally and installed it with nix profile install ./result:

       {
          "active": true,
          "priority": 4,
          "storePaths": [
            "/nix/store/vfzyrg15gf2gvzi76ijsgjd004gcrncv-nix-2.19.0pre20231026_79e0c5c"
          ]
        }
    

    So while an element like this can't be upgraded, it can absolutely be installed without any changes to the manifest format. And as all the installables produced by either --apply or --with would just be store paths, they can be treated as such in every context where installables are valid.

    I don't want to advocate for "extensive support" for this kind of thing though, I'd much rather people write a flake with everything they want to have in their profile and install that.

  16. thufschmitt commented on Oct 27, 2023

    @thufschmitt
    Member

    Thanks for the write-up and the offer to implement @iFreilicht !

    I would weight in favour of the simplest --apply flavour (although --expr could also make sense, and could actually make sense for multiple installable if they are just all added to the scope). I've added that to the @nixos/nix-team backlog, hopefully it can be discussed today or on Monday, and we can get a decision by then.

  17. roberth commented on Oct 27, 2023

    @roberth
    Member

    According to the docs of nix eval --apply, it applies the function expression to each installable, except the second installable is error: unexpected argument.

    This isn't quite as general as I think it should be. What if each installable creates a positional argument? That way you can really use anything as an input.

    nix eval --apply "hello: runCommand: runCommand "hi" { nativeBuildInputs = [ hello ]; } ''hello >$out''" nixpkgs#hello nixpkgs#runCommand
    

    Not sure whether getting the default package is a good idea, when a fragment is missing. I guess nixpkgs#. could represent the whole Nixpkgs flake, but I would find nixpkgs to be simpler, and I'd be happy to write nixpkgs#default for a hypothetical default package.

  18. bobvanderlinden commented on Oct 27, 2023

    @bobvanderlinden
    Member

    Hmm, looking at the nix profile example and it being unable to upgrade... Could we unify this more so that things will work everywhere? For instance, have the expression as part of the url. That way it is easier to store and will work for any cmdline tool. Not sure if it'll lead to the perfect UX, but just to explore that space a bit:

    The same has been done for explicitly stating outputs: nix shell nixpkgs#openssl^bin which is basically openssl.bin in nix repl. This already is kind of confusing, as nix shell nixpkgs#openssl.bin is equal (different discussion I guess).

    If the suffix of # would be any Nix expression inside the context of the flake, then you would be able to:

    nix shell "nixpkgs#openssl.override { withZlib = false; }"
    

    Same for python:

    nix shell "nixpkgs#python3.withPackages (ps: [ ps.pandas ])"
    

    It should then also work for packages that do not use . notation:

    nix build 'nixpkgs#writeShellScript "fancyapp" "echo hello"'
    

    Because it is part of the URL, it'll work for build, shell, profile. For nix shell it'll support multiple expressions.

    All of these will work using nix profile upgrade as well.

    Edit: thinking about this some more, it even makes sense to drop the 'multiple output'-syntax for URLs (nixpkgs#openssl^bin,lib) and replace it with an array (nixpkgs#with openssl; [ bin lib ]). It works just like using nix repl after:

    :lf nixpkgs
    with legacyPackages.${system}; 
    ```.
    
  19. self-assigned this
    on Oct 27, 2023
  20. iFreilicht commented on Oct 27, 2023

    @iFreilicht
    Contributor

    What if each installable creates a positional argument? That way you can really use anything as an input.

    @roberth Yes, I discussed this solution under the "Split options" heading.

    Not sure whether getting the default package is a good idea, when a fragment is missing.

    I would like this to not have as little special behavior as possible. I'll have to look at a few examples to see potential drawbacks.

    If the suffix of # would be any Nix expression inside the context of the flake, then you would be able to:

    nix shell "nixpkgs#openssl.override { withZlib = false; }"
    

    @bobvanderlinden Very interesting idea as well! I guess in terms of parsing the flake name this isn't an issue, but about the output I'm not sure. It should be doable.

    Because it is part of the URL, it'll work for build, shell, profile. For nix shell it'll support multiple expressions.

    That's true and makes this a very elegant solution, though it does make parsing a flake URL much more difficult and in some cases potentially impossible. I'm thinking especially about the work in #8678. Also, as I understand, this would not solve the multiple-inputs usecase. So --apply would still be needed when you want to combine nixpkgs with an external overlay.

    thinking about this some more, it even makes sense to drop the 'multiple output'-syntax for URLs (nixpkgs#openssl^bin,lib) and replace it with an array (nixpkgs#with openssl; [ bin lib ])

    Hmm, I'm not so sure about that. Having the output syntax as syntactic sugar is nice. This shields new and consumer-only users from Nix syntax on the command line, something that the old CLI required for some basic use-cases IIRC. But these should be equivalent, I agree with that.

  21. fricklerhandwerk commented on Oct 27, 2023

    @fricklerhandwerk
    Contributor

    Triaged in Nix meeting:

    • Most solution proposals are iffy
    • How about @roberth's: Flakes UX: make it easy to evaluate an arbitrary expression in a context of a flake #5567 (comment)
    • Pretty much just function and argument, very general
    • Why is the language itself not sufficient?
      • It is, but not as convenient when on the fly
    • Applying functions is a one way street from installables
    • The for each and the currying/positional argument interpretation are both valid and we have to clarify the use cases
    • Just sugar, but we're not clear on how to structure the underlying thing yet
      • There may be some answers when clarifying the role of what's currently callFlake
    • Risk of getting stuck with something we don't want
    • Hopefully in the future something like flake-compat defines flakes, then we can have a direct mapping from CLI flags to flake-compat functionality
    • We discuss a lot of flakes samples, but the same questions apply to any expression in a file
    • Decision: Postponed until after RFC 136 is implemented
  22. iFreilicht commented on Oct 27, 2023

    @iFreilicht
    Contributor

    Yeah that decision is fair. Especially as all proposals we had are non-breaking additions, stabilizing the current state is more important.

  23. nixos-discourse commented on Oct 27, 2023

    @nixos-discourse
  24. nixos-discourse commented on Oct 29, 2023

    @nixos-discourse

    This issue has been mentioned on NixOS Discourse. There might be relevant details there:

    https://discourse.nixos.org/t/decision-making-2-0-1-0-1/12851/24

  25. bobvanderlinden commented on Oct 30, 2023

    @bobvanderlinden
    Member

    That's true and makes this a very elegant solution, though it does make parsing a flake URL much more difficult and in some cases potentially impossible

    I was under the impression that would be easily parsable. Both NodeJS and Python are able to parse them. However, according to RFC2396 it is indeed not a valid URI. Nix seems to follow that standard more strictly. Allowing more than RFC2396 defines URIs makes it a harder decision.

    Decision: Postponed until after RFC 136 is implemented

    👍

  26. iFreilicht commented on Oct 30, 2023

    @iFreilicht
    Contributor

    I was under the impression that would be easily parsable. Both NodeJS and Python are able to parse them.

    I should've been clearer. What I meant was that it makes it impossible to find a human-readable name for flake from the URL by just parsing. You have to actually evaluate the Nix code inside of it to get all the output paths and can then potentially create a compound name.
    I guess that's not necessarily an argument against implementing this, just something to be aware of, as it's definitely a solvable problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

UXflakes

Projects

  • Status
    Backlog

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions