Code Monkey home page Code Monkey logo

nix-direnv's Introduction

nix-direnv

Test

A faster, persistent implementation of direnv's use_nix and use_flake, to replace the built-in one.

Prominent features:

  • significantly faster after the first run by caching the nix-shell environment
  • prevents garbage collection of build dependencies by symlinking the resulting shell derivation in the user's gcroots (Life is too short to lose your project's build cache if you are on a flight with no internet connection)

Why not use lorri instead?

Compared to lorri, nix-direnv is simpler (and requires no external daemon) and supports flakes. Additionally, lorri can sometimes re-evaluate the entirety of nixpkgs on every change (leading to perpetual high CPU load).

Installation

Heads up: nix-direnv requires a modern Bash. MacOS ships with bash 3.2 from 2007. As a work-around we suggest that macOS users install direnv via Nix or Homebrew. There are different ways to install nix-direnv, pick your favourite:

Via home-manager (Recommended)

Via home-manager

Note that while the home-manager integration is recommended, some use cases require the use of features only present in some versions of nix-direnv. It is much harder to control the version of nix-direnv installed with this method. If you require such specific control, please use another method of installing nix-direnv.

In $HOME/.config/home-manager/home.nix add

{
  # ...other config, other config...

  programs = {
    direnv = {
      enable = true;
      enableBashIntegration = true; # see note on other shells below
      nix-direnv.enable = true;
    };

    bash.enable = true; # see note on other shells below
  };
}

Check the current Home Manager Options for integration with shells other than Bash. Be sure to also allow home-manager to manage your shell with programs.<your_shell>.enable = true.

Direnv's source_url

Direnv source_url

Put the following lines in your .envrc:

if ! has nix_direnv_version || ! nix_direnv_version 3.0.4; then
  source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.4/direnvrc" "sha256-DzlYZ33mWF/Gs8DDeyjr8mnVmQGx7ASYqA5WlxwvBG4="
fi
Via system configuration on NixOS

Via system configuration on NixOS

For NixOS 23.05+ all that's required is

{
  programs.direnv.enable = true;
}

other available options are:

{ pkgs, ... }: {
  #set to default values
  programs.direnv = {
    package = pkgs.direnv;
    silent = false;
    loadInNixShell = true;
    direnvrcExtra = "";
    nix-direnv = {
      enable = true;
      package = pkgs.nix-direnv;
    };
  }
With `nix profile`

With nix profile

As non-root user do the following:

nix profile install nixpkgs#nix-direnv

Then add nix-direnv to $HOME/.config/direnv/direnvrc:

source $HOME/.nix-profile/share/nix-direnv/direnvrc
From source

From source

Clone the repository to some directory and then source the direnvrc from this repository in your own ~/.config/direnv/direnvrc:

# put this in ~/.config/direnv/direnvrc
source $HOME/nix-direnv/direnvrc

Usage example

Either add shell.nix or a default.nix to the project directory:

# save this as shell.nix
{ pkgs ? import <nixpkgs> {}}:

pkgs.mkShell {
  packages = [ pkgs.hello ];
}

Then add the line use nix to your envrc:

$ echo "use nix" >> .envrc
$ direnv allow

If you haven't used direnv before, make sure to hook it into your shell first.

Using a non-standard file name

You may use a different file name than shell.nix or default.nix by passing the file name in .envrc, e.g.:

$ echo "use nix foo.nix" >> .envrc

Flakes support

nix-direnv also comes with an alternative use_flake implementation. The code is tested and does work but the upstream flake api is not finalized, so we cannot guarantee stability after a nix upgrade.

Like use_nix, our use_flake will prevent garbage collection of downloaded packages, including flake inputs.

Creating a new flake-native project

This repository ships with a flake template. which provides a basic flake with devShell integration and a basic .envrc.

To make use of this template, you may issue the following command:

$ nix flake new -t github:nix-community/nix-direnv <desired output path>

Integrating with a existing flake

$ echo "use flake" >> .envrc && direnv allow

The use flake line also takes an additional arbitrary flake parameter, so you can point at external flakes as follows:

use flake ~/myflakes#project

Advanced usage

use flake

Under the covers, use_flake calls nix print-dev-env. The first argument to the use_flake function is the flake expression to use, and all other arguments are proxied along to the call to print-dev-env. You may make use of this fact for some more arcane invocations.

For instance, if you have a flake that needs to be called impurely under some conditions, you may wish to pass --impure to the print-dev-env invocation so that the environment of the calling shell is passed in.

You can do that as follows:

$ echo "use flake . --impure" > .envrc
$ direnv allow

use nix

Like use flake, use nix now uses nix print-dev-env. Due to historical reasons, the argument parsing emulates nix shell.

This leads to some limitations in what we can reasonably parse.

Currently, all single-word arguments and some well-known double arguments will be interpreted or passed along.

Manual reload of the nix environment

To avoid delays and time consuming rebuilds at unexpected times, you can use nix-direnv in the "manual reload" mode. nix-direnv will then tell you when the nix environment is no longer up to date. You can then decide yourself when you want to reload the nix environment.

To activate manual mode, use nix_direnv_manual_reload in your .envrc like this:

nix_direnv_manual_reload
use nix # or use flake

To reload your nix environment, use the nix-direnv-reload command:

$ nix-direnv-reload
Known arguments
  • -p: Starts a list of packages to install; consumes all remaining arguments
  • --include / -I: Add the following path to the list of lookup locations for <...> file names
  • --attr / -A: Specify the output attribute to utilize

--command, --run, --exclude, --pure, -i, and --keep are explicitly ignored.

All single word arguments (-j4, --impure etc) are passed to the underlying nix invocation.

Tracked files

As a convenience, nix-direnv adds common files to direnv's watched file list automatically.

The list of additionally tracked files is as follows:

  • for use nix:

    • ~/.direnvrc
    • ~/.config/direnv/direnvrc
    • .envrc,
    • A single nix file. In order of preference:
      • The file argument to use nix
      • default.nix if it exists
      • shell.nix if it exists
  • for use flake:

    • ~/.direnvrc
    • ~/.config/direnv/direnvrc
    • .envrc
    • flake.nix
    • flake.lock
    • devshell.toml if it exists

Users are free to use direnv's builtin watch_file function to track additional files. watch_file must be invoked before either use flake or use nix to take effect.

Environment Variables

nix-direnv sets the following environment variables for user consumption. All other environment variables are either a product of the underlying nix invocation or are purely incidental and should not be relied upon.

  • NIX_DIRENV_DID_FALLBACK: Set when the current revision of your nix shell or flake's devShell are invalid and nix-direnv has loaded the last known working shell.

General direnv tips

Other projects in the field

nix-direnv's People

Contributors

aaqaishtyaq avatar amarshall avatar bbenne10 avatar bbigras avatar bors[bot] avatar carschandler avatar cassandracomar avatar cydparser avatar cyntheticfox avatar davhau avatar dependabot[bot] avatar enzime avatar erikarvstedt avatar ew-at-vier avatar fzakaria avatar gepbird avatar gerg-l avatar github-actions[bot] avatar hoverbear avatar kingarrrt avatar m4dc4p avatar martinetd avatar meck avatar mergify[bot] avatar mic92 avatar pelme avatar pinselimo avatar qaristote avatar ryneeverett avatar tie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nix-direnv's Issues

nix-direnv cannot find nixpkgs with nix-2.4

I have a .envrc containing use nix, and a shell.nix containing with import <nixpkgs> {}; stdenv.mkDerivation { name = "name"; nativeBuildInputs = [ (leiningen.override { jdk = jdk11; }) ]; }

This works fine with nix 2.3, but after upgrading to nix (Nix) 2.4pre-rc1, I get the following when I cd into the directory:
error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)

However, nix-shell still works, and if I use direnv without nix-direnv, that also works.

I'm on macos, and am using home-manager (programs.direnv.nix-direnv.enable = true;), if that's relevant.

$ nix-channel --list`
home-manager https://github.com/nix-community/home-manager/archive/master.tar.gz
nixpkgs https://nixos.org/channels/nixpkgs-unstable

The full output after using cd is as follows:

direnv: loading ~/src/foo/.envrc
direnv: using nix
error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)
direnv: using cached derivation
direnv: eval /Users/djm/src/foo.direnv/cache-unknown
direnv: export +IN_NIX_SHELL +TEMPDIR +XDG_DATA_DIRS ~PATH

Document specifying another Nix file

If one wants to use a custom file (e.g. shell-foo.nix), it appears that use nix shell-foo.nix works.

What do you think about documenting this nice feature in the README?

Thank you for Nix-direnv 🙇

direnvrc probably shouldn't be executable

Describe the bug

Running this file as-is probably shouldn't be possible:

$ /run/current-system/sw/share/nix-direnv/direnvrc
/run/current-system/sw/share/nix-direnv/direnvrc: /nix/store/7grkrbbwq86h54g4kb9rhkk6rhdr4xh3-bash-interactive-4.4-p23/share/bashdb/bashdb-main.inc: No such file or directory
/run/current-system/sw/share/nix-direnv/direnvrc: warning: cannot start debugger; debugging mode disabled

I'm not sure if that does anything. The exit code is 0, which is strange. Sourcing the same file works fine and as expected.

To Reproduce
See above.

Expected behavior
The result should be something like "bash: /run/current-system/sw/share/nix-direnv/direnvrc: Permission denied"

Environment

  • OS: NixOS
  • Shell: Bash
  • Direnv version: 2.28.0

Based off of direnv/direnv#836.

functions defined in shellHook aren't available

# shell.nix
{ pkgs ? import <nixpkgs> {} }:

pkgs.mkShell {
  shellHook = ''
    function afunction() { echo "test"; }
  '';
}

afunction is available in nix-shell:

$ nix-shell

[nix-shell:~/src/nix/direnv-bug]$ afunction
test

but not with direnv:

$ direnv allow
direnv: loading ~/src/nix/direnv-bug/.envrc
direnv: using cached derivation
direnv: eval /.../src/nix/direnv-bug/.direnv/cache-pre237362.e31a4679d50
direnv: export +AR +AS +CC +CONFIG_SHELL +CXX +HOST_PATH +IN_NIX_SHELL +LD +NIX_BINTOOLS +NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu +NIX_BUILD_CORES +NIX_BUILD_TOP +NIX_CC +NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu +NIX_ENFORCE_NO_NATIVE +NIX_HARDENING_ENABLE +NIX_INDENT_MAKE +NIX_LDFLAGS +NIX_STORE +NM +OBJCOPY +OBJDUMP +RANLIB +READELF +SIZE +SOURCE_DATE_EPOCH +STRINGS +STRIP +TEMP +TEMPDIR +TMP +__ETC_PROFILE_SOURCED +buildInputs +builder +configureFlags +depsBuildBuild +depsBuildBuildPropagated +depsBuildTarget +depsBuildTargetPropagated +depsHostHost +depsHostHostPropagated +depsTargetTarget +depsTargetTargetPropagated +doCheck +doInstallCheck +name +nativeBuildInputs +nobuildPhase +out +outputs +patches +phases +propagatedBuildInputs +propagatedNativeBuildInputs +shell +shellHook +stdenv +strictDeps +system ~PATH

$ afunction
afunction: command not found

direnv export fish fails with buildFHSUserEnv

I have a shell.nix that unfortunately requires me to use buildFHSUserEnv. nix shell works, but nix-direnv doesn't.

$ touch shell.nix
direnv: loading ~/some_dir/.envrc
direnv: using nix
cypress-chrootenv:tifa@nixos:~/some_dir$ direnv: 
  ([/nix/store/4ikbx711q3ajvsw74m9sqzk02xcrk6cr-direnv-2.27.0/bin/direnv export fish]) 
  is taking a while to execute. Use CTRL-C to give up.
^C
cypress-chrootenv:tifa@nixos:~/some_diri$ exit

direnv: eval /home/tifa/some_dir/.direnv/cache-.3341.df8e3bd1109
direnv: export +IN_NIX_SHELL ~PATH

I inserted the line breaks around the Nix store path manually so it's easier to read without scrolling

It doesn't tell me anything else. It works in all other folders where I'm just using mkShell.

I'm on NixOS.

nix-shell dependencies not updated during nixos-rebuild

Synpothesis

Derivations that are (only) referenced by some nix-shell (.envrc) are not upgraded during nixos-rebuild --upgrade, while the nixpkgs channel is upgraded. So a rebuild will be triggered when entering those direnv guarded directories.

According to my understanding, nixos-rebuild only builds the user environment defined by /etc/nixos/configuration.nix, so other gc-roots are not rebuilt.

My nix-direnv version is 1.2.6, from nixpkgs 21.05.

Desired behavior

Direnv referenced derivations also get upgraded on nixos-rebuild, or can get upgraded altogether through some separate utility (like home-manager does).

Update install instructions for nix-shell

Hey, to get this package working by installing from nix-shell, I had to changed my $HOME/.direnvrc to

source $HOME/.nix-profile/share/nix-direnv/direnvrc

I think this would be helpful to add to the README in the nix-shell area. If you agree, I can submit a PR

Execute shellHook on cached runs

I set PS1 in the shellHook of my flake.nix (which I think isn't terrible).

However, after #91 is merged, I think this is ineffective because my shell is basically always cached...

Is there anyway to run shellHook in cached hit cases? Or if not, could there be another attribute that is always read out and executed?

GC rooting misses C dependencies of a Haskell project

Hi,

I recently went through every Nix extension of Direnv extension I could find, and did a comparative study. I found that the approach you use seems to miss creating a GC root for C-libraries of a Haskell project.

To test this out, you can clone my shajra/nix-haskell-hls project and do the following steps:

# setup, assuming nix-direnv is installed
#
git clone https://github.com/shajra/nix-haskell-hls.git
echo use_nix > nix-haskell-hls/examples/example-cabal/.envrc
direnv allow nix-haskell-hls/examples/example-cabal/.envrc
cd nix-haskell-hls/examples/example-cabal

# prove that the program compiles and runs
#
cabal run all

# get out of the direnv environment keeping dependencies alive
#
cd ..

# clear out anything not GC rooted
#
nix-collect-garbage

# go back into the environment and see that we're missing a runtime dependency
cd example-cabal
cabal run all

This will give you the following error:

Warning: The package list for 'hackage.haskell.org' does not exist. Run 'cabal
update' to download it.RemoteRepo {remoteRepoName = "hackage.haskell.org",
remoteRepoURI = http://hackage.haskell.org/, remoteRepoSecure = Just True,
remoteRepoRootKeys =
["fe331502606802feac15e514d9b9ea83fee8b6ffef71335479a2e68d84adc6b0","1ea9ba32c526d1cc91ab5e5bd364ec5e9e8cb67179a471872f6e26f0ae773d42","2c6c3627bd6c982990239487f1abd02e08a02e6cf16edb105a8012d444d870c3","0a5c7ea47cd1b15f01f5f51a33adda7e655bc0f0b0615baa8e271f4c3351e21d","51f0161b906011b52c6613376b1ae937670da69322113a246a09f807c62f6921"],
remoteRepoKeyThreshold = 3, remoteRepoShouldTryHttps = True}
Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] trying: example-haskell-app-0.1.0.0 (user goal)
[__1] unknown package: text-icu (dependency of example-haskell-app)
[__1] fail (backjumping, conflict set: example-haskell-app, text-icu)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: example-haskell-app, text-icu

The problem is that the C-library text-icu that this project depends on is being garbage collected.

You can do the steps above with the .envrc provided by the project (not doing the echo setup step above), and you shouldn't see this problem.

The .envrc file I provide uses a project I ended up making in all of this exploration called Lorelei. This project delegates very heavily to Lorri to sort out what to GC root. I think Lorri has the best algorithm I've seen. My project is an attempt to get the benefits of Lorri, but without needing a daemon running, for those people that find daemons a hassle.

Also, I believe that the Nixify approach doesn't have this problem with GC rooting C dependencies.

For the longest time I've been trying to avoid writing something like Lorelei, because I was frustrated that I'd be making yet-another-option, which can be confusing for new users. But now that it's written, I tried to pull in all the features I saw in your project, Nixify, and Sorri that I could think to. Here's what it has thus far:

  • automatically detectable files to watch (lorri/sorri style)
    • uses Lorri code to avoid implementation drift
    • provides an option to control depth of auto-detection, which can help with Nix evaluation speed
  • user-specified files to watch by mtime (nix-direnv style)
  • user-specified files to watch by content hash (Nixify style)
  • keeping the last-n environments to save time when reverting back
  • provides an option to bypass environment caching, but keep GC rooting

One thing I think your project does a lot more is integrate with the Nix community more. You're in NUR, and you're also in Nixpkgs. This is stuff I could do too. But I was hoping maybe we could join forces if you liked my approach.

There's one more difference of implementation between your project and mine. You provide a shell script directly, whereas I build mine out with Nix, allowing me to slip in references to /nix/store for any interesting executables I decide to use as helpers. This means users don't have to install tools like jq, but I can use them if I want to. Also, it locks things down more, which I think is in the spirit of Nix.

Anyway, let me know what you think. Also thanks for putting work in to this project. I definitely took ideas from it.

NIX_BIN_PREFIX: unbound variable

Since version 1.2.3 I get the following error

~/work/some-dir
direnv: loading ~/work/some-dir/.envrc
direnv: using nix
/nix/store/4aifrh1mksd52aam92a4zc6hzjvargrk-nix-direnv-1.2.3/share/nix-direnv/direnvrc:145: NIX_BIN_PREFIX: unbound variable

It works with version 1.2.1.

My system info is

 - system: `"x86_64-darwin"`
 - host os: `Darwin 19.6.0, macOS 10.15.7`
 - multi-user?: `yes`
 - sandbox: `yes`
 - version: `nix-env (Nix) 2.3.10`
 - channels(user): `"darwin, home-manager"`
 - channels(root): `"nixpkgs-21.05pre272202.7fd33568097, darwin, home-manager"`
 - nixpkgs: `/nix/var/nix/profiles/per-user/root/channels/nixpkgs`

Which other information are required?

I haven't investigated further yet, but if you have a tip for me how to fix, I can also try to provide a PR

Additional documentation wrt attributes

It looks like this package supports attributes with something like use nix -A shells.ghc. This is really nice to have, but I think this would be nice to have documented. (Additional nix flags might also be useful to be documented.)

shellHook caching inconsistency with and without flakes

In cached shells, the shellHook does not execute with use nix but does with use flake.

It would be easy to achieve consistency by piping the nix print-dev-env output through sed to remove the final eval "$shellHook", but I'm not sure this is the right direction. It seems that nix develop runs the shellHook even when cached so perhaps it's better not to fight the pattern flakes is currently implementing.

I'm not sure if this is a bug or just a (documentation-worthy?) distinction but it does complicate the creation of environments compatible with or without flakes. For example, I was planning to use an .envrc like:

nix flake --help > /dev/null \
  && use flake \
  || use nix

but heavy shellHooks will need to be rewritten to check whether their expensive processes have been run already.

Has anyone seen this error: "cut: only one type of list may be specified"

I am trying to use nix-direnv in my nix setup on macOS to stop some local nix-shells from being garbage collected.

I have it installed via home-manager, I have the settings in /etc/nix/nix.conf and I have a .envrc in each project that contains use nix.

I get the "cut" error mentions above, and the derivation isn't preserved when I garbage collect… :\

Time for a release?

Before making a PR on nixpkgs (see #16), it might be interesting to release a first version of nix-direnv.

should ldd be /usr/bin/ldd

I have a philosophical question here about how direnv & nix-shell interoperate.

My understanding is that direnv should be bringing in the defined tooling that was defined in shell.nix to allow a more seamless impure development environment (allows running in the user's predefined shell).

I faced an interesting dilemma when trying to run a binary within my direnv'd shell: BeyondCompare -- a diffing tool.
This is a personal tool I have installed outside the world of Nix

The application has a wrapper script which does the following:

#check to see if we have all of the shared libraries.
if ldd "$EXEC" | grep -q "not found" ; then
   #if not then add our qt4 libraries in and see if that fixes problem
   export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$BC_LIB/qt4"
   if ldd "$EXEC" | grep -q "not found" ; then
       echo Some Shared Libraries were not found
       ldd "$EXEC"
        exit 1
   fi
fi

The above looks pretty sane; it just wants to guarantee that the required libraries are present and modify the LD_LIBRARY_PATH if so.

Unfortunately, since ldd in my direnv'd shell is the /nix/store one; it's patched to only look in /nix/store for libraries.

$ which ldd
/nix/store/3imnvgp2dkfpsi75ygmgksn16nksf6ls-glibc-2.30-bin/bin/ldd

$ ldd /usr/lib/beyondcompare/BCompare
	linux-vdso.so.1 (0x00007f9e17b12000)
	/lib/x86_64-linux-gnu/libnss_cache.so.2 (0x00007f9e17b05000)
	librt.so.1 => /nix/store/bqbg6hb2jsl3kvf6jgmgfdqy06fpjrrn-glibc-2.30/lib/librt.so.1 (0x00007f9e17afb000)
	libbz2.so.1.0 => not found
	lib7z.so => not found
	libpthread.so.0 => /nix/store/bqbg6hb2jsl3kvf6jgmgfdqy06fpjrrn-glibc-2.30/lib/libpthread.so.0 (0x00007f9e17ada000)
	libc.so.6 => /nix/store/bqbg6hb2jsl3kvf6jgmgfdqy06fpjrrn-glibc-2.30/lib/libc.so.6 (0x00007f9e1791b000)
	libdl.so.2 => /nix/store/bqbg6hb2jsl3kvf6jgmgfdqy06fpjrrn-glibc-2.30/lib/libdl.so.2 (0x00007f9e17914000)
	/lib64/ld-linux-x86-64.so.2 => /nix/store/bqbg6hb2jsl3kvf6jgmgfdqy06fpjrrn-glibc-2.30/lib64/ld-linux-x86-64.so.2 (0x00007f9e17b14000)
	libQt4Pas.so.5 => not found
	libX11.so.6 => not found
	libz.so.1 => not found
$ /bin/ldd /usr/lib/beyondcompare/BCompare
	linux-vdso.so.1 (0x00007ffc5e0b0000)
	/lib/x86_64-linux-gnu/libnss_cache.so.2 (0x00007f74f5fbb000)
	librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f74f5f96000)
	libbz2.so.1.0 => /lib/x86_64-linux-gnu/libbz2.so.1.0 (0x00007f74f5f83000)
	lib7z.so => not found
	libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f74f5f62000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f74f5d9f000)
	libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f74f5d98000)
	libQt4Pas.so.5 => not found
	libX11.so.6 => /lib/x86_64-linux-gnu/libX11.so.6 (0x00007f74f5c56000)
	libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f74f5c39000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f74f5fc4000)
	libxcb.so.1 => /lib/x86_64-linux-gnu/libxcb.so.1 (0x00007f74f5c0f000)
	libXau.so.6 => /lib/x86_64-linux-gnu/libXau.so.6 (0x00007f74f5c08000)
	libXdmcp.so.6 => /lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007f74f5c00000)
	libbsd.so.0 => /lib/x86_64-linux-gnu/libbsd.so.0 (0x00007f74f5be6000)

Since the whole premise of direnv is to bring in the defined software in an impure fashion; should ldd be unset in this case to allow this program to function?

Explanation how it compares with lorri

Unless I'm wrong, I believe this overlaps with lorri project (from target) how does it compare? What are its strengths? Lorri requires to have a deamon running, looks like this doesn't at first that seems like advantage. Is it possible to add something in the readme that would explain why one would want to use this project?

IN_NIX_SHELL should be pruned

I noticed that in my env IN_NIX_SHELL=pure after using this plugin; but that seems incorrect since the premise of this plugin is to merge the NIX_SHELL into your other shell; making it impure.

Might be worthwhile to purge this variable from the environment dump.
It was very noticeable because my ZSH theme was picking up that environment variable and displaying it.

image

Cannot install via home-manager

I tried to add as README says:

programs = {
    direnv = {
      enable = true;
      nix-direnv.enable = true;
    };
  };

However I always get this error:

error: The option `programs.direnv.nix-direnv' does not exist. Definition values:
- In `/home/matthew/documents/privy/dotfiles/home/home.nix':
    {
      enable = true;
    }
(use '--show-trace' to show detailed location information)

There are 158 unread and relevant news items.
Read them by running the command 'home-manager news'.

Metadata

  • system: "x86_64-linux"
  • host os: Linux 5.12.9, NixOS, 21.11pre295280.fa0326ce523 (Porcupine)
  • multi-user?: yes
  • sandbox: yes
  • version: nix-env (Nix) 2.3.12
  • channels(root): "nixos-21.11pre295280.fa0326ce523"
  • channels(matthew): "home-manager, nixos-21.05pre289339.83d907fd760, nixpkgs-21.05pre289536.c58b97674b1"
  • nixpkgs: /home/matthew/.nix-defexpr/channels/nixpkgs

How i could use nix-direnv but also set up custom functions?

I recently started to use nix-direnv but I think I'm doing some mistakes on how to set up and customize it.

I installed via home-manager as README says. So, going to ~/.config/direnv/direnvrc, the content is:

source /nix/store/j0ai049yz9bjsxy423zppk0ipni1jdr0-nix-direnv-1.2.6/share/nix-direnv/direnvrc

But I want to create a layout_postgres functon to have a per project postgres. So I wrote it with home-manager:

  xdg.configFile.".direnvrc".text = ''
    #! /usr/bin/env nix-shelL
    #! nix-shell -i bash -p postgresql

    layout_postgres() {
      PGHOST=$(direnv_layout_dir)/.postgres
      PGHOST=$PGHOST/data
      PGLOG=$PGHOST/postgres.log
      PGUSER=postgres
      export PGPASSWORD=postgres

      is_running() {
        pg_ctl status 2>/dev/null | grep "server is running" 1>/dev/null
      }

      if [[ ! -d "$PGDATA" ]]; then
        echo 'Initializing postgresql daemon...'
        initdb -auth=trust --no-locale --encoding=UTF8 >/dev/null

        echo "unix_socket_directories = '$PGHOST'" | \
          "$PGDATA/postgresql.conf"

        echo "CREATE DATABASE $PGUSER;" | postgres --single -E postgres
      fi

      if ! is_running; then
        pg_ctl start -l $PGLOG 
      fi

      finish() {
        pg_ctl -D $PGDATA stop  
      }

      trap finish EXIT
    }
  '';

what Iḿ doing wrongly?

does nix-direnv have good integration support for text editors, like emacs ?

Hello There,

I'm currently using lorri, which i'm really happy with for the most part, but I just recently heard about this nix-direnv alternative tool, while reading a nixos reddit forum. nix-direnv looks simpler and easier to setup and configure, than lorri, and nix-direnv being maintained by the nix-community is a huge plus. anyways, before I try nix-direnv, I want to know if it has good support for functionality, such as, integrating with a text editor, like emacs ? lorri has a lot of documentation for things like this, but nix-direnv currently does not, so I want to make sure that switching from lorri to nix-direnv will be a smooth transition.

I'm a little confused, so if you could clarify this, thanks in advance for the help !

"path ... is not a flake" when using flake from outside the current repo

Running nix-darwin using nixpkgs-21.05-darwin on Mac OS Catalina. Shell is fish.

I am following the directions in the README to use a flake.nix from outside the current directory without needing to have a flake.nix in the current directory, however I always get the following error:

direnv: loading ~/Development/flake-pythonify/.envrc
direnv: using flake /Users/masonevans/Development/flake-python-test
error: path '/Users/masonevans/Development/flake-pythonify' is not a flake (because it doesn't contain a 'flake.nix' file)

I have the following setup

  1. A verified-working flake under /Users/masonevans/Development/flake-python-test which outputs a devShell.x86_64-darwin attribute. Direnv works as expected in this directory and gives me a shell with my Python dev env.
  2. A second directory (/Users/masonevans/Development/flake-pythonify) with use flake /Users/masonevans/Development/flake-python-test in .envrc (I've tried variations of that as well, e.g. flake-python-test#devShell.x86_64-darwin). This directory gives me an error about a missing flake.nix.

My goal is to create a flake on my system that defines a Python dev environment which I can then reference from all my individual projects.

My expectation, based on my reading of the README, is that I can define a flake in one place and then import it in multiple other directories, and this way I don't need to have a flake.nix in each project if I don't want to.

Output of direnv status

direnv status
direnv exec path /Users/masonevans/.nix-profile/bin/direnv
DIRENV_CONFIG /Users/masonevans/.config/direnv
bash_path /nix/store/cpgyi9khbv1yg2i22vg0zhmsnif9aih9-bash-4.4-p23/bin/bash
disable_stdin false
warn_timeout 5s
whitelist.prefix []
whitelist.exact map[]
Loaded RC path /Users/masonevans/Development/flake-pythonify/.envrc
Loaded watch: ".envrc" - 2021-09-21T10:54:31-06:00
Loaded watch: "../../.local/share/direnv/allow/333820b7d19679cefbbe829e9bd64414f5afc9306a0d09e082df328615e0abd3" - 2021-09-21T10:11:47-06:00
Loaded watch: "flake.nix" - 1969-12-31T17:00:00-07:00
Loaded watch: "flake.lock" - 1969-12-31T17:00:00-07:00
Loaded RC allowed false
Loaded RC allowPath
Found RC path /Users/masonevans/Development/flake-pythonify/.envrc
Found watch: ".envrc" - 2021-09-21T10:54:31-06:00
Found watch: "../../.local/share/direnv/allow/333820b7d19679cefbbe829e9bd64414f5afc9306a0d09e082df328615e0abd3" - 2021-09-21T10:11:47-06:00
Found RC allowed true
Found RC allowPath /Users/masonevans/.local/share/direnv/allow/333820b7d19679cefbbe829e9bd64414f5afc9306a0d09e082df328615e0abd3

Requires GNU grep

Issue

This isn't really an issue with nix-direnv, but more of a caveate I encountered when trying to use nix-direnv on macOS. I first encountered this using direnv-mode in emacs w/ nix-direnv on macOS, but it looks like it's also a problem just using direnv from bash on macOS.

From a directory that DOESN'T have a cached environment (i.e. .direnv either doesn't exist or is empty), the following error is shown when making a first attempt at loading the env:

usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
	[-e pattern] [-f file] [--binary-files=value] [--color=when]
	[--context[=num]] [--directories=action] [--label] [--line-buffered]
	[--null] [pattern] [file ...]

which results in the creation of an empty cache.

Setup

Directory structure:

nix-direnv-test taylor$ ls -la
total 16
drwxr-xr-x   5 taylor  staff   160 Mar 10 11:26 .
drwxr-xr-x  55 taylor  staff  1760 Mar 10 11:24 ..
drwxr-xr-x   3 taylor  staff    96 Mar 10 11:26 .direnv
-rw-r--r--   1 taylor  staff     8 Mar 10 11:24 .envrc
-rw-r--r--   1 taylor  staff    87 Mar 10 11:25 shell.nix

.direnv:

use nix

shell.nix:

let pkgs = import <nixpkgs> { };
in pkgs.mkShell {
    buildInputs = [ pkgs.hello ];
}

Steps to reproduce

nix-direnv-test taylor$ direnv allow
direnv: loading ~/Source/nix-direnv-test/.envrc
direnv: using nix
usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
	[-e pattern] [-f file] [--binary-files=value] [--color=when]
	[--context[=num]] [--directories=action] [--label] [--line-buffered]
	[--null] [pattern] [file ...]

Fix

The issue seems to be that nix-direnv is trying to invoke the macOS builtin BSD-grep at /usr/bin/grep, which for one reason or another doesn't like (in direnvrc):

    tmp=$(nix-shell --show-trace --pure "$@" --run "$dump_cmd" \
              | grep -oP '(?<=_____direnv_____).*')

I haven't actually spent any time trying to figure out WHY that line is problematic with the builtin grep, but I managed to sort this out by installing nix-direnv with the following derivation, which explicitely uses nixpkgs.gnugrep

{ bash, fetchFromGitHub, gnugrep, stdenv }:

stdenv.mkDerivation {
  name = "nix-direnv";

  src = fetchFromGitHub {
    owner = "nix-community";
    repo = "nix-direnv";
    rev = "81d3f5083ae68aec5d9f6fc9eebac57c82a9d280";
    sha256 = "067493hbsij59bvaqi38iybacqbzwx876dvdm651b5mn3zs3h42c";
  };

  phases = [ "unpackPhase" "patchPhase" "installPhase" ];

  prePatch = ''
    substituteInPlace direnvrc --replace "/usr/bin/env bash" "${bash}/bin/bash"
    substituteInPlace direnvrc --replace "grep" "${gnugrep}/bin/grep"
  '';
  
  installPhase = ''
    mkdir -p $out/share/nix-direnv
    cp -rv ./* $out/share/nix-direnv
  '';
}

Optionally move project-wise .direnv to a centralized location

Hi,

Currently, this use_nix function will create a .direnv folder along with the .envrc file. The problem is: I have some of my project stored in Dropbox, and this has 2 problems:

  1. Dropbox will mess up symblinks
  2. The cache- and drv files doesn't seem to be portable

Is it possible to add an additional environmental variable to store all .direnv in a centralized location?

Question: Is it possible to get the drv without looking at $out?

I have a shellHook that sets out=$PWD/_install (and CMAKE_INSTALL_PREFIX=...) to allow running genericBuild inside nix-shell. But this breaks nix-direnv due to $out no longer pointing into the nix store, breaking this line in direnvrc:

drv=$(nix show-derivation "$out" | grep -E -o -m1 '/nix/store/.*.drv')

Is it possible to get the drv any other way?

Error when nix-shell is an alias

After not touching some nix projects for a while and running nixpkgs updates regularly, the nix-direnv suddenly no longer functioned.

I think it is because my nix-shell command is aliased, and the lookup in direnvrc breaks on this.

$ command -v nix-shell
alias nix-shell='nix-shell --command "$(declare -p PS1); return"'

$ type -P nix-shell
/run/current-system/sw/bin/nix-shell

$ type --help
[...]
      -P	force a PATH search for each NAME, even if it is an alias,
    		builtin, or function, and returns the name of the disk file
    		that would be executed
[...]

This would be my suggested fix, I can open a PR for it if this seems like a good idea, but I don't know if I'm missing some subtlety here.

--extra-experimental-features check passes when it is not allowed

After updating to nixos-21.05 and nix 2.3.11, running direnv reload issues this warning:

warning: ignoring the user-specified setting 'experimental-features', because it is a restricted setting and you are not a trusted user

nix-direnv uses this test to check that experimental features can be enabled:

  if "${NIX_BIN_PREFIX}nix-shell" --extra-experimental-features '' --version 2>/dev/null >&2; then
    experimental_flags+=('--extra-experimental-features' 'nix-command flakes')
  fi

It appears that this test does not work:

$ NIX_BIN_PREFIX=/nix/store/nbr38zzkkypjxnq3l7w0d9wscxxwv00x-nix-2.4pre20210503_6d2553a/bin/
$ "${NIX_BIN_PREFIX}nix-shell" --extra-experimental-features '' --version
nix-shell (Nix) 2.4pre20210503_6d2553a
$ echo $?
0
$ "${NIX_BIN_PREFIX}nix-shell" --extra-experimental-features ''
warning: ignoring the user-specified setting 'experimental-features', because it is a restricted setting and you are not a trusted user
...

json.exception.parse_error on nixos-unstable-small

Using use flake on my config repo's flake-update branch causes the following error to appear:

$ direnv reload
direnv: loading ~/src/nix-config/.envrc                                                                                                                                                               
direnv: using flake
warning: Git tree '/home/bemeurer/src/nix-config' is dirty
error: [json.exception.parse_error.101] parse error at line 57, column 178: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '" \n    local fn=\"$1\";\n    local fd;\n    local magic;\n    exec {fd}< \"$fn\";\n    read -r -n 4 -u \"$fd\" magic;\n    exec {fd}>&-;\n    if [[ \"$magic\" = ''
warning: Git tree '/home/bemeurer/src/nix-config' is dirty
direnv: renewed cache
direnv: export ~XDG_DATA_DIRS

The first thing that strikes me is that it complains about my tree being dirty, even when it isn't:

$ git status   
On branch flake-update
Your branch is up to date with 'origin/flake-update'.

nothing to commit, working tree clean

If I replace use flake with use nix things seem to mostly work fine, so I suspect a bump of nixUnstable might have broken things.

This is running off of commit a878fd020e1ab88888ef72aae46d2c98d9212c79 on my repo, which is using nixpkgs commit ff748a82a5fff004c952f32eacd64604a6f4036f.

git pull doesn't work because of missing NIX_SSL_CERT_FILE

I'm using nix on macOS. In a git repo with use_nix, I get this:

➜  git pull
fatal: unable to access '<my-repo>': SSL certificate problem: unable to get local issuer certificate

➜  NIX_SSL_CERT_FILE=/Users/lukeworth/.nix-profile/etc/ssl/certs/ca-bundle.crt git pull
Already up to date.

Perhaps instead of unsetting the SSL variables, it could restore them.

nix-direnv doesn't seem to cache

Hello,

I believe I've followed all instructions at https://github.com/nix-community/nix-direnv/blob/master/README.md (Via configuration.nix in NixOS), and although nix-direnv is giving me correct results, it seems to want to re-evaluate my shell.nix every time I cd into the directory. Is there a way to debug what is causing it to not reuse a previous result? What settings should I check?

$ nixos-option nix.extraOptions
Value:
''
  keep-outputs = true
  keep-derivations = true
''

Default:
""
(...)

$ nixos-option environment.pathsToLink
Value:
[
  "/share/nix-direnv"
(...)

I do notice that /share/nix-direnv does not exist, is that a problem?

Thank you

`use flake` on macOS fails due to missing `realpath`

I'm trying nixUnstable to tinker with flakes, and hence tried use flake in my .envrc. When I cd into the directory I get the following:

❯ cd ulidgen
direnv: loading ~/src/github.com/jamesottaway/ulidgen/.envrc
direnv: using flake
warning: Git tree '/Users/james/src/github.com/jamesottaway/ulidgen' is dirty
/nix/store/zqyb1i0phqpf2gkg7yna8v4i2p4c3zf4-nix-direnv-1.1/share/nix-direnv/direnvrc:69: realpath: command not found
ln: /Users/james/src/github.com/jamesottaway/ulidgen/.direnv/flake-profile: Invalid argument
direnv: renewed cache
direnv: export +AR +AS +CC +CONFIG_SHELL +CXX +HOST_PATH +IN_NIX_SHELL +LD +LD_DYLD_PATH +MACOSX_DEPLOYMENT_TARGET +NIX_BINTOOLS +NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_apple_darwin +NIX_BUILD_CORES +NIX_CC +NIX_CC_WRAPPER_TARGET_HOST_x86_64_apple_darwin +NIX_CFLAGS_COMPILE +NIX_COREFOUNDATION_RPATH +NIX_DONT_SET_RPATH +NIX_DONT_SET_RPATH_FOR_BUILD +NIX_ENFORCE_NO_NATIVE +NIX_HARDENING_ENABLE +NIX_IGNORE_LD_THROUGH_GCC +NIX_INDENT_MAKE +NIX_LDFLAGS +NIX_NO_SELF_RPATH +NIX_STORE +NM +NODE_PATH +PATH_LOCALE +RANLIB +SIZE +SOURCE_DATE_EPOCH +STRINGS +STRIP +__darwinAllowLocalNetworking +__impureHostDeps +__propagatedImpureHostDeps +__propagatedSandboxProfile +__sandboxProfile +buildInputs +builder +configureFlags +configurePhase +depsBuildBuild +depsBuildBuildPropagated +depsBuildTarget +depsBuildTargetPropagated +depsHostHost +depsHostHostPropagated +depsTargetTarget +depsTargetTargetPropagated +distPhase +doCheck +doDist +doInstallCheck +dontAddDisableDepTrack +gl_cv_func_getcwd_abort_bug +installPhase +name +nativeBuildInputs +node_modules +out +outputs +patches +pname +propagatedBuildInputs +propagatedNativeBuildInputs +shell +src +stdenv +strictDeps +system ~PATH

I do have realpath, however:

❯ which realpath
/nix/store/96yx22s06r1y7rcp1lyz25q8j1ymwmng-coreutils-8.32/bin/realpath

Does not work this `strict_env` option enabled

I've run into this bug and I'm starting to think the problem is on nix-direnv. My .envrc looks like this:

set -x
use_nix

When I run it I get:

direnv: loading ~/.envrc                                                                                                    
++ use_nix
++ local path direnv_dir
+++ nix-instantiate --find-file nixpkgs
++ path=~/.nix-defexpr/channels/nixpkgs
+++ direnv_layout_dir
+++ echo ~/.direnv
++ direnv_dir=~/.direnv
++ [[ direnv == '' ]]
++ local version
++ [[ -f ~/.nix-defexpr/channels/nixpkgs/.version-suffix ]]
++ read -r version
+ __dump_at_exit
+ local ret=1
+ direnv dump json ''
+ trap - EXIT
+ exit 1
direnv: error exit status 1

MacOS - Migration from `direnv`

Hello,

I've been using direnv for some times now and I wanted to use nix-direnv to benefit from the caching mechanism but I can't figure out why it does not work on my side.
It looks like it keeps using direnv whereas I tried to install and configure nix-direnv following the documentation.

  • I updated my project .envrc file as below:
use nix
  • I installed nix-direnv using nix-env and tried but I still get the following output:
  • I ran direnv allow in my project directory
  • Result = It keeps using direnv as before:
➜  projects cd my-project
direnv: loading ~/projects/my-project/.envrc
direnv: using nix
direnv: ([/Users/Remi/.nix-profile/bin/direnv export zsh]) is taking a while to execute. Use CTRL-C to give up.
direnv: export +API_MGT_HOST +AR +AR_FOR_TARGET +AS +AS_FOR_TARGET +CC +CC_FOR_TARGET +CLIENT_ID +CLIENT_SECRET +CONFIG_SHELL +CXX +CXX_FOR_TARGET +DATA_DICTIONARY_X_API_KEY +DETERMINISTIC_BUILD +GRAFANA_ADMIN_PASSWORD +GRAFANA_ADMIN_USER +HOST_PATH +INFLUXDB_PASSWORD +IN_NIX_SHELL +LD +LD_DYLD_PATH +LD_FOR_TARGET +LOCALES +MACOSX_DEPLOYMENT_TARGET +MASTER_DATA_X_API_KEY +NIX_BINTOOLS +NIX_BINTOOLS_FOR_TARGET +NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_apple_darwin +NIX_BINTOOLS_WRAPPER_TARGET_TARGET_x86_64_apple_darwin +NIX_BUILD_CORES +NIX_BUILD_TOP +NIX_CC +NIX_CC_FOR_TARGET +NIX_CC_WRAPPER_TARGET_HOST_x86_64_apple_darwin +NIX_CC_WRAPPER_TARGET_TARGET_x86_64_apple_darwin +NIX_CFLAGS_COMPILE +NIX_CFLAGS_COMPILE_FOR_TARGET +NIX_COREFOUNDATION_RPATH +NIX_DONT_SET_RPATH +NIX_DONT_SET_RPATH_FOR_BUILD +NIX_ENFORCE_NO_NATIVE +NIX_HARDENING_ENABLE +NIX_IGNORE_LD_THROUGH_GCC +NIX_INDENT_MAKE +NIX_LDFLAGS +NIX_LDFLAGS_FOR_TARGET +NIX_NO_SELF_RPATH +NIX_STORE +NM +NM_FOR_TARGET +PATH_LOCALE +PYTHONHASHSEED +PYTHONNOUSERSITE +PYTHONPATH +RANLIB +RANLIB_FOR_TARGET +SDKROOT +SIZE +SIZE_FOR_TARGET +SOURCE_DATE_EPOCH +STRINGS +STRINGS_FOR_TARGET +STRIP +STRIP_FOR_TARGET +TEMP +TEMPDIR +TMP +__CF_USER_TEXT_ENCODING +__darwinAllowLocalNetworking +__impureHostDeps +__propagatedImpureHostDeps +__propagatedSandboxProfile +__sandboxProfile +buildInputs +builder +configureFlags +depsBuildBuild +depsBuildBuildPropagated +depsBuildTarget +depsBuildTargetPropagated +depsHostHost +depsHostHostPropagated +depsTargetTarget +depsTargetTargetPropagated +doCheck +doInstallCheck +gl_cv_func_getcwd_abort_bug +name +nativeBuildInputs +nobuildPhase +out +outputs +patches +phases +propagatedBuildInputs +propagatedNativeBuildInputs +shell +shellHook +stdenv +strictDeps +system ~NIX_PATH ~PATH

I also tried to install it "from source" as explained in the documentation but I got the same result in the end.

Here are more details about my nix-env installed packages:

cachix-0.3.7
direnv-2.21.3
nix-2.3.7
nix-direnv-1.1
nss-cacert-3.49.2

I must have mis-installed something as I am new to nix stuff so any help debugging my problem is very much appreciated!

Thank you!

watch_file doesn't invalidate the cache

I am trying to use watch_file to also reload the environment if a file that is imported in shell.nix changes.

Setup

.envrc

use_nix
watch_file shell2.nix

shell.nix

import ./shell2.nix

shell2.nix

with (import <nixpkgs> {});
mkShell {
  buildInputs = [
    hello
  ];
}

Test

If I change shell2.nix and press enter direnv starts:

direnv: loading ~/Development/nix-direnv-test/.envrc

But nix-direnv says:

direnv: using cached derivation

I need to explicitly call touch .envrc to get the updated environment.

Can this be fixed?

New direnvrc is constantly re-evaluating

I've started seeing an issue when using this integration through home-manager. A recent change seems to have caused it to re-evaluate the cache constantly - upon entering a directory with an .envrc file containing use nix, I see the following every time the prompt is redrawn:

loading ~/<project-dir>/.envrc
renew cache in background

I see that along with any output my shell hook would show in my shell.nix - which for some of my projects is a LOT of output if it, say, builds a go environment or caches vendored dependencies.

nix-direnv is always using cache/unknown

I only ever see .direnv/cache-unknown and looking at the source i don't quite understand how it could be any different:

$ nix-instantiate --find-file nixpkgs
/nix/store/plaxbbv04m996smsi6gaqgx2lvb2yz0j-356pa04sqir8ycxni9pd0c8j9qv2z4v0-source

There is neither a version-suffix file (where would that come from? nixpkgs only has a .version file doesn't it?) and there is no .git directory because it's not a working copy.

Terribly sorry if i am somehow completely missing the point in some regard but i don't quite understand what's going on or if I am perhaps just "holding it wrong" :)

How to revalidate cache for git+ssh

I use flakes and try to use a private flake from my private github repo as such:

use flake git+ssh://[email protected]/anilanar/home.nix.git#shells.nix

However I have no clue how to revalidate the cache after I push something to the repo. In theory, I can use specific revisions but I don't want to do that if possible.

Using direnv with flakes builds a recursive source tree

Every time you make a change that triggers a direnv rebuild, it generates a .direnv/flake symlink that points to the application source tree in the nix store /nix/store/*-source/. The problem is that after the first rebuild, it starts including this symlink in the nix store source directory itself. This keeps happening recursively until you have paths like .direnv/flake/.direnv/flake/.direnv/flake etc. This causes various text editors to explode unless you specifically configure it to ignore .direnv.

It's not a big issue and can be worked around easily in most editors, but I'm wondering if this could somehow be avoided in the first place.

flake build error wasn't surfaced until I manually ran `nix-shell`

I've got something messed up in my flake.nix. I think nix-direnv is sort of hiding it from me:


> cd code/nixpkgs-wayland
cd: no such file or directory: code/nixpkgs-wayland
direnv: loading ~/code/nixpkgs-wayland/.envrc                                                                                                                                     
direnv: using flake
warning: Git tree '/home/cole/code/nixpkgs-wayland' is dirty
error: --- SysError ---------------------------------------------------------------------------------------------------------------------------------------------------------- nix
getting attributes of path '/nix/store/pbcaa4p55p11x7f1hb53iknzmi2vhm33-source': No such file or directory
(use '--show-trace' to show detailed location information)
direnv: renewed cache

> nix-shell
warning: Git tree '/home/cole/code/nixpkgs-wayland' is dirty
error: --- ThrownError ------------------------------------------------------------------------------------------------------------------------------------------------- nix-shell
flake input has unsupported input type 'path'
(use '--show-trace' to show detailed location information)

Add substituters support

For some projects I need to configure substituters.
cachix use is suboptimal due to not being pure (edits local nix.conf).

I propose adding something along the lines of

use nix-cache PATH
use nix-key PUBKEY

which would parse current system and environment substituters, add ones from command line opts, and collect them for later use in use nix

`direnv export json` writes nothing when using `use nix`

I'm trying to use nix-direnv inside https://github.com/wbolster/emacs-direnv, and it's not setting any env variables with the following config files:

.envrc:

use nix

shell.nix:

with import <nixpkgs> { };

let
  pythonPkg = pkgs.python39;
  pythonPkgs = pkgs.python39Packages;
in
stdenv.mkDerivation rec {
  name = "my-env-derivation";
  buildInputs = with pkgs; [
    pythonPkg
    pkgconfig
    pythonPkgs.black
    pythonPkgs.isort
    pythonPkgs.pip
    pythonPkgs.setuptools

    # pip install dependencies:
    openssl
  ];
  shellHook = ''
    if ! [ -d venv ] ; then
      ${pythonPkgs.virtualenv}/bin/virtualenv venv
    fi;
    . venv/bin/activate
  '';
}

Activating that direnv on the shell works perfectly - which pkg-config returns the right path.

Unfortunately, emacs's direnv-mode doesn't think so. After using M-x direnv-allow, it claims there are no diffs to the current environment. That strikes me as odd, but then if I run the following on the shell, it gets confirmed:

$ direnv export json
$

However, running it with a completely empty environment at least makes direnv export json print something:

$ env -i HOME=/Users/asf /Users/asf/.nix-profile/bin/direnv export json 2>/dev/null
{
  "DIRENV_DIFF": "eJxUkU-PmkAcQL_L7wyBiq5AsoeR_yrsLANKvUwQsUMFdmCgiMbv3uyhhx5f8k7vPYGD-XxJ0IL5BDuInehA7SAGE2QlFWUvlFxcFT8vbkKpFiD9c44osXyHgAnldg4furG72-jzF3a1-XxTQ7XRkkxkfxArcdD4walh04VZ216M1Qcd50QXlrzcU1zJq4k-iKf-qNYunut06C5sXXVGJ9ahcX4r8uRYlMaQzN5KuPH9ij5O1T3Urm3vaJE6djFeD33q0gUJs47wwzDzo3Z7OxCjLc5LG21jpm-2q3yDHZ3E7aeFvnbpvW6tyENE33h6umEFd-umnU5o8q16LtyJGBhn3o79XLRGLQwaXZnLgl7m8u8dP0y5pmZy4fqqzlKEMKVLgz84en8HCYKIRkFGie_s92BC1fCxL0ECjBIfTFDaL1mMBZN5PjDzPwIJEicOwYTL2JxBgsz2qI0S9D3kuzS8Xn8DAAD__6jLihE=",
  "DIRENV_DIR": "-/Users/asf/Hacks/i2",
  "DIRENV_WATCHES": "eJyMz89KxDAQgPF3ybk0M0m3TXsXvAhePImHIZmhwdhCJrsuiO_uyT8sC-4L_Pi-5w_zSG01i7FPylUtqdh7iq9qs7M9b6caTWce9tTyG5sFRxfAOZixM3fnrE3N0uqRP7trUF_2SMXqSpVtypW3k6VS9ncb4DAJRh8BJ5aBPE8SRnQCAoKUxlnCNGAS8BG8UBhcpFlmnwZAwHClycFwS9PPXGKhY2n9ls9_NfhFhIr-p-jKpVwa30X-cFH08hUAAP__49pzpA==",
  "IN_NIX_SHELL": "impure",
  "PATH": "/no-such-path:/no-such-path",
  "TERM": "dumb",
  "XDG_DATA_DIRS": ""
}%

Not completely sure how to read this, but it sounds like PATH is not getting set in a reasonable way?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.