Newbie tip: using multiple projects/switches from command line and emacs

Just a random newbie emacs/opam/OCaml tip from my recent project setup travails re using multiple OPAM switches that I wish I could have googled:

  • I’ve used tuareg-opam-update-env to change between opam switches in emacs (I think this does everything necessary to select a different opam switch – at least nothing seems broken right now!)
  • From the command line I’m using this little wrapper script which I call inopam
#!/bin/bash

set -e

switch="$1"
shift
exec opam exec --switch "$switch" --set-switch --set-root -- "$@"

To be used like this:

$ opam switch show
4.06.1
$ inopam 4.12.0 opam switch show
4.12.0
1 Like

I find this useful to stuff into a .bashrc someplace

function refresh_switch {
 eval $(opam env)
}

so whenever I change the switch, I run refresh_switch.

I use https://direnv.net/ to do this for me. It also integrates with emacs.

1 Like

All good solutions.

Personally I picked up the habit from a colleague years ago of encoding needed context in my command line history (working directory, environment, etc.), which works well with prefix commands like this (and works even when you have variations that aren’t simply a function of current working directory).

Just out of curiosity: I notice that tuareg-opam-update-env doesn’t set OPAMROOT. I recall having to set that manually in emacs, though I don’t remember what didn’t work without it. Does anybody know why that emacs command doesn’t set it?