|
| 1 | +# Using a devshell as a Nix application |
| 2 | + |
| 3 | +Devshells provide the attribute `flakeApp`, which contains an attribute set |
| 4 | +suitable for use as an entry in the `apps` flake output structure. Export this |
| 5 | +attribute under `apps.<system>.<myapp>`, and then you can run commands within |
| 6 | +your devshell as follows: |
| 7 | + |
| 8 | +```sh |
| 9 | +nix run '.#<myapp>' -- <devshell-command> <and-args> |
| 10 | +``` |
| 11 | + |
| 12 | +For example, given the following `flake.nix`: |
| 13 | + |
| 14 | +```nix |
| 15 | +{ |
| 16 | + inputs.devshell.url = "github:numtide/devshell"; |
| 17 | + inputs.flake-utils.url = "github:numtide/flake-utils"; |
| 18 | +
|
| 19 | + outputs = { self, flake-utils, devshell, nixpkgs }: |
| 20 | + flake-utils.lib.eachDefaultSystem (system: { |
| 21 | + apps.devshell = self.outputs.devShells.${system}.default.flakeApp; |
| 22 | +
|
| 23 | + devShells.default = |
| 24 | + let |
| 25 | + pkgs = import nixpkgs { |
| 26 | + inherit system; |
| 27 | +
|
| 28 | + overlays = [ devshell.overlays.default ]; |
| 29 | + }; |
| 30 | + in |
| 31 | + pkgs.devshell.mkShell ({ config, ... }: { |
| 32 | + commands = [ |
| 33 | + { |
| 34 | + name = "greet"; |
| 35 | + command = '' |
| 36 | + printf -- 'Hello, %s!\n' "''${1:-world}" |
| 37 | + ''; |
| 38 | + } |
| 39 | + ]; |
| 40 | + }); |
| 41 | + }); |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +You can execute your devshell's `greet` command like this: |
| 46 | + |
| 47 | +```console |
| 48 | +$ nix run '.#devshell' -- greet myself |
| 49 | +Hello, myself! |
| 50 | +``` |
| 51 | + |
| 52 | +## Setting `PRJ_ROOT` |
| 53 | + |
| 54 | +By default, the `PRJ_ROOT` environment variable is set to the value of the |
| 55 | +`PWD` environment variable. You can override this by defining `PRJ_ROOT` in |
| 56 | +`nix run`'s environment: |
| 57 | + |
| 58 | +```sh |
| 59 | +PRJ_ROOT=/some/where/else nix run '.#<myapp>' -- <devshell-command> <and-args> |
| 60 | +``` |
| 61 | + |
| 62 | +You can also use the `--prj-root` option: |
| 63 | + |
| 64 | +```sh |
| 65 | +nix run '.#<myapp>' -- --prj-root /yet/another/path -- <devshell-command> <and-args> |
| 66 | +``` |
0 commit comments