Skip to content

For git SHA and dirty, use .cargo_vcs_info.json if in a published crate #448

@hgomersall

Description

@hgomersall

Apparently using a published crate populates VERGEN_GIT_SHA and VERGEN_GIT_DIRTY with the default (idempotent) output.

Shameless stealing from https://github.com/fedimint/fedimint/pull/3735/files, the following example in my build.rs might be a better option (perhaps enabled optionally):

use std::error::Error;
use vergen_git2::{Emitter, Git2Builder};

fn main() -> Result<(), Box<dyn Error>> {

    if let Ok(file) = std::fs::File::open("./.cargo_vcs_info.json") {
        let info: serde_json::Value = serde_json::from_reader(file)
            .map_err(|e| format!("Failed to parse .cargo_vcs_info.json: {}", e))?;
        let hash = info["git"]["sha1"].as_str().ok_or_else(|| {
            format!(
                "Failed to parse .cargo_vcs_info.json: no `.git.sha` field: {:?}",
                info
            )
        })?;
        let dirty = info["git"]["dirty"].as_bool().ok_or_else(|| {
            format!(
                "Failed to parse .cargo_vcs_info.json: no `.git.dirty` field: {:?}",
                info
            )
        })?;
        println!("cargo:rustc-env=VERGEN_GIT_DIRTY={dirty}");
        println!("cargo:rustc-env=VERGEN_GIT_SHA={hash}");
        return Ok(());
    } else {
        let gitcl = Git2Builder::default()
            .dirty(false)
            .sha(false)
            .build()?;

        Emitter::default()
            .add_instructions(&gitcl)?
            .emit()?;
    }
    Ok(())
}

This uses .cargo_vcs_info.json which is provided in the crate.

Interestingly, Gemini is convinced Vergen already supports this, though my investigation fell short, hence this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions