Have Emacs set environment variables defined in a project’s .envrc.
The newer emacs-direnv project takes a slightly different approach, which solves some of the drawbacks of this solution. I encourage you to try it out.
When working at the terminal, I use direnv to export environment variables that alter the behavior of the 12 factor applications I write. direnv automatically exports the variables to the environment when you cd into a directory containing a .envrc file.
When launching a GUI instance of Emacs (not from the terminal), direnv never gets the chance to export your environment variables, however.
This package contains a command projectile-direnv-export-variables which will look for a .envrc file in the projectile-project-root.
It will then parse the .envrc file for exports and call setenv in the Emacs environment. This is useful, for instance, when launching processes from within Emacs (e.g. REPLs) that depend on the values in these variables.
This package is available on MELPA as projectile-direnv
The easiest way to use this package is to invoke projectile-direnv-export-variables from a hook:
(add-hook 'projectile-mode-hook 'projectile-direnv-export-variables)
You should only do this if you work on one project with a .envrc file at a time. This is because Emacs’ environment is a global one, and projectile mode is per-buffer. It is easily conceivable to visit a file in one project and load envvars whose names clash with those in another project. This will cause a last-project-wins scenario that could lead to confusion and frustrated debugging.
There are two ways to address this concern.
- Explicitly invoke the command (instead of using a hook)
- Name your environment variables uniquely with a project prefix
- This package doesn’t yet handle variable unloading
- Ideally, the user should be prompted to allow a particular .envrc just as direnv does (and Emacs does when loading from .dir-locals.el)
Copyright (C) 2016 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.