6

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?

4
  • 1
    What do you need this for? Have you tried cargo tree --depth 0? Commented Jan 5, 2023 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 Commented Jan 5, 2023 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. Commented Jan 5, 2023 at 19:17
  • 1
    If you need it in a build.rs script or embedded in an application, there's a CARGO_PKG_VERSION environment variable. Commented Jan 5, 2023 at 19:18

2 Answers 2

10

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"
Sign up to request clarification or add additional context in comments.

1 Comment

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.
8

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

2 Comments

Note that if package.name in Cargo.toml is different than the project folder name, the output will be slightly different: path+file:///Users/sus/code/folder_name#[email protected]
cargo pkgid | awk -F'[#@]' '{print $NF}' should work regardless of folder name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.