如何告诉 Cargo 使用 git 标签来确定 crate 版本?

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

我正在仔细阅读 Rust 书,并学习 Cargo。在 Cargo.toml 格式的描述中,它似乎要求您将当前正在使用或最近发布的版本硬编码到该文件中,该文件已检入修订控制。由于任何理智的人都会标记他们的发布,这意味着版本信息是重复的,我们都知道在两个地方拥有相同的信息是多么糟糕的主意。

考虑到 Cargo 似乎对修订控制主题(在 cargo new 上创建 git 回购协议)持有令人钦佩的自以为是,我有点惊讶我无法找到一种方法来判断货物,"grab version information from the annotated tags in the repo"。我是不是遗漏了什么,或者这是 Cargo 完全缺少的功能?

crates.io stores full snapshots of crates' sources without any VCS meta-information。因此,关于板条箱的信息必须编码在 Cargo.toml 中,它是快照的一部分。

还有 an old issue 关于反向方法的想法:在 crates.io 上发布新版本时让 cargo 子命令创建 git 标签。

为了结束这个循环,我开始以残酷的方式做事并在 Cargo.toml 中设置一个“假”版本,然后在发布构建期间(通过 GitHub Actions 完成) 稍微 sed 设置真实的版本号,像这样:

  - 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

然后像这样离开Cargo.toml

[package]
version = "0.0.0-git"

虽然丑陋,但确实有效。