How to make dune include version number in a library module

Hello,

sorry if this is obvious but I could not find the way to achieve this.

I would like to include the version number of my library in a module of this library, so that it can be accessed for example with .Version.number .

Is this possible ?

I found this solution in opam-publish:
opam-publish/dune at 08d69c0ff50018455f54523187203c45efa18128 · ocaml-opam/opam-publish · GitHub

My first attempt was:


(rule
 (target version.ml)
 (deps %{version:stog})
 (action
  (write-file %{target} "let number = \"%{version:stog}\"")
 )
)

but I got this message:

Error: No rule found for lib

Removing the (deps ...) field makes it work.

1 Like

Dune has dune subst: Command-line interface — dune documentation

It’ll substitute markers like this with the output of git describe:

let version = "%%VERSION%%"

However, this is supposed to be substituted only in the release tarball generated by dune-release. (or when the package is pinned in Opam: OPAM integration — dune documentation)

The version variable will still be literally "%%VERSION%%" unless dune subst is called before building. Your version.ml approach might be better if you want every builds to have the version string substituted.

For the %{version:...} variable, that’s how Dune determines the version of packages: Other topics — dune documentation
The documentation for the variable says:

Note that this is only supported for packages that are being defined in the current scope

The deps field is unnecessary in your code, it’s supposed to contain things that can be built (files, packages), a version string doesn’t make sense here.

1 Like

I think you could use dune-build-info package.

See how ocaml-lsp uses it here: ocaml-lsp/version.ml at master · ocaml/ocaml-lsp · GitHub

1 Like

Thanks for your answers. I’ll use the dune-build-info based solution :slight_smile: