hex/build.rs
Kit Langton f35d90471b
fix(sidebar): show local builds once below What's new (#2605)
* fix(sidebar): show local builds once below What's new

* test(golden): update mac-local-build-dark for local build footer
2026-11-23 15:58:20 -08:00

425 lines
17 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::path::PathBuf;
use std::process::Command;
fn main() {
check_windows_split();
x86_baseline();
let version = build_version();
println!("cargo:rustc-env=HEX_BUILD_VERSION={version}");
build_commit(&version);
// `hex_dev_onboarding`: the first run's replay strip and its swearing
// jokes, in debug and `HEX_TEST_BUILD=1` builds only.
println!("cargo::rustc-check-cfg=cfg(hex_dev_onboarding)");
if std::env::var_os("CARGO_CFG_DEBUG_ASSERTIONS").is_some()
|| std::env::var("HEX_TEST_BUILD").as_deref() == Ok("1")
{
println!("cargo::rustc-cfg=hex_dev_onboarding");
}
// `hex_capture`: the `capture` experiment's code, in every macOS, Linux,
// and Windows build (`scrawl-capture` is their dependency).
println!("cargo::rustc-check-cfg=cfg(hex_capture)");
if matches!(
std::env::var("CARGO_CFG_TARGET_OS").as_deref(),
Ok("macos" | "linux" | "windows")
) {
println!("cargo::rustc-cfg=hex_capture");
}
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") {
// transcribe-cpp's static manifest records OpenBLAS as an absolute
// link argument, which Cargo does not propagate through the -sys
// crate to this final binary. Keep it after the static archives so
// GNU ld's --as-needed does not discard it before seeing cblas_*.
println!("cargo:rustc-link-arg=-lopenblas");
}
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
// transcribe-cpp's Vulkan backend links the vulkan-1 import
// library by name without its search path. The DLL itself ships
// with the GPU driver, so it is delay-loaded: a missing or
// Vulkan 1.0 loader must not stop Hex at launch (#1240;
// `windows::vulkan` keeps ggml off it then).
println!("cargo:rerun-if-env-changed=VULKAN_SDK");
if std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64") {
if let Some(sdk) = std::env::var_os("VULKAN_SDK") {
println!(
"cargo:rustc-link-search=native={}",
PathBuf::from(sdk).join("Lib").display()
);
}
println!("cargo:rustc-link-arg=/DELAYLOAD:vulkan-1.dll");
println!("cargo:rustc-link-lib=delayimp");
}
#[cfg(windows)]
embed_windows_resources();
}
return;
}
let output = Command::new("xcode-select")
.arg("-p")
.output()
.expect("xcode-select is required to link ScreenCaptureKit");
assert!(output.status.success(), "xcode-select -p failed");
let developer_dir = String::from_utf8(output.stdout).expect("Xcode path must be UTF-8");
compile_swift_bridge("apple_speech", "HEXAppleSpeechBridge", &[], None);
println!("cargo:rustc-link-lib=framework=AVFAudio");
println!("cargo:rustc-link-lib=framework=Speech");
// AVFoundation decodes an imported meeting's audio into a 16 kHz WAV.
compile_swift_bridge("meeting_import", "HEXMeetingImportBridge", &[], None);
println!("cargo:rustc-link-lib=framework=AudioToolbox");
// Labs › Voice isolation runs dictation's microphone through Apple's
// voice processing, an AVAudioEngine duplex unit on the chosen device.
// Its Objective-C guard turns the exceptions AVAudioEngine raises for a
// refused graph into errors Swift can fall back from.
println!("cargo:rerun-if-changed=native/voice_processing_guard.m");
println!("cargo:rerun-if-changed=native/voice_processing_guard.h");
// Link the guard as an object beside the Swift object, so neither depends
// on a static archive's place in the linker's argument order.
for guard in cc::Build::new()
.file("native/voice_processing_guard.m")
.flag("-fobjc-arc")
.flag("-fblocks")
.compile_intermediates()
{
println!("cargo:rustc-link-arg={}", guard.display());
}
compile_swift_bridge(
"voice_processing",
"HEXVoiceProcessingBridge",
&[],
Some("native/voice_processing_guard.h"),
);
println!("cargo:rustc-link-lib=framework=CoreAudio");
// FoundationModels exists only on macOS 26 and later. Weak-link it, and
// drop the object's strong autolink entry, so Hex still launches on older
// systems and reports Apple Intelligence as unavailable.
compile_swift_bridge(
"apple_intelligence",
"HEXAppleIntelligenceBridge",
&["FoundationModels"],
None,
);
println!("cargo:rustc-link-arg=-Wl,-weak_framework,FoundationModels");
compile_swift_bridge("calendar", "HEXCalendarBridge", &[], None);
println!("cargo:rustc-link-lib=framework=EventKit");
compile_permission_guide();
println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/lib/swift");
for runtime in ["swift-5.5/macosx", "swift/macosx"] {
let swift_runtime = format!(
"{}/Toolchains/XcodeDefault.xctoolchain/usr/lib/{runtime}",
developer_dir.trim()
);
println!("cargo:rustc-link-arg=-Wl,-rpath,{swift_runtime}");
}
}
/// The version Hex reports (`HEX_BUILD_VERSION`): the crate version, which
/// the Release workflow stamps (scripts/set-crate-version.sh), else, for any
/// other build of the unstamped `0.0.0`, `0.0.0-dev-local-<commit>` with
/// `-dirty` for uncommitted changes (`0.0.0-dev-local` without git, as in Nix).
/// It counts as a dev build, so it follows the dev channel's current release.
/// Fails every OS's build when Cargo.lock puts gpu-allocator and wgpu-hal on
/// different `windows` crates. wgpu-hal passes D3D12 types into
/// gpu-allocator, so the split only breaks the Windows build, and
/// `cargo update -p rune` has re-resolved gpu-allocator onto an older
/// `windows` twice (#997, #1085). Fix it by setting gpu-allocator's `windows`
/// (and iana-time-zone's `windows-core`) back to wgpu-hal's version.
fn check_windows_split() {
println!("cargo:rerun-if-changed=Cargo.lock");
let Ok(lock) = std::fs::read_to_string("Cargo.lock") else {
return;
};
let windows = |name: &str| {
lock.split("[[package]]")
.find(|block| block.contains(&format!("\nname = \"{name}\"\n")))
.and_then(|block| {
block
.lines()
.map(|line| line.trim().trim_end_matches(',').trim_matches('"'))
.find(|dependency| {
*dependency == "windows" || dependency.starts_with("windows ")
})
.map(str::to_owned)
})
};
let (allocator, hal) = (windows("gpu-allocator"), windows("wgpu-hal"));
assert_eq!(
allocator, hal,
"Cargo.lock: gpu-allocator must use wgpu-hal's `windows` crate, or the Windows build breaks"
);
}
/// `HEX_X86_BASELINE=ivybridge` builds ggml for Ivy Bridge (2012: SSE4.2, AVX,
/// F16C) instead of the releases' x86-64-v3, for source builds below the release
/// floor (docs/linux.md, docs/windows.md). Unset, empty, and `v3` keep the
/// release baseline exactly as CI builds it; any other target ignores the switch.
fn x86_baseline() {
println!("cargo::rustc-check-cfg=cfg(hex_x86_ivybridge)");
println!("cargo:rerun-if-env-changed=HEX_X86_BASELINE");
println!("cargo:rerun-if-env-changed=TRANSCRIBE_CMAKE_ARGS");
const RECOMMENDED: &str = "-DGGML_NATIVE=OFF -DGGML_SSE42=ON -DGGML_AVX=ON -DGGML_F16C=ON -DGGML_AVX2=OFF -DGGML_BMI2=OFF -DGGML_FMA=OFF";
let baseline = std::env::var("HEX_X86_BASELINE").ok();
match baseline.as_deref() {
None | Some("" | "v3") => return,
Some("ivybridge") => {}
Some(other) => panic!(
"HEX_X86_BASELINE={other} is not a baseline; use `v3` (the release baseline), `ivybridge`, or leave it unset"
),
}
if !matches!(
std::env::var("CARGO_CFG_TARGET_OS").as_deref(),
Ok("linux" | "windows")
) || std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() != Ok("x86_64")
{
return;
}
let cmake = std::env::var("TRANSCRIBE_CMAKE_ARGS").unwrap_or_default();
let arguments = cmake.split_whitespace().collect::<Vec<_>>();
// Exactly this build's baseline: no AVX2, BMI2, or FMA (the OFF flags), and
// no stale CMake cache leaving AVX or F16C off (the ON flags).
for flag in [
"-DGGML_NATIVE=OFF",
"-DGGML_SSE42=ON",
"-DGGML_AVX=ON",
"-DGGML_F16C=ON",
"-DGGML_AVX2=OFF",
"-DGGML_BMI2=OFF",
"-DGGML_FMA=OFF",
] {
assert!(
arguments.contains(&flag),
"HEX_X86_BASELINE=ivybridge needs `{flag}` in TRANSCRIBE_CMAKE_ARGS, or ggml keeps \
its previous CPU baseline: Hex would crash on the processor this build is for, or \
crawl on it.\n\
Set TRANSCRIBE_CMAKE_ARGS=\"{RECOMMENDED}\""
);
}
println!("cargo::rustc-cfg=hex_x86_ivybridge");
}
fn build_version() -> String {
println!("cargo:rerun-if-env-changed=HEX_VERSION");
let version = std::env::var("CARGO_PKG_VERSION").unwrap();
// CI builds name their version in HEX_VERSION and check `hex --version`
// against it, test builds included (they name the crate version).
if let Some(named) = std::env::var("HEX_VERSION")
.ok()
.filter(|named| !named.is_empty())
{
return named;
}
if version != "0.0.0" {
return version;
}
let git = |args: &[&str]| {
Command::new("git")
.args(args)
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
};
let mut version = "0.0.0-dev-local".to_owned();
if let Some(commit) =
git(&["rev-parse", "--short=7", "HEAD"]).filter(|commit| !commit.is_empty())
{
version = format!("{version}-{commit}");
if git(&["status", "--porcelain", "--untracked-files=no"])
.is_some_and(|status| !status.is_empty())
{
version.push_str("-dirty");
}
let reference = git(&["symbolic-ref", "-q", "HEAD"]);
for name in ["HEAD", "packed-refs", "index"]
.into_iter()
.chain(reference.as_deref())
{
if let Some(path) = git(&["rev-parse", "--path-format=absolute", "--git-path", name])
.filter(|path| std::path::Path::new(path).exists())
{
println!("cargo:rerun-if-changed={path}");
}
}
}
version
}
/// Test builds keep their short badge label; local builds can identify the
/// exact checkout without starting the app (`hex --version`).
fn build_commit(version: &str) {
println!("cargo:rerun-if-env-changed=HEX_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=HEX_TEST_BUILD");
println!("cargo:rerun-if-env-changed=HEX_LOCAL_BUILD");
let local = std::env::var("HEX_LOCAL_BUILD").as_deref() == Ok("1");
if !local && std::env::var("HEX_TEST_BUILD").as_deref() != Ok("1") {
return;
}
let git = |args: &[&str]| {
Command::new("git")
.args(args)
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.filter(|value| !value.is_empty())
};
let commit = if local {
// A remote build may have the source but not its Git checkout.
println!("cargo:rerun-if-env-changed=HEX_COMMIT");
let commit = std::env::var("HEX_COMMIT")
.ok()
.filter(|s| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit()))
.or_else(|| git(&["rev-parse", "HEAD"]));
let detail = commit
.as_deref()
.map(|sha| format!(" · {sha}"))
.unwrap_or_default();
println!(
"cargo:rustc-env=HEX_LOCAL_LONG_VERSION={version} · Local build · updates off{detail}"
);
commit
} else {
git(&["rev-parse", "--short=7", "HEAD"])
};
if let Some(commit) = commit {
println!("cargo:rustc-env=HEX_COMMIT={commit}");
}
let reference = git(&["symbolic-ref", "-q", "HEAD"]);
for name in ["HEAD", "packed-refs"]
.into_iter()
.chain(reference.as_deref())
{
if let Some(path) = git(&["rev-parse", "--path-format=absolute", "--git-path", name])
.filter(|path| std::path::Path::new(path).exists())
{
println!("cargo:rerun-if-changed={path}");
}
}
}
/// Gives the executable its icon and the "Hex" name Explorer and Task
/// Manager show, whatever the file is called.
#[cfg(windows)]
fn embed_windows_resources() {
let manifest_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap());
let output_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
let icon = manifest_dir.join("resources/windows/hex.ico");
println!("cargo:rerun-if-changed={}", icon.display());
let version = std::env::var("CARGO_PKG_VERSION").unwrap();
let numeric = version
.split(['.', '-'])
.take(3)
.map(|part| part.parse::<u16>().unwrap_or(0).to_string())
.chain(std::iter::repeat("0".to_string()))
.take(4)
.collect::<Vec<_>>()
.join(",");
let script = format!(
r#"#include <winver.h>
1 ICON "{icon}"
1 VERSIONINFO
FILEVERSION {numeric}
PRODUCTVERSION {numeric}
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "FileDescription", "Hex"
VALUE "ProductName", "Hex"
VALUE "FileVersion", "{version}"
VALUE "ProductVersion", "{version}"
VALUE "OriginalFilename", "hex.exe"
VALUE "InternalName", "hex"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
"#,
icon = icon.display().to_string().replace('\\', "/"),
);
let resource = output_dir.join("hex.rc");
std::fs::write(&resource, script).expect("write the Windows resource script");
embed_resource::compile(&resource, embed_resource::NONE)
.manifest_optional()
.expect("compile the Windows resources");
}
fn compile_permission_guide() {
println!("cargo:rerun-if-changed=native/permission_guide.m");
println!("cargo:rustc-link-lib=framework=AppKit");
println!("cargo:rustc-link-lib=framework=ApplicationServices");
println!("cargo:rustc-link-lib=framework=AVFoundation");
println!("cargo:rustc-link-lib=framework=CoreGraphics");
println!("cargo:rustc-link-lib=framework=CoreImage");
println!("cargo:rustc-link-lib=framework=IOKit");
println!("cargo:rustc-link-lib=framework=QuartzCore");
cc::Build::new()
.file("native/permission_guide.m")
.flag("-fobjc-arc")
.compile("hex_permission_guide");
}
fn compile_swift_bridge(
name: &str,
module: &str,
without_autolink: &[&str],
bridging_header: Option<&str>,
) {
let manifest_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap());
let output_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
let source = manifest_dir.join(format!("src/{name}.swift"));
let object = output_dir.join(format!("{name}.o"));
let sdk = Command::new("xcrun")
.args(["--sdk", "macosx", "--show-sdk-path"])
.output()
.expect("xcrun is required to compile Swift bridges");
assert!(sdk.status.success(), "could not locate the macOS SDK");
let target = match std::env::var("TARGET").as_deref() {
Ok("aarch64-apple-darwin") => "arm64-apple-macosx15.0",
Ok("x86_64-apple-darwin") => "x86_64-apple-macosx15.0",
Ok(target) => panic!("unsupported macOS target for {module}: {target}"),
Err(error) => panic!("TARGET is unavailable: {error}"),
};
println!("cargo:rerun-if-changed={}", source.display());
let mut swift = Command::new("xcrun");
swift.args([
"swiftc",
"-parse-as-library",
"-emit-object",
"-module-name",
module,
"-sdk",
]);
swift
.arg(String::from_utf8_lossy(&sdk.stdout).trim())
.args(["-target", target]);
for framework in without_autolink {
swift.args([
"-Xfrontend",
"-disable-autolink-framework",
"-Xfrontend",
framework,
]);
}
if let Some(header) = bridging_header {
swift
.arg("-import-objc-header")
.arg(manifest_dir.join(header))
.arg("-Xcc")
.arg("-fblocks");
}
let status = swift
.arg(&source)
.arg("-o")
.arg(&object)
.status()
.expect("xcrun swiftc is required to compile Swift bridges");
assert!(status.success(), "{module} compilation failed");
println!("cargo:rustc-link-arg={}", object.display());
}