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?
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?
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
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"
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 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
© 2022 - 2025 — McMap. All rights reserved.
cargo tree --depth 0
? – Abhorrentcargo pkgid
givesfiles:///Users/sus/code/project#0.1.0
– Ojedacargo metadata
, but it is verbose and not geared to the current package if you're in a workspace. – StaggardCARGO_PKG_VERSION
environment variable. – Staggard