Emacs integration for nix-prefetch to update source hashes

I put together some pretty basic helper function that insert an updated
hash of a derivation from within emacs.
It is based on the awesome nix-prefetch

  (defun shell-stdout-to-string (command)
    (with-output-to-string
      (with-current-buffer
          standard-output
        (process-file shell-file-name nil '(t nil)  nil shell-command-switch command))))

  (defun insert-nix-hash (attribute)
    (interactive "sNix attribute to fetch")
    (let ((hash (shell-stdout-to-string (concat "nix-prefetch " attribute))))
      ;; replace current selection → can we detect the hash under the cursor as well?
      (if (use-region-p)
          (kill-region (region-beginning)
                       (region-end)))
      (insert (string-trim-right hash))))

  ;; optional if you are using spacemacs
  ;(spacemacs/set-leader-keys "xn" 'insert-nix-hash)

Basic usage:

M-x insert-nix-hash RET hello RET

where hello is the package name you want to get the hash for.
See nix-prefetch for further usage example.

As I said the function is currently pretty basic. If you are an experienced lisper,
don’t hesitate to post improved version of my code here. In particular
it would be interesting to automatically guess the attribute name and
also find the source hash position.

1 Like

Thanks! That looks very useful!

I have been wanting to try this for a while, but John Wiegley also has an Emacs package for updating a hash:

1 Like