How to tell the version number of the Rust crate I'm in?
Asked Answered
L

2

5

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?

Lindo answered 5/1, 2023 at 18:49 Comment(4)
What do you need this for? Have you tried cargo tree --depth 0?Abhorrent
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.0Ojeda
There's also cargo metadata, but it is verbose and not geared to the current package if you're in a workspace.Staggard
If you need it in a build.rs script or embedded in an application, there's a CARGO_PKG_VERSION environment variable.Staggard
O
5

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
Ojeda answered 5/1, 2023 at 20:4 Comment(0)
S
7

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"
Staggard answered 5/1, 2023 at 19:24 Comment(1)
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.Jokjakarta
O
5

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
Ojeda answered 5/1, 2023 at 20:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.