aboutsummaryrefslogtreecommitdiff
path: root/build.rs
blob: 20c813ad9ae350a88809bbc04a7eb97bc57c03e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use anyhow::Result;
use vergen_gix::{Build, Cargo, Emitter, Gix};

/// Fallback used when the crate is built outside a git checkout (e.g. from a
/// packaged `.crate` file), so `env!("VERGEN_GIT_REMOTE_URL")` always resolves.
const UNKNOWN_REMOTE: &str = "unknown";

fn main() -> Result<()> {
    let build = Build::all_build();
    let gix = Gix::all_git();
    let cargo = Cargo::all_cargo();
    Emitter::default()
        .default_on_error()
        .add_instructions(&build)?
        .add_instructions(&gix)?
        .add_instructions(&cargo)?
        .emit()?;

    emit_git_remote_url();
    Ok(())
}

/// vergen only reports the local checkout (sha, branch, describe...), so read the
/// `origin` remote out of the same repository and expose it alongside the rest of
/// the `VERGEN_GIT_*` variables.
fn emit_git_remote_url() {
    let url = git_remote_url().unwrap_or_else(|| UNKNOWN_REMOTE.to_string());
    println!("cargo:rustc-env=VERGEN_GIT_REMOTE_URL={url}");
    println!("cargo:rerun-if-changed=.git/config");
}

fn git_remote_url() -> Option<String> {
    let repo = gix::discover(env!("CARGO_MANIFEST_DIR")).ok()?;
    let remote = repo.find_remote("origin").ok()?;
    let url = remote.url(gix::remote::Direction::Fetch)?;
    Some(url.to_bstring().to_string())
}