2

Is there a robust way, maybe something in cargo CLI, to get the version of the crate?

I can grep on Cargo.toml, but I'm looking for something that won't break in 6 months.

Is there a better way?

SwimBikeRun
  • 4,192
  • 11
  • 49
  • 85
  • 1
    What do you need this for? Have you tried `cargo tree --depth 0`? – PitaJ Jan 05 '23 at 18:59
  • 1
    Are you needing just a number (well a string, since a number cant have multiple periods) or are you fine with a tiny bit of extra data? `cargo pkgid` gives `files:///Users/sus/code/project#0.1.0` – Samathingamajig Jan 05 '23 at 19:02
  • 1
    There's also `cargo metadata`, but it is verbose and not geared to the current package if you're in a workspace. – kmdreko Jan 05 '23 at 19:17
  • 1
    If you need it in a build.rs script or embedded in an application, there's a [`CARGO_PKG_VERSION`](https://stackoverflow.com/questions/27840394/how-can-a-rust-program-access-metadata-from-its-cargo-package) environment variable. – kmdreko Jan 05 '23 at 19:18
  • @Samathingamajig you should probably post that as an answer since it is the most direct and requires trivial trimming (can be done with `cut -d "#" -f2` for example) – kmdreko Jan 05 '23 at 19:33

2 Answers2

4

The general way to get metadata about your package or workspace is via the cargo metadata command, which produces a JSON output with your workspace packages, dependencies, targets, etc. However it is very verbose.

If you are not in a workspace, then you can simply get the version of the first package excluding dependencies (parsing with jq):

> cargo metadata --format-version=1 --no-deps | jq '.packages[0].version'
"0.1.0"

If you are in a workspace however, then there will be multiple packages (even after excluding dependencies) and appears to be in alphabetical order. You'd need to know the package's name:

> cargo metadata --format-version=1 --no-deps | jq '.packages[] | select(.name == "PACKAGE_NAME") | .version'
"0.1.0"
kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • When using `jq` you might also want to use `--raw-output` to remove the quotes around the version number. Maybe would also be good to set `--exit-status` to fail if (for some reason) the version number could not be extracted. See also the [`jq` manual](https://stedolan.github.io/jq/manual/). – Marcono1234 Apr 22 '23 at 13:55
3

The simplest answer is

cargo pkgid

This outputs

files:///Users/sus/code/project#0.1.0

If you want this as just the version part, you can pipe this to cut (or handle it yourself in your programming language of choice)

cargo pkgid | cut -d "#" -f2
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34