gitflow-cli 2.1.0

跨平台 Git 工程化工作流编排框架:统一封装 GitHub / GitLab / GitCode 三大平台,配合 AI Agent Skills,覆盖从需求到发布的完整工程循环。
//! Build script for `gf`.
//!
//! Generates build-time metadata (version, commit, target triple, etc.)
//! via the `built` crate and writes it to `OUT_DIR/built.rs` for inclusion
//! in the binary.
//!
//! Also scans the `skills/` directory and writes a manifest to
//! `OUT_DIR/skills_manifest.rs` so the binary has a list of bundled skills.

#![allow(
    clippy::disallowed_methods,
    reason = "Build script runs synchronously before any async runtime"
)]
#![allow(
    clippy::format_push_string,
    reason = "Single push per loop iteration, not hot path"
)]
#![allow(
    clippy::expect_used,
    reason = "Build scripts run once at compile time; panicking on failure is appropriate"
)]
#![allow(
    missing_docs,
    reason = "Build script `main` is an implementation detail, not a public API"
)]
#![allow(
    clippy::disallowed_types,
    reason = "Build script runs synchronously before any async runtime; std::process::Command is \
              the appropriate tool here, not tokio::process::Command"
)]

use std::{
    env, fs,
    path::{Path, PathBuf},
};

fn main() {
    built::write_built_file().expect("Failed to acquire build-time information");

    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR env var"));
    write_git_sha(&manifest_dir, &out_dir);

    // Generate skills manifest from skills/ directory.
    // Search order:
    //   1. CARGO_MANIFEST_DIR/skills — crates.io package (skills copied into package before
    //      publish)
    //   2. CARGO_MANIFEST_DIR/../../skills — workspace build (skills at workspace root)
    let skills_dir = manifest_dir.join("skills");
    let skills_dir = if skills_dir.exists() {
        skills_dir
    } else {
        manifest_dir.join("../../skills")
    };

    if skills_dir.exists() {
        // Canonicalize to absolute path for include_bytes!
        let skills_dir = skills_dir
            .canonicalize()
            .expect("Failed to canonicalize skills path");

        let manifest_path = out_dir.join("skills_manifest.rs");

        let mut entries: Vec<RelativePath> = Vec::new();
        collect_skills(&skills_dir, &skills_dir, &mut entries);

        let mut manifest = String::new();
        manifest.push_str("// @generated by build.rs - do not edit\n");
        manifest.push_str("pub const SKILLS: &[(&str, &[u8])] = &[\n");
        for entry in &entries {
            // Convert paths to use forward slashes for cross-platform compatibility
            // Windows paths use backslashes which are escape characters in Rust strings
            let relative = entry.relative.replace('\\', "/");
            let absolute = entry.absolute.display().to_string().replace('\\', "/");
            manifest.push_str(&format!(
                "    (\"{relative}\", include_bytes!(\"{absolute}\")),\n"
            ));
        }
        manifest.push_str("];\n");

        fs::write(&manifest_path, manifest).expect("Failed to write skills manifest");
        println!("cargo:rerun-if-changed={}", skills_dir.display());
    } else {
        // Release build (no skills/ next to binary): generate empty manifest
        let manifest_path = out_dir.join("skills_manifest.rs");
        fs::write(
            &manifest_path,
            "// @generated by build.rs - no skills bundled\npub const SKILLS: &[(&str, &[u8])] = \
             &[];\n",
        )
        .expect("Failed to write empty skills manifest");
    }
}

/// Captures the short git commit hash of `HEAD` at compile time.
///
/// Falls back to `"unknown"` (never panics) when the build tree is not a
/// git checkout (e.g. a crates.io source tarball) or `git` is unavailable.
/// Also arranges for cargo to rerun this script whenever `HEAD` moves —
/// via `git rev-parse --git-path`, which resolves to the correct file for
/// both the main worktree and any linked worktree (e.g. the ones
/// `gf-workflow` creates under `.worktree/`) — so the embedded sha never
/// goes stale relative to the source it was actually built from.
fn write_git_sha(manifest_dir: &Path, out_dir: &Path) {
    let git_dir_relative_paths = ["HEAD", "logs/HEAD"];
    for rel in git_dir_relative_paths {
        if let Ok(output) = std::process::Command::new("git")
            .args(["rev-parse", "--git-path", rel])
            .current_dir(manifest_dir)
            .output()
            && output.status.success()
            && let Ok(path) = String::from_utf8(output.stdout)
        {
            println!("cargo:rerun-if-changed={}", path.trim());
        }
    }

    let sha = std::process::Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .current_dir(manifest_dir)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "unknown".to_owned());

    let git_sha_path = out_dir.join("git_sha.rs");
    fs::write(
        &git_sha_path,
        format!("// @generated by build.rs - do not edit\npub const GIT_SHA: &str = \"{sha}\";\n"),
    )
    .expect("Failed to write git_sha.rs");
}

struct RelativePath {
    relative: String,
    absolute: PathBuf,
}

fn collect_skills(dir: &Path, base: &Path, entries: &mut Vec<RelativePath>) {
    if let Ok(read_dir) = fs::read_dir(dir) {
        for entry in read_dir.flatten() {
            let path = entry.path();
            let name = entry.file_name();
            if name == ".git" || name == "target" {
                continue;
            }

            match (path.strip_prefix(base), path.is_dir()) {
                (Ok(_relative), true) => {
                    collect_skills(&path, base, entries);
                }
                (Ok(relative), false) => {
                    entries.push(RelativePath {
                        relative: relative.to_string_lossy().to_string(),
                        absolute: path,
                    });
                }
                _ => {}
            }
        }
    }
}