Adding flags to retrieve only name, version or url from cargo pkgid

Since cargo doesn’t support post build scripts, I’m running cargo in a Makefile to compile my project and run scripts afterwards. One of the steps involved is moving the target binaries which requires the name of the crate. However, at the moment there doesn’t seem to be a straightforward way to get a name of the current crate. Currently, two options are either parsing the Cargo.toml file or running cargo pkgid and parsing the Package ID spec.

Since pkgid already keeps name, version and url in the PackageIDSpec struct internally and those fields are also available to regular build scripts (in the form of environment variables), it would be useful for external tools if additional flags were added to the pkgid command to only retrieve one of the components of the spec. This could be implemented by e.g. mutually exclusive --name, --version and --url flags which print the respective parts of the spec to stdout.

There’s a third option that might give you what you need in a parseable format: cargo read-manifest. It gives you the manifest as JSON data, which you can then parse using jq or other tools:

❯ cargo read-manifest | jq '[.name, .version]'

IMO that’s much more flexible than adding individual flags. Would this suit your needs?

I agree that this is more flexible since it also allows access to other information from the manifest - but it still requires installing external tools. Adding the functionality to get a subset from read-manifest directly would be very nice though and probably more useful than extending pkgid.

You can use --message-format=json to get the build output in JSON format. This includes artifact objects, which specify the location of all built binaries. You still have to parse the JSON, but this approach also works when overriding the target directory or building projects with multiple executables.