womble
womble

Reputation: 12407

How to tell Cargo to use git tags to determine the crate version?

I'm chewing through the Rust book, and learning about Cargo. In the description of the Cargo.toml format, it seems to require that you hard-code the version you're currently working on or have most recently released into that file, which is checked into revision control. Since anyone sane tags their releases, this means that the version information is duplicated, and we all know what a bad idea it is to have the same information in two places.

Given that Cargo seems admirably opinionated on the subject of revision control (creating a git repo on cargo new), I'm a bit surprised that I can't find a way to tell Cargo, "grab version information from the annotated tags in the repo". Am I missing something, or is this a feature that is just out-and-out missing from Cargo entirely?

Upvotes: 9

Views: 2901

Answers (2)

womble
womble

Reputation: 12407

To close the loop on this, I've started just doing things the brutal way and setting a "fake" version in Cargo.toml, and then during release builds (done via GitHub Actions) doing a bit of light sed to set the real version number, like this:

  - name: Set Cargo.toml version
    shell: bash
    env:
      RELEASE_TAG: ${{ github.ref }}
    run: |
      mv Cargo.toml Cargo.toml.orig
      sed "s/0\\.0\\.0-git/${RELEASE_TAG##*\/v}/" Cargo.toml.orig >Cargo.toml
      mv Cargo.lock Cargo.lock.orig
      sed "s/0\\.0\\.0-git/${RELEASE_TAG##*\/v}/" Cargo.lock.orig >Cargo.lock

Then leave Cargo.toml like this:

[package]
version = "0.0.0-git"

It's ugly, but it works.

Upvotes: 10

ozkriff
ozkriff

Reputation: 1359

crates.io stores full snapshots of crates' sources without any VCS meta-information. So this information about the crate must be encoded in Cargo.toml which is a part of a snapshot.

There's also an old issue about the idea of a reversed approach: make cargo subcommands create git tags when publishing a new version on crates.io.

Upvotes: 0

Related Questions