You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在编译时获取已克隆Git仓库的标签

编译时获取Git仓库最新标签(含提交哈希优化)

核心实现逻辑

通过Git命令获取仓库元信息,在build.rs中注入环境变量供主程序调用:

  • 用git describe --tags --abbrev=0获取仓库最新标签,同时处理无标签的异常场景
  • 优化原有提交哈希获取逻辑,去除多余换行符,可选生成短哈希

修改后的build.rs代码

// build.rs
use std::process::Command;

fn main() {
    // 获取最新提交哈希(添加--short可生成短哈希,按需选择)
    let hash_output = Command::new("git")
        .args(&["rev-parse", "--short", "HEAD"])
        .output()
        .expect("执行git命令失败,请确认当前目录是Git仓库且已安装Git");
    let git_hash = String::from_utf8(hash_output.stdout)
        .expect("git输出非UTF-8格式")
        .trim()
        .to_string();
    println!("cargo:rustc-env=GIT_HASH={}", git_hash);

    // 获取最新标签,处理无标签场景
    let tag_output = Command::new("git")
        .args(&["describe", "--tags", "--abbrev=0"])
        .output();
    let git_tag = match tag_output {
        Ok(output) if output.status.success() => {
            String::from_utf8(output.stdout)
                .expect("标签输出非UTF-8格式")
                .trim()
                .to_string()
        }
        _ => "无可用标签".to_string(), // 无标签时的默认值,可按需修改
    };
    println!("cargo:rustc-env=GIT_TAG={}", git_tag);
}

主程序main.rs调用示例

// main.rs
fn main() {
    println!("当前提交哈希: {}", env!("GIT_HASH"));
    println!("最新标签: {}", env!("GIT_TAG"));
}

注意事项

  • 确保编译环境已安装Git,且编译目录处于Git仓库内
  • 若需要获取带提交偏移的标签(如v1.0.0-5-gabc123),移除--abbrev=0参数即可
  • 无标签时的默认值可根据需求调整,比如改为空字符串""

内容的提问来源于stack exchange,提问作者Harry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:36:00