How to get an .ocamlinit file per [ switch | project ]?

How do you manage your ~/.ocamlinit file with several switches?

In other words, in the context of a growing number of opam switches with very different sets of libraries within a same machine, how can we get something like an .ocamlinit file related to one switch?

Of course, one solution is to create a dedicated toplevel with all libraries with ocamlmktop or to use dune utop

See https://dune.readthedocs.io/en/latest/usage.html?highlight=utop#launching-the-toplevel-repl

See https://discuss.ocaml.org/t/tips-on-building-a-custom-toplevel-with-jbuilder-and-utop/545 and related https://github.com/ocaml/dune/issues/114

Is there something simpler?

First:


Happy New Year to all OCamlers!


In fact, this simple and stdlib-based solution works:

#use "/home/test/dev/stuff/stuff.ocamlinit"

File is named stuff.ocamlinit instead of .ocamlinit to keep clear (and avoid a possible confusion with ~/.ocamlinit).
Is there any convention?

And its functional equivalent:

Topdirs.dir_use Format.std_formatter
( Filename.concat (Sys.getcwd ())  ".ocamlinit" )

…assuming we launch the Toplevel from the stuff/ directory where we have the stuff.ocamlinit file (with a test on Sys.getcwd () and a Sys.chdir if needed).

BTW, it may be useful to use ~/.ocamlinit as well, assuming it has only some common setup and no specific OCaml directives:

 #use "/home/test/.ocamlinit"

I’ve found a ~/.ocamlinit file content which adjusts ocaml dynamically to the current opam switch loaded. For this, opam install opam-client is needed first (if not already installed).
Source (by “AltGr”) can be found here:
https://github.com/ocaml/opam/blob/master/.ocamlinit
Then utop, while switch 4.09.1 ocaml-base-compiler.4.09.1 is active:

Welcome to utop version 2.4.3 (using OCaml version 4.09.1)
Findlib has been successfully loaded. Additional directives:
#require “package”;; to load a package
list;; to list the available packages
#camlp4o;; to load camlp4 (standard syntax)
#camlp4r;; to load camlp4 (revised syntax)
#predicates “p,q,…”;; to set these predicates
Topfind.reset();; to force that packages will be reloaded
#thread;; to enable threads

Opam global state for /home/hape/.opam loaded in ‘gt’
Opam repository state loaded in ‘rt’
Opam switch state of ‘4.09.1’ loaded in ‘st’