Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::env;
use std::fs;
use std::io::Error;
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;

use clap::{Command, CommandFactory};
use clap_complete::Shell;
Expand All @@ -18,6 +19,7 @@ mod cli;
fn main() -> Result<(), Error> {
println!("cargo:rerun-if-changed=src/cli.rs");
println!("cargo:rerun-if-changed=build.rs");
emit_version_info();

let Some(out_dir) = env::var_os("OUT_DIR").map(PathBuf::from) else {
return Ok(());
Expand All @@ -43,6 +45,49 @@ fn main() -> Result<(), Error> {
Ok(())
}

/// Sets `COMLINE_GIT_HASH` / `COMLINE_GIT_BRANCH` / `COMLINE_COMMIT_COUNT` /
/// `COMLINE_BUILD_DATE` for `cli.rs`'s `LONG_VERSION` to pull in via
/// `env!()`. Every one of these degrades to `"unknown"` rather than
/// failing the build — a source tarball with no `.git` directory, or a
/// machine with no `git`/`date` on PATH, still produces a working binary.
///
/// Re-run (and so re-captured) whenever the current commit or branch
/// changes; a build with no new commits reuses the cached binary anyway, so
/// there's nothing to refresh in that case.
fn emit_version_info() {
println!("cargo:rerun-if-changed=.git/HEAD");
println!("cargo:rerun-if-changed=.git/refs");

let hash = run(&["git", "rev-parse", "--short=12", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
let dirty = run(&["git", "status", "--porcelain"]).is_some_and(|s| !s.is_empty());
let branch =
run(&["git", "rev-parse", "--abbrev-ref", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
let commit_count = run(&["git", "rev-list", "--count", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
let build_date =
run(&["date", "-u", "+%Y-%m-%dT%H:%M:%SZ"]).unwrap_or_else(|| "unknown".to_string());

println!(
"cargo:rustc-env=COMLINE_GIT_HASH={}{}",
hash,
if dirty { "-dirty" } else { "" }
);
println!("cargo:rustc-env=COMLINE_GIT_BRANCH={branch}");
println!("cargo:rustc-env=COMLINE_COMMIT_COUNT={commit_count}");
println!("cargo:rustc-env=COMLINE_BUILD_DATE={build_date}");
}

/// Run a command, returning trimmed stdout on success - `None` on any
/// failure (missing binary, non-zero exit, not a git repo, ...).
fn run(args: &[&str]) -> Option<String> {
let output = ProcessCommand::new(args[0]).args(&args[1..]).output().ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8(output.stdout).ok()?;
let text = text.trim();
(!text.is_empty()).then(|| text.to_string())
}

fn render_man_pages(dir: &Path, command: &Command) -> Result<(), Error> {
let name = command.get_name().to_string();
write_man(&dir.join(format!("{name}.1")), command.clone(), &name)?;
Expand Down
30 changes: 28 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mod watch;
use std::env;
use std::process::ExitCode;

use clap::Parser;
use clap::{CommandFactory, FromArgMatches};
use miette::Result;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

Expand All @@ -19,7 +19,7 @@ use cli::{Cli, Commands};
fn main() -> ExitCode {
reset_sigpipe();

let cli = Cli::parse();
let cli = parse_cli();

init_tracing(&cli);
ui::set_quiet(cli.quiet);
Expand All @@ -39,6 +39,32 @@ fn main() -> ExitCode {
}
}

/// Parse CLI args with an enriched `--version` (`-V` stays the bare
/// `CARGO_PKG_VERSION` `clap`'s derive attribute already gives `Cli`).
/// Built as a `Command`, not the `#[command(long_version = ...)]` derive
/// attribute, because `build.rs` also compiles `cli.rs` (via `#[path]`, for
/// man-page/completion generation) *before* it has emitted these env vars
/// for the real binary — a `const` baked in by that attribute would need
/// `env!()`, which hard-fails the build in that earlier context. Building
/// the string here instead, with `option_env!()`, means every field just
/// degrades to `"unknown"` if `build.rs`'s own `git`/`date` capture
/// (`emit_version_info`) came up empty, rather than failing anything.
fn parse_cli() -> Cli {
let long_version = format!(
"{}\ncommit-hash: {}\ncommit-branch: {}\ncommit-count: {}\nbuild-date: {}",
env!("CARGO_PKG_VERSION"),
option_env!("COMLINE_GIT_HASH").unwrap_or("unknown"),
option_env!("COMLINE_GIT_BRANCH").unwrap_or("unknown"),
option_env!("COMLINE_COMMIT_COUNT").unwrap_or("unknown"),
option_env!("COMLINE_BUILD_DATE").unwrap_or("unknown"),
);
// `Command::long_version` needs a `&'static str`, not an owned
// `String` - leaking it is fine here, it lives for the process anyway.
let long_version: &'static str = Box::leak(long_version.into_boxed_str());
let matches = Cli::command().long_version(long_version).get_matches();
Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit())
}

/// `tracing` carries `comline-core` diagnostics only; the CLI's own output goes
/// through [`ui`]. Everything is written to stderr so stdout stays a clean
/// channel for payloads (`comline completions`, `comline targets`). Verbosity
Expand Down
Loading