Skip to content

Instantly share code, notes, and snippets.

@zph
Last active March 30, 2017 16:29
Show Gist options
  • Save zph/50c766d6c7aa212896b5 to your computer and use it in GitHub Desktop.
Save zph/50c766d6c7aa212896b5 to your computer and use it in GitHub Desktop.
(require 'cl-lib)
;; Depends on s.el
(defun direnv-data (dir)
;; TODO: use dir for folder or smart current-project-dir variable
(let ((cmd (concat "$SHELL -i -c '" "cd " dir " && direnv export bash'")))
(shell-command-to-string cmd)))
;;(direnv-data "~/src/direnv")
(defun commands-from-direnv (text)
(cl-remove-if 's-blank?
(split-string (first (last (split-string text "\n"))) ";")))
(defun line->pair (line)
(split-string (string-join (rest (split-string line " ")) " ") "="))
(defun remove-$-and-quotes (val)
(s-with val
(s-chop-prefix "$")
(s-chop-prefix "'")
(s-chop-suffix "'")
(s-chop-prefix "\"")
(s-chop-suffix "\"")))
(defun line->kv (line)
(let* ((pair (line->pair line))
(key (first pair))
(value (remove-$-and-quotes (first (last pair)))))
(list key value)))
(defun is-export? (str)
(s-starts-with? "export" str))
(defun is-ignored-key? (ls)
(let ((key (first ls)))
(or
(s-starts-with? "DIRENV" key)
(s-starts-with? "PATH" key))))
(defun extract-exports (cmds)
(mapcar 'line->kv
(cl-remove-if-not 'is-export?
(commands-from-direnv cmds))))
(defun commands->list (cmds)
(let ((exports (extract-exports cmds)))
(cl-remove-if 'is-ignored-key? exports)))
(defun setenv-pair (pair)
(let* ((k (first pair))
(v (first (last pair))))
(setenv k v)))
(defun set-env-from-direnv (dir)
(let* ((data (direnv-data dir))
(pairs (commands->list data)))
(mapcar 'setenv-pair pairs)))
;;(getenv "TEST_ENV")
;;(set-env-from-direnv "~/src/direnv")
@zph
Copy link
Author

zph commented Mar 30, 2015

Loads export statements from direnv for specific directory into emacs ENV settings.

Doesn't yet unload keys.

@5t111111
Copy link

Thank you! This is exactly what I am looking for.
However, I had to change the below line to make it work, because string-join doesn't exist.

(defun line->pair (line)
  (split-string (string-join (rest (split-string line " ")) " ") "="))

to:

(defun line->pair (line)
  (split-string (s-join " " (rest (split-string line " "))) "="))

@wbolster
Copy link

nowadays https://github.com/wbolster/emacs-direnv should be used instead

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