syd 3.24.3

rock-solid unikernel
//
// Syd: rock-solid unikernel
// build.rs: Helper file for build-time information
//
// Copyright (c) 2021, 2024 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{env, path::Path, process::Command};

const VERSION: &str = env!("CARGO_PKG_VERSION");

fn main() {
    // Gather information on target.
    println!(
        "cargo:rustc-env=SYD_TARGET_ENV={}",
        env::var("CARGO_CFG_TARGET_ENV").unwrap_or("?".to_string())
    );
    println!(
        "cargo:rustc-env=SYD_TARGET_POINTER_WIDTH={}",
        env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap_or("?".to_string())
    );
    println!(
        "cargo:rustc-env=SYD_TARGET_ENDIAN={}",
        env::var("CARGO_CFG_TARGET_ENDIAN").unwrap_or("?".to_string())
    );
    println!(
        "cargo:rustc-env=SYD_TARGET_FEATURE={}",
        env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or("?".to_string())
    );

    // Gather information on build host.
    let host = if let Ok(output) = Command::new("uname").arg("-mr").output() {
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    } else {
        "?".to_string()
    };
    println!("cargo:rustc-env=SYD_BUILDHOST={host}");

    // We don't want to build libgit2 library just to get the git version.
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let root = root.join(".git");
    let mut head = String::new();

    if root.exists() {
        // Try to get the description
        if let Ok(output) = Command::new("git").arg("describe").output() {
            head = String::from_utf8_lossy(&output.stdout).trim().to_string();
        }

        // If description is empty, try to get the short HEAD
        // Only use main version tags, skip pandora, libsyd etc. tags
        if head.is_empty() || !head.starts_with('v') {
            if let Ok(output) = Command::new("git")
                .args(["rev-parse", "--short", "HEAD"])
                .output()
            {
                head = format!(
                    "v{VERSION}-{}",
                    String::from_utf8_lossy(&output.stdout).trim()
                );
            }
        }

        // Check for any changes
        if let Ok(output) = Command::new("git")
            .args(["diff-index", "-m", "--name-only", "HEAD"])
            .output()
        {
            let changes = String::from_utf8_lossy(&output.stdout);
            if !changes.is_empty() {
                head = format!("{head}-dirty");
            }
        }

        // Strip prefix v$VERSION -> $VERSION
        if head.starts_with('v') {
            head = head[1..].to_string();
        }
    }
    println!("cargo:rustc-env=SYD_GITHEAD={head}");
}