From 9d6b346462c66243c8a9089740223e4717f6fee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 11 Nov 2026 13:51:52 +0800 Subject: [PATCH] =?UTF-8?q?=E7=89=88=E6=9C=AC:=20v-=20with?= =?UTF-8?q?=20the=20build=20time,=20the=20same=20in=20the=20app,=20the=20p?= =?UTF-8?q?hone,=20--version=20and=20the=20server=20log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 +- Cargo.toml | 2 +- Makefile | 12 ++++++--- build.rs | 58 +++++++++++++++++++++++++++++++++++++++++++ deploy/mac/bundle.sh | 9 ++++--- mobile/index.html | 2 +- src/app.rs | 18 +++----------- src/app/remote_ui.rs | 2 +- src/app/sidebar_ui.rs | 2 +- src/main.rs | 9 +++++++ src/version.rs | 46 ++++++++++++++++++++++++++++++++++ 11 files changed, 136 insertions(+), 26 deletions(-) create mode 100644 build.rs create mode 100644 src/version.rs diff --git a/Cargo.lock b/Cargo.lock index 26b512d..c27bf94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -336,7 +336,7 @@ dependencies = [ [[package]] name = "anybot" -version = "0.1.0" +version = "0.0.1" dependencies = [ "agent-desktop-core", "agent-desktop-linux", diff --git a/Cargo.toml b/Cargo.toml index 89c96c1..2c9c7a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "anybot" -version = "0.1.0" +version = "0.0.1" license = "Apache-2.0" edition = "2021" # Older Rust stops with a clear message instead of odd errors deep in a dependency. diff --git a/Makefile b/Makefile index fac342d..9c5c10c 100644 --- a/Makefile +++ b/Makefile @@ -11,10 +11,14 @@ export PATH := $(HOME)/.cargo/bin:$(PATH) CARGO ?= cargo UNAME := $(shell uname -s) -# `git describe` prints nothing outside a repo; sed passes the empty string through with -# status 0, so "|| echo dev" never fired and VERSION came out blank ("AnyBot ", dist files -# named ".tar.gz"). grep . fails on empty input, which makes the fallback work. -VERSION ?= $(shell git describe --tags --always 2>/dev/null | sed 's/^v//' | grep . || echo dev) +# The version, as the program shows it: v-, with "-dirty" when what +# goes into the program has uncommitted changes (the same paths as INPUTS in build.rs). Outside git +# it is just v. ANYBOT_GIT_COMMIT is handed to cargo, so the program built here and the +# dist file names say the same thing (build.rs takes it instead of asking git again). +VERSION_NUMBER := $(shell sed -n 's/^version *= *"\(.*\)"/\1/p' Cargo.toml | head -n 1) +GIT_COMMIT := $(shell git rev-parse --short=7 HEAD 2>/dev/null)$(shell git status --porcelain --untracked-files=no -- src box fonts icons mobile Cargo.toml Cargo.lock build.rs 2>/dev/null | grep -q . && echo -dirty) +export ANYBOT_GIT_COMMIT ?= $(GIT_COMMIT) +VERSION ?= v$(VERSION_NUMBER)$(if $(ANYBOT_GIT_COMMIT),-$(ANYBOT_GIT_COMMIT)) TARGET := $(or $(CARGO_TARGET_DIR),target) APPDIR ?= $(HOME)/Applications BIN := $(TARGET)/release/anybot diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..cc77035 --- /dev/null +++ b/build.rs @@ -0,0 +1,58 @@ +// Which build this is, for 設定 › 更新, the phone and `anybot --version`: v-. +// +// v0.0.1-36bc2be built from commit 36bc2be as it is +// v0.0.1-36bc2be-dirty built from 36bc2be with changes to what goes into the program +// v0.0.1 no git here (a source tarball) +// +// is the one in Cargo.toml, the only place the number is kept. The commit comes from +// ANYBOT_GIT_COMMIT when it is set (make sets it, so the program and the dist file names agree), +// otherwise from git. The build time is not baked in: it is the program file's own time (src/version.rs). +use std::process::Command; + +/// What goes into the program: a change anywhere else (docs, deploy scripts) doesn't make it "dirty". +const INPUTS: &[&str] = &["src", "box", "fonts", "icons", "mobile", "Cargo.toml", "Cargo.lock", "build.rs"]; + +fn git(args: &[&str]) -> Option { + let out = Command::new("git").args(args).output().ok()?; + if !out.status.success() { + return None; + } + let s = String::from_utf8(out.stdout).ok()?.trim().to_string(); + (!s.is_empty()).then_some(s) +} + +fn main() { + let number = std::env::var("CARGO_PKG_VERSION").unwrap_or_default(); + let commit = match std::env::var("ANYBOT_GIT_COMMIT").ok().filter(|s| !s.trim().is_empty()) { + Some(c) => Some(c.trim().to_string()), + None => git(&["rev-parse", "--short=7", "HEAD"]).map(|c| { + let mut args = vec!["status", "--porcelain", "--untracked-files=no", "--"]; + args.extend_from_slice(INPUTS); + let dirty = git(&args).is_some(); + if dirty { format!("{c}-dirty") } else { c } + }), + }; + let label = match commit { + Some(c) => format!("v{number}-{c}"), + None => format!("v{number}"), + }; + println!("cargo:rustc-env=ANYBOT_VERSION={label}"); + + // Run again when the commit changes (commit, checkout, pull) or what goes into the program + // does (then it's compiled again anyway). Not on the index: `git status` rewrites it, and every + // rerun recompiles the whole program. + println!("cargo:rerun-if-env-changed=ANYBOT_GIT_COMMIT"); + for p in INPUTS { + println!("cargo:rerun-if-changed={p}"); + } + if let Some(dir) = git(&["rev-parse", "--absolute-git-dir"]) { + println!("cargo:rerun-if-changed={dir}/HEAD"); + } + if let Some(common) = git(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) { + for p in ["refs/heads", "packed-refs"] { + if std::path::Path::new(&common).join(p).exists() { + println!("cargo:rerun-if-changed={common}/{p}"); + } + } + } +} diff --git a/deploy/mac/bundle.sh b/deploy/mac/bundle.sh index 1f928f0..1f3600c 100755 --- a/deploy/mac/bundle.sh +++ b/deploy/mac/bundle.sh @@ -1,10 +1,13 @@ #!/bin/sh # Make AnyBot.app from the release build and zip it (run from app/ on a Mac, after -# `cargo build --release`): deploy/mac/bundle.sh 1.2.0 → dist/AnyBot-1.2.0-macos-.zip +# `cargo build --release`): deploy/mac/bundle.sh v0.0.1-36bc2be → dist/AnyBot-v0.0.1-36bc2be-macos-.zip # With KEEP_APP=1 it leaves dist/AnyBot.app instead of zipping it (make install). # Signed with this Mac's own fixed key (no Apple developer account): the first time, right-click › 打開. set -e VERSION=${1:?version} +# Info.plist wants plain numbers (0.0.1): the commit stays in the file name and in the app itself. +NUMBER=$(printf '%s' "$VERSION" | sed -n 's/^v\{0,1\}\([0-9][0-9.]*\).*/\1/p') +NUMBER=${NUMBER:-0.0.0} BIN=${CARGO_TARGET_DIR:-target}/release/anybot ARCH=$(uname -m) OUT=dist @@ -31,8 +34,8 @@ cat > "$APP/Contents/Info.plist" <CFBundleExecutableAnyBot CFBundleIconFileAnyBot CFBundlePackageTypeAPPL - CFBundleShortVersionString$VERSION - CFBundleVersion$VERSION + CFBundleShortVersionString$NUMBER + CFBundleVersion$NUMBER LSMinimumSystemVersion12.0 NSHighResolutionCapable NSMicrophoneUsageDescription語音聊天時,聽你說話。 diff --git a/mobile/index.html b/mobile/index.html index 0bb6e5b..e6fc3d8 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1826,7 +1826,7 @@ function drawSettings(kind, quiet) { h += group("這支手機", acts.join("")); } if (kind === "updates") { - h += group("", item({icon: "info", k: "版本", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"}))); + h += group("", item({icon: "info", k: "版本", v: st.built ? `${st.built} 建置` : "", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"}))); h += `
Bot 的電腦的更新在「電腦」裡。
`; } el.innerHTML = h + `
`; diff --git a/src/app.rs b/src/app.rs index 3fac029..3991592 100644 --- a/src/app.rs +++ b/src/app.rs @@ -325,7 +325,7 @@ impl App { want_direct: Default::default(), managed: if demo { policy::Managed::default() } else { policy::read() }, settings_was_open: false, - exe_built: exe_modified(), + exe_built: crate::version::exe_modified(), newer_build: None, last_build_check: Instant::now(), next_update_apply: Instant::now() + std::time::Duration::from_secs(notify::UPDATE_FIRST_CHECK_SECS), @@ -3567,9 +3567,9 @@ impl App { } SettingsTab::Updates => { section(ui, "AnyBot 更新", p); - setting_row(ui, p, "版本", &version_label(self.exe_built), |ui| { + setting_row(ui, p, "版本", &crate::version::full(self.exe_built), |ui| { if let Some(tm) = self.newer_build { - ui.label(RichText::new(format!("{}{}", t("有更新的版本:"), version_label(Some(tm)))).size(12.0).color(p.accent)); + ui.label(RichText::new(format!("{}{}", t("有更新的版本:"), crate::version::time_label(Some(tm)))).size(12.0).color(p.accent)); } else { ui.label(RichText::new(t("已是最新版本")).size(12.0).color(p.text3)); } @@ -3766,7 +3766,7 @@ impl App { // Noticing a new build is a cheap file check, so the banner keeps up quickly (estimated 10 s). if self.last_build_check.elapsed().as_secs() >= 10 { self.last_build_check = Instant::now(); - self.newer_build = match (exe_modified(), self.exe_built) { + self.newer_build = match (crate::version::exe_modified(), self.exe_built) { (Some(now), Some(started)) if now > started => Some(now), _ => None, }; @@ -4315,16 +4315,6 @@ impl eframe::App for App { // ---------- helpers ---------- -/// When the program file was last written (= when this build was made). -fn exe_modified() -> Option { - std::env::current_exe().ok().and_then(|p| std::fs::metadata(p).ok()).and_then(|m| m.modified().ok()) -} - -/// "2026-11-03 20:57" in local time, or "?" when unknown. -fn version_label(t: Option) -> String { - t.map(|t| chrono::DateTime::::from(t).format("%Y-%m-%d %H:%M").to_string()).unwrap_or_else(|| "?".into()) -} - /// How often the relaunch helper checks whether the old copy has exited /// (`while kill -0 "$pid" …; do sleep 0.2; done; exec "$app"`). pub const RELAUNCH_POLL_SECS: f32 = 0.2; diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index e1f6152..67f0e23 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1374,7 +1374,7 @@ impl App { let log = crate::cloudbox::log_lines(); let mut out = json!({ "role": if owner { "owner" } else { "admin" }, - "host": st.remote.host_name, "version": version_label(self.exe_built), "newer": self.newer_build.is_some(), + "host": st.remote.host_name, "version": crate::version::LABEL, "built": crate::version::time_label(self.exe_built), "newer": self.newer_build.is_some(), "theme": match st.theme { Theme::Light => "light", Theme::Dark => "dark", Theme::System => "system" }, "accent": serde_json::to_value(st.accent).unwrap_or_default(), "timezone": st.timezone, "notify": st.notify, "language": st.language, diff --git a/src/app/sidebar_ui.rs b/src/app/sidebar_ui.rs index f945572..473a47d 100644 --- a/src/app/sidebar_ui.rs +++ b/src/app/sidebar_ui.rs @@ -203,7 +203,7 @@ impl App { } }); if let Some(tm) = self.newer_build { - if crate::icons::pill(ui, crate::icons::Icon::Update, &format!("{}({})", t("重新啟動以更新"), version_label(Some(tm))), p.accent, Color32::WHITE, 30.0).clicked() { + if crate::icons::pill(ui, crate::icons::Icon::Update, &format!("{}({})", t("重新啟動以更新"), crate::version::time_label(Some(tm))), p.accent, Color32::WHITE, 30.0).clicked() { self.relaunch_requested = true; } } diff --git a/src/main.rs b/src/main.rs index 72a5b90..6663182 100644 --- a/src/main.rs +++ b/src/main.rs @@ -63,6 +63,7 @@ mod docindex; mod drops; mod vault; mod vault_store; +mod version; mod vnc; mod voice; #[cfg(target_os = "windows")] @@ -248,6 +249,7 @@ const USAGE: &str = "用法: anybot --ask 問題… 問第一個 Bot 一句,印出回答(測試用) anybot setup … 在沒有螢幕的機器上設定 anybot --screenshot 檔名 把視窗畫成一張圖 + anybot --version 印出版本(v0.0.1-36bc2be · 建置時間) 資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)"; fn fetch_skill_text(src: &str) -> Result { @@ -265,6 +267,11 @@ fn fetch_skill_text(src: &str) -> Result { fn main() -> eframe::Result<()> { let args: Vec = std::env::args().collect(); + // Before anything else: no data folder, no window. + if matches!(args.get(1).map(String::as_str), Some("--version" | "-V")) { + println!("AnyBot {}", version::full(version::exe_modified())); + return Ok(()); + } // P7: install a skill file (a path or a URL) and be done: skills are .md files you can keep in a repo. if let Some(i) = args.iter().position(|a| a == "--install-skill") { let src = args.get(i + 1).cloned().unwrap_or_default(); @@ -345,6 +352,8 @@ fn main() -> eframe::Result<()> { } // No window: keep the bots working and answer the phone (always-on Mac or server). if args.iter().any(|a| a == "--serve") { + // The first line of the log says which build is running (make server-logs, journalctl). + eprintln!("AnyBot {}", version::full(version::exe_modified())); let ctx = egui::Context::default(); let _folder = take_folder_or_exit(); app::App::serve(&ctx); diff --git a/src/version.rs b/src/version.rs new file mode 100644 index 0000000..520c837 --- /dev/null +++ b/src/version.rs @@ -0,0 +1,46 @@ +//! Which build this is: "v0.0.1-36bc2be" (build.rs), and when it was built. + +use std::time::SystemTime; + +/// "v0.0.1-36bc2be", "v0.0.1-36bc2be-dirty" (built with uncommitted changes), or "v0.0.1". +pub const LABEL: &str = env!("ANYBOT_VERSION"); + +/// When the program file was last written (= when this build was made; a newer one replacing it is +/// how an update is noticed). +pub fn exe_modified() -> Option { + std::env::current_exe().ok().and_then(|p| std::fs::metadata(p).ok()).and_then(|m| m.modified().ok()) +} + +/// "2026-11-03 20:57" in local time, or "?" when unknown. +pub fn time_label(t: Option) -> String { + t.map(|t| chrono::DateTime::::from(t).format("%Y-%m-%d %H:%M").to_string()).unwrap_or_else(|| "?".into()) +} + +/// "v0.0.1-36bc2be · 2026-11-11 14:20": the version and when this build was made. +pub fn full(built: Option) -> String { + match built { + Some(_) => format!("{LABEL} · {}", time_label(built)), + None => LABEL.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn label_is_v_number_dash_commit() { + let number = env!("CARGO_PKG_VERSION"); + assert!(LABEL.starts_with(&format!("v{number}")), "{LABEL}"); + let rest = &LABEL[1 + number.len()..]; + // A commit, maybe "-dirty"; or nothing outside git. + assert!(rest.is_empty() || rest.starts_with('-'), "{LABEL}"); + } + + #[test] + fn full_adds_the_build_time() { + assert_eq!(full(None), LABEL); + let s = full(Some(SystemTime::UNIX_EPOCH)); + assert!(s.starts_with(&format!("{LABEL} · ")) && s.len() > LABEL.len() + 10, "{s}"); + } +}