Skip to main content

kanbrain_core/cli/
update.rs

1//! `kb update`, and the app's update: installs the latest release over this one, by running the installer the
2//! README gives, which downloads it, checks its checksum and replaces the binaries, then runs the new version's
3//! `init --all`, so none of that is repeated here. Never while an agent works on a task: `init --all` would rewrite
4//! its instructions and a migration its data mid-session.
5
6use super::Program;
7use crate::model::Author;
8use anyhow::{Context, Result, bail};
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11
12/// The installer for Linux and macOS, as the latest release has it: `main`'s may already expect a release that
13/// isn't out.
14const INSTALL_SH: &str = "https://github.com/singudotdev/kanbrain/releases/latest/download/install.sh";
15
16/// The installer for Windows, likewise.
17pub const INSTALL_PS1: &str = "https://github.com/singudotdev/kanbrain/releases/latest/download/install.ps1";
18
19/// Redirects to the latest release's page, whose address ends in its tag. A redirect, not GitHub's API, which
20/// limits how often an address may ask.
21const LATEST: &str = "https://github.com/singudotdev/kanbrain/releases/latest";
22
23/// Where the installer's macOS app bundle says the binaries are, relative to its executable: the bundle's is a
24/// link to the app in the install folder, which is the one to replace.
25const BUNDLE_INSTALL_DIR: &str = "../Resources/install-dir";
26
27/// Which apps are installed in `dir`, as the installer's `--app` names them: the one running is, and
28/// the other is updated along with it when it's there too.
29fn installed_app(dir: &Path) -> &'static str {
30    let has = |name: &str| dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX)).is_file();
31    match (has("kb"), has("kanbrain")) {
32        (true, true) => "both",
33        (false, true) => "gui",
34        _ => "cli",
35    }
36}
37
38/// Whether `dir` is cargo's folder of installed programs (`$CARGO_HOME/bin`, else `~/.cargo/bin`): a program
39/// there came from `cargo install`, which keeps its own record of what it installed.
40fn installed_by_cargo(dir: &Path, cargo_home: Option<PathBuf>) -> bool {
41    let Some(home) = cargo_home.or_else(|| dirs::home_dir().map(|home| home.join(".cargo"))) else { return false };
42    let canonical = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
43    canonical(dir) == canonical(&home.join("bin"))
44}
45
46/// How the running program was installed, which says how to update it.
47#[derive(Debug, PartialEq, Eq)]
48pub enum Install {
49    /// With `cargo install`, which keeps its own record of what it installed: the installer would replace the
50    /// file behind cargo's back.
51    Cargo,
52    /// By the installer, into `dir`, with `app` (its `--app`) there.
53    Installer {
54        /// The install folder.
55        dir: PathBuf,
56        /// `cli`, `gui` or `both`.
57        app: &'static str,
58    },
59}
60
61/// How the program at `exe` was installed.
62pub fn install_of(exe: &Path) -> Result<Install> {
63    let dir = exe.parent().context("finding this program's folder")?;
64    if installed_by_cargo(dir, std::env::var_os("CARGO_HOME").map(PathBuf::from)) {
65        return Ok(Install::Cargo);
66    }
67    let dir = match std::fs::read_to_string(dir.join(BUNDLE_INSTALL_DIR)) {
68        Ok(text) => PathBuf::from(text.trim_end()),
69        Err(_) => dir.to_path_buf(),
70    };
71    Ok(Install::Installer { app: installed_app(&dir), dir })
72}
73
74/// The tasks agents are working on, in doing, in every registered repository and the central brain, as
75/// `shop/api #3 title` (`#3 title` in the central brain), as `kb status` names them: an update waits for them. A
76/// brain that can't be read, such as one a newer kanbrain wrote, has none to wait for.
77pub fn agents_working(central: &Path) -> Result<Vec<String>> {
78    let mut working = Vec::new();
79    for (label, tasks) in super::every_brain(central)? {
80        working.extend(
81            tasks.iter().filter(|t| t.doing_by(Author::Agent)).map(|t| format!("{label}#{} {}", t.id, t.title)),
82        );
83    }
84    Ok(working)
85}
86
87/// Refuses while [`agents_working`] finds any, naming them.
88pub fn check_no_agent_working(central: &Path) -> Result<()> {
89    let working = agents_working(central)?;
90    if !working.is_empty() {
91        bail!(
92            "agents are working on {}: update once they're done or parked, so their instructions and data don't \
93             change under them",
94            working.join(", ")
95        );
96    }
97    Ok(())
98}
99
100/// The latest release's version, `X.Y.Z`, when it's newer than this one. Asks GitHub, through curl, for where its
101/// latest release is.
102pub fn newer_release() -> Result<Option<String>> {
103    let mut curl = Command::new("curl");
104    curl.args(["-fsSI", "--max-time", "20", "--", LATEST]);
105    hide_console(&mut curl);
106    let out = curl.output().context("running curl, which asks for the latest release")?;
107    if !out.status.success() {
108        bail!("couldn't ask {LATEST} for the latest release");
109    }
110    let latest = redirected_version(&String::from_utf8_lossy(&out.stdout))
111        .context("the latest release's address has no version")?;
112    Ok(newer(&latest, env!("CARGO_PKG_VERSION")).then_some(latest))
113}
114
115/// What `program`'s `update` says instead of reinstalling, when the latest release is this one (or older, a build
116/// ahead of it); `None` to install: a newer release, or none found (the installer then says why it can't download).
117fn up_to_date(newer: &Result<Option<String>>, program: Program) -> Option<String> {
118    matches!(newer, Ok(None))
119        .then(|| format!("{} {} is the latest release: nothing to update", program.name, env!("CARGO_PKG_VERSION")))
120}
121
122/// What `program`'s `update` says when cargo installed it, which keeps its own record of what it installed: the
123/// command that updates it, [`cargo_update_command`], and then the projects.
124fn cargo_update(program: Program, release: Option<&str>) -> String {
125    format!(
126        "{} was installed with cargo: update it, and then every project's agent instructions, with\n\n  {} && {} init \
127         --all",
128        program.name,
129        cargo_update_command(program, release),
130        program.name
131    )
132}
133
134/// The `cargo install` that updates `program` to `release` (`X.Y.Z`), or to the latest when it isn't known. The
135/// crate `kanbrain` on crates.io is the command line, whose latest cargo installs; the kanban app's, `kanbrain-app`,
136/// isn't there (GPUI comes from git), so it comes from the repository, at the release's tag, else at `main`, which is
137/// the latest release. The app is told apart by its name, `kanbrain`: [`Program`] says nothing else about it, and a
138/// field it gained would break code building one.
139pub fn cargo_update_command(program: Program, release: Option<&str>) -> String {
140    if program.name != "kanbrain" {
141        return "cargo install kanbrain".to_string();
142    }
143    let tag = release.map(|version| format!(" --tag v{version}")).unwrap_or_default();
144    format!("cargo install --locked --git https://github.com/singudotdev/kanbrain{tag} kanbrain-app")
145}
146
147/// The version at the end of the address a response's headers redirect to, `…/tag/vX.Y.Z`.
148fn redirected_version(headers: &str) -> Option<String> {
149    let location = headers.lines().find_map(|line| {
150        let (name, value) = line.split_once(':')?;
151        name.eq_ignore_ascii_case("location").then(|| value.trim())
152    })?;
153    location.rsplit_once("/tag/v").map(|(_, version)| version.to_string())
154}
155
156/// Whether version `a` comes after `b`, both `X.Y.Z`; a part that isn't a number counts as 0.
157fn newer(a: &str, b: &str) -> bool {
158    let parts = |v: &str| -> Vec<u64> { v.split('.').map(|p| p.parse().unwrap_or(0)).collect() };
159    parts(a) > parts(b)
160}
161
162/// Keeps a console window from flashing up when the app, which has none, runs a program on Windows.
163pub fn hide_console(command: &mut Command) {
164    #[cfg(windows)]
165    {
166        use std::os::windows::process::CommandExt;
167        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
168        command.creation_flags(CREATE_NO_WINDOW);
169    }
170    #[cfg(not(windows))]
171    let _ = command;
172}
173
174/// The installer's variables that say to do something else than install the latest release: left set in a shell
175/// from an uninstall or a pinned install, they'd have an update uninstall, purge without asking, or reinstall
176/// that version instead. An update runs the installer without them.
177pub(crate) const INSTALLER_CHOICES: [&str; 4] =
178    ["KANBRAIN_UNINSTALL", "KANBRAIN_PURGE", "KANBRAIN_YES", "KANBRAIN_VERSION"];
179
180/// PowerShell that clears [`INSTALLER_CHOICES`] in its session, to run before the installer there.
181pub fn clear_installer_choices_ps1() -> String {
182    let vars: Vec<String> = INSTALLER_CHOICES.iter().map(|v| format!("Env:{v}")).collect();
183    format!("Remove-Item {} -ErrorAction SilentlyContinue", vars.join(", "))
184}
185
186/// `text` as a PowerShell single-quoted string literal, which PowerShell reads back to exactly `text`, whatever its
187/// characters: for a folder or file in a command or script made for PowerShell. Nothing expands in single quotes,
188/// neither `$` nor a backtick; only a single quote is special, written twice, and PowerShell takes the typographic
189/// ones (`‘ ’ ‚ ‛`) for one too.
190pub fn powershell_string(text: &str) -> String {
191    let mut quoted = String::with_capacity(text.len() + 2);
192    quoted.push('\'');
193    for c in text.chars() {
194        if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
195            quoted.push(c);
196        }
197        quoted.push(c);
198    }
199    quoted.push('\'');
200    quoted
201}
202
203/// The PowerShell command that installs the latest release of `app` into `dir`, on Windows, where a running
204/// program's file can't be replaced, so `update` prints it, to run once the program and the app are closed.
205fn windows_update_command(dir: &Path, app: &str) -> String {
206    format!(
207        "{}; $env:KANBRAIN_APP = {}; $env:KANBRAIN_INSTALL_DIR = {}; irm {INSTALL_PS1} | iex",
208        clear_installer_choices_ps1(),
209        powershell_string(app),
210        powershell_string(&dir.display().to_string())
211    )
212}
213
214/// The shell that runs the installer script given on its stdin, for `app` into `dir`, without
215/// [`INSTALLER_CHOICES`].
216fn installer_shell(dir: &Path, app: &str) -> Command {
217    let mut sh = Command::new("sh");
218    sh.args(["-s", "--", "--app", app, "--dir"]).arg(dir);
219    for var in INSTALLER_CHOICES {
220        sh.env_remove(var);
221    }
222    sh
223}
224
225/// Runs the installer for `app` into `dir`, on Linux and macOS: the binaries are replaced by renaming, so the
226/// running ones carry on. `captured`, its messages are kept out of sight and the last of them make up the error
227/// when it fails, as the app wants; otherwise they're printed.
228pub fn run_installer(dir: &Path, app: &str, captured: bool) -> Result<()> {
229    // The script goes from curl to sh through a pipe, and the folder as an argument of its own, so
230    // nothing here is ever read by a shell as code.
231    let mut curl = Command::new("curl")
232        .args(["-fsSL", "--", INSTALL_SH])
233        .stdout(Stdio::piped())
234        .spawn()
235        .context("running curl, which downloads the installer")?;
236    let script = curl.stdout.take().context("reading curl's output")?;
237    let mut sh = installer_shell(dir, app);
238    sh.stdin(script);
239    let (installed, said) = if captured {
240        let out = sh.output().context("running the installer")?;
241        let said = String::from_utf8_lossy(&out.stderr).trim().lines().last().unwrap_or_default().to_string();
242        (out.status, said)
243    } else {
244        (sh.status().context("running the installer")?, "its messages are above".to_string())
245    };
246    let downloaded = curl.wait().context("waiting for curl")?;
247    if !downloaded.success() {
248        bail!("couldn't download the installer from {INSTALL_SH}");
249    }
250    if !installed.success() {
251        bail!("the installer failed ({said})");
252    }
253    Ok(())
254}
255
256/// [`update_program`] for `kb`, which this always names.
257#[deprecated(since = "0.6.3", note = "use `update_program`, which names the program running in what it says")]
258pub fn update(central: &Path) -> Result<()> {
259    update_program(central, Program { name: "kb" })
260}
261
262/// `program`'s `update`: runs the installer for the apps installed where this program is, into the same folder,
263/// unless an agent is working. On Windows it prints the PowerShell command instead, since a running program's file
264/// can't be replaced there. Installed with `cargo install`, it says how cargo updates it instead.
265pub fn update_program(central: &Path, program: Program) -> Result<()> {
266    check_no_agent_working(central)?;
267    let newer = newer_release();
268    if let Some(said) = up_to_date(&newer, program) {
269        println!("{said}");
270        return Ok(());
271    }
272    let exe = std::env::current_exe().context("finding this program's file")?;
273    let Install::Installer { dir, app } = install_of(&exe)? else {
274        println!("{}", cargo_update(program, newer.ok().flatten().as_deref()));
275        return Ok(());
276    };
277    if cfg!(windows) {
278        println!("Close kanbrain, then run in PowerShell:\n\n  {}", windows_update_command(&dir, app));
279        return Ok(());
280    }
281    run_installer(&dir, app, false)
282}
283
284#[cfg(test)]
285#[path = "../../tests/cli/update.rs"]
286mod tests;