Files
ghostty-rs/crates/ghostty-cli/build.rs
T
ddidderr 4787565397 feat: port GTK version fallbacks, helpgen, bench modes, CLI leftovers
- apprt-gtk: Ghostty's runtime+build-time version gating (at_least)
  with cargo features adw_1_3/adw_1_4/adw_1_5/gtk_4_16 (default on) and
  the fallbacks for older libraries: MessageDialog (adw < 1.5),
  clipboard dialog without SwitchRow, pre-Banner debug warning and
  child-exited widgets, the old about dialog, GTK 4.16 CSS error source
  bytes. The minimum stays GTK 4.14 / libadwaita 1.5 (Ghostty's floor).
  The root build links with -z lazy so version-gated symbols don't keep
  older libraries from loading.
- ghostty-helpgen (port of helpgen.zig) generates CLI action help and
  keybinding action docs from doc comments at build time, replacing the
  checked-in help/*.txt; +help and +list-actions --docs stay
  byte-identical to Ghostty 1.3.1.
- ghostty-bench: libc wcwidth mode and separate simd/table and
  uucode/table code paths like Zig.
- ghostty-cli: Windows branches of edit-config, list-colors,
  list-keybinds and boo; ssh-cache DiskCache flock locking (no-op on
  Windows, as in Zig) with an exclusivity test.

Test Plan:
- cargo test --workspace
- diff <(cargo run -q -- +list-actions --docs) \
  <(ghostty +list-actions --docs)
2026-10-12 06:38:33 +02:00

195 lines
7.0 KiB
Rust

//! Build metadata for `+version` and the generated docs.
//!
//! * the compiler version (Zig: `builtin.zig_version_string`)
//! * the app version, release channel and commit (Zig: `build/Config.zig`
//! version detection + `build/GitVersion.zig`)
//! * the build mode (Zig: `builtin.mode`)
//!
//! The version can be overridden with `GHOSTTY_VERSION_STRING` (Zig:
//! `-Dversion-string`), which must be a semantic version.
use std::{
path::{Path, PathBuf},
process::Command,
};
fn run(cmd: &str, args: &[&str], dir: &Path) -> Option<String> {
let out = Command::new(cmd)
.args(args)
.current_dir(dir)
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim_end().to_string())
}
/// The `app-version` from `[workspace.metadata.ghostty]` of the workspace
/// manifest (two levels above this crate).
fn app_version(manifest_dir: &Path) -> (u64, u64, u64) {
let root = manifest_dir.join("../../Cargo.toml");
println!("cargo:rerun-if-changed={}", root.display());
let text = std::fs::read_to_string(root).unwrap_or_default();
let v = text
.lines()
.find_map(|l| l.trim().strip_prefix("app-version"))
.and_then(|l| l.split('"').nth(1))
.unwrap_or("1.3.1");
let mut it = v.split('.').map(|p| p.parse::<u64>().unwrap_or(0));
(
it.next().unwrap_or(1),
it.next().unwrap_or(3),
it.next().unwrap_or(1),
)
}
/// Returns `(version_string, commit)` mirroring `Config.zig`.
fn detect_version(manifest_dir: &Path) -> (String, Option<String>) {
println!("cargo:rerun-if-env-changed=GHOSTTY_VERSION_STRING");
if let Ok(v) = std::env::var("GHOSTTY_VERSION_STRING") {
let commit = v.split_once('+').map(|(_, b)| b.to_string());
return (v, commit);
}
let (maj, min, pat) = app_version(manifest_dir);
let base = format!("{maj}.{min}.{pat}");
// Git unavailable or not a repository: unknown dev version.
let Some(branch) = run("git", &["rev-parse", "--abbrev-ref", "HEAD"], manifest_dir) else {
return (format!("{base}-dev+0000000"), Some("0000000".into()));
};
if let Some(git_dir) = run("git", &["rev-parse", "--absolute-git-dir"], manifest_dir) {
let git_dir = PathBuf::from(git_dir);
println!("cargo:rerun-if-changed={}", git_dir.join("HEAD").display());
println!("cargo:rerun-if-changed={}", git_dir.join("refs").display());
println!(
"cargo:rerun-if-changed={}",
git_dir.join("packed-refs").display()
);
}
let hash = run(
"git",
&[
"-c",
"log.showSignature=false",
"log",
"--pretty=format:%h",
"-n",
"1",
],
manifest_dir,
)
.unwrap_or_default();
let tag = run(
"git",
&["describe", "--exact-match", "--tags"],
manifest_dir,
)
.filter(|t| !t.is_empty());
if let Some(tag) = tag {
// Tip releases behave just like any other pre-release so we skip.
if tag != "tip" {
assert!(
tag == format!("v{base}"),
"tagged releases must be in vX.Y.Z format matching the workspace app-version"
);
return (base, None);
}
}
// Slashes in branch names are replaced like in `GitVersion.zig`.
let branch = branch.replace('/', "-");
(format!("{base}-{branch}+{hash}"), Some(hash))
}
/// The Zig optimize-mode name for the Cargo profile being built.
fn build_mode() -> &'static str {
// The profile name is the directory below `target/` that holds OUT_DIR.
let out = std::env::var("OUT_DIR").unwrap_or_default();
let profile = Path::new(&out)
.ancestors()
.skip_while(|p| p.file_name().is_none_or(|n| n != "build"))
.nth(1)
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let debug_assertions = std::env::var_os("CARGO_CFG_DEBUG_ASSERTIONS").is_some();
let opt = std::env::var("OPT_LEVEL").unwrap_or_default();
if profile == "production" || !debug_assertions {
".ReleaseFast"
} else if opt == "0" {
".Debug"
} else {
".ReleaseSafe"
}
}
/// Generates the per-action help table (Zig: `helpgen.zig` `genActions`):
/// the doc comment of each action's `run` function becomes
/// `Action::help_text`.
fn gen_action_help(manifest_dir: &Path) {
let ghostty_rs = manifest_dir.join("src/ghostty.rs");
println!("cargo:rerun-if-changed={}", ghostty_rs.display());
let src = std::fs::read_to_string(&ghostty_rs).expect("read ghostty.rs");
let mut table = Vec::new();
for (variant, _) in ghostty_helpgen::enum_variant_docs(&src, "Action") {
// `ListFonts` -> `list_fonts` (file name, as Zig `Action.file`).
let mut file = String::new();
for (i, c) in variant.chars().enumerate() {
if c.is_ascii_uppercase() && i > 0 {
file.push('_');
}
file.push(c.to_ascii_lowercase());
}
let path = manifest_dir.join(format!("src/{file}.rs"));
println!("cargo:rerun-if-changed={}", path.display());
let text = std::fs::read_to_string(&path).expect("read action source");
let help = ghostty_helpgen::run_fn_doc(&text).unwrap_or_else(|| {
panic!("doc comment must be present on run function of the {file} action!")
});
table.push((variant, help));
}
assert!(!table.is_empty(), "no actions found");
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR"));
std::fs::write(
out.join("action_help.rs"),
ghostty_helpgen::cli_help_match(&table),
)
.expect("write action_help.rs");
}
fn main() {
println!("cargo:rerun-if-changed=build.rs");
gen_action_help(&PathBuf::from(
std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default(),
));
println!("cargo:rerun-if-env-changed=RUSTC");
let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".into());
let version = Command::new(rustc)
.arg("--version")
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
// "rustc 1.99.0 (b940084d7 2026-09-28)" -> "1.99.0"
.and_then(|s| s.split_whitespace().nth(1).map(str::to_owned))
.unwrap_or_else(|| "unknown".into());
println!("cargo:rustc-env=GHOSTTY_RUSTC_VERSION={version}");
let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default());
let (version_string, commit) = detect_version(&manifest_dir);
// Release channel: stable unless the version has a pre-release part.
let channel = if version_string.contains('-') {
"tip"
} else {
"stable"
};
println!("cargo:rustc-env=GHOSTTY_VERSION_STRING={version_string}");
println!(
"cargo:rustc-env=GHOSTTY_COMMIT={}",
commit.unwrap_or_default()
);
println!("cargo:rustc-env=GHOSTTY_RELEASE_CHANNEL={channel}");
println!("cargo:rustc-env=GHOSTTY_BUILD_MODE={}", build_mode());
}