larust-cli 0.8.0

A Laravel-shaped web framework for Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! `xr upgrade` - by default, reinstalls `larust-cli` from crates.io
//! (`cargo install larust-cli[, --force]`), matching an `xr` that was
//! installed that way in the first place: every Larust crate is published
//! now, so there's no checkout to pull for an `xr` installed straight
//! from the registry, and nothing to compare commits against either.
//!
//! `--legacy` instead keeps this command's original mechanism entirely:
//! checks the checkout this `xr` was built from (baked in at build time,
//! see `build.rs`) for new commits on the current branch's upstream, and
//! if there are any, fast-forwards and reinstalls `xr` from it via
//! `cargo install --path`. `--force` (with `--legacy`) skips that check
//! entirely and just reinstalls from the checkout's current state - the
//! "repair/reinstall now" mode, equivalent to re-running `install.sh`/
//! `install.ps1`. Kept, not removed, for an `xr` actually installed that
//! way - `install.sh`/`install.ps1`/`cargo install --path` from a real
//! checkout, the only install method that existed before every crate was
//! published - which has nothing to do with the crates.io registry at
//! all and would gain nothing from the new default.
//!
//! **Why `--legacy` compares commit hashes, not semver**: a checkout
//! tracks a branch, not a tag - most commits on it were never `xr
//! release`d, so comparing against `Cargo.toml`'s own version would miss
//! everything between releases. A commit hash is always accurate with
//! zero bookkeeping either way, so that's what `xr --version`/this
//! module's legacy path compare, via `LARUST_GIT_COMMIT` (`build.rs`).
//! The crates.io default doesn't need this at all - `cargo install` has
//! its own, real version comparison against the registry already.
//!
//! **Why a baked-in checkout path, not "run this from inside the
//! checkout"**: today's actual usage pattern is one machine building and
//! installing `xr` from its own local clone (`install.sh`/`install.ps1`,
//! `cargo install --path crates/larust-cli`) - `LARUST_CHECKOUT_ROOT`
//! (`build.rs`) just remembers where that was, so `xr upgrade` works from
//! any directory (a scaffolded app's own, most of the time) the same way
//! every other `xr` command does, rather than requiring a `cd` back to the
//! checkout first.
//!
//! **Overridable, because "baked in" genuinely doesn't survive every real
//! scenario**: reported directly - the checkout location varies by
//! installation and differs between a developer's own machine and however
//! a deployment ends up laying files out, so a value frozen into the
//! binary at the *original* `cargo install` time is the wrong thing to
//! trust unconditionally forever after. An environment variable of the
//! same name, `LARUST_CHECKOUT_ROOT` (read from the process environment or
//! a `.env` file in the current directory - the identical `dotenvy::
//! from_filename(".env").ok()` pattern `restart.rs`/`dev.rs`'s own
//! `APP_NAME`/`DEPLOY_TYPE` reads already use, for the same "this runs
//! outside any compiled app, so it can't go through `larust_core::Config`"
//! reason), wins over the compile-time default whenever it's set - the
//! same override precedence `RUST_LOG` already has over this crate's own
//! hardcoded logging default. Covers a moved checkout, a prebuilt `xr`
//! binary shared across machines, or a deployment layout that never
//! matches wherever `xr` happened to be built, all without needing to
//! rebuild/reinstall `xr` itself just to teach it a new path.
//!
//! **Never force-pushes/rewrites/discards anything**: the pull step is
//! `git merge --ff-only`, never `--hard` or `-f` - a non-fast-forward
//! history (local commits, a rebased upstream) or uncommitted local changes
//! that would be overwritten both fail loudly (git's own refusal, not a
//! bypass) rather than being resolved automatically.
//!
//! **"Up to date" means the checkout matches its upstream *and* the
//! installed binary - not just the first half**: reported directly, a real
//! bug, not hypothetical - a checkout that had been fast-forwarded by
//! something other than a successful `xr upgrade` run (a plain `git pull`,
//! or an earlier `xr upgrade` that pulled but then failed partway through
//! `cargo install`) left the *installed* `xr` permanently stale, with `xr
//! upgrade` reporting "already up to date" forever after: the original
//! check only ever compared the checkout's own `HEAD` against its
//! upstream, never against `BUILT_COMMIT` (what's actually installed), so
//! once the checkout itself had nothing left to pull, this command
//! considered its job done regardless of whether a reinstall had ever
//! actually happened. [`plan`] now takes `BUILT_COMMIT` into account too -
//! see that function's own doc comment for the exact three-way decision.

use crate::{kill, process_scan};
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

const BUILT_COMMIT: &str = env!("LARUST_GIT_COMMIT");
const CHECKOUT_ROOT: &str = env!("LARUST_CHECKOUT_ROOT");

/// `xr --version`'s own string - `CARGO_PKG_VERSION` plus the commit this
/// binary was actually built from, since the former alone never changes.
pub const VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    " (",
    env!("LARUST_GIT_COMMIT"),
    ")"
);

pub fn run(force: bool, legacy: bool, stop_running: bool) -> Result<()> {
    if legacy {
        run_legacy(force, stop_running)
    } else {
        run_from_crates_io(force, stop_running)
    }
}

/// Checked right before either path's own `cargo install` call - reported
/// directly as the actual blocker behind a confusing Windows failure:
/// `cargo install`'s final step moves its freshly-built binary over the
/// one already installed, which fails outright with "Access is denied"
/// if anything at all still has that file open, and `xr list` has no way
/// to explain it when the culprit was never a tracked `xr dev` session to
/// begin with (see `process_scan`'s own doc comment). Checking proactively,
/// rather than trying to pattern-match `cargo`'s own error text after the
/// fact, works regardless of exactly how `cargo` phrases the failure and
/// catches it before wasting a full rebuild on a `cargo install` that was
/// always going to fail at its very last step.
fn ensure_binary_not_locked(stop_running: bool) -> Result<()> {
    let other_pids = process_scan::other_running_xr_pids();
    if other_pids.is_empty() {
        return Ok(());
    }

    if stop_running {
        println!(
            "xr upgrade: stopping {} other running `xr` process(es) first...",
            other_pids.len()
        );
        return kill::kill_all();
    }

    anyhow::bail!(
        "{} other `xr` process(es) are still running (pid(s): {}) - one of them is almost \
         certainly holding the installed `xr` binary open, which is what actually fails \
         `cargo install`'s own last step (moving the new binary into place) on Windows. \
         Re-run with `--stop-running` to stop them first, or run `xr kill --all` yourself, \
         then retry.",
        other_pids.len(),
        other_pids
            .iter()
            .map(|pid| pid.to_string())
            .collect::<Vec<_>>()
            .join(", "),
    );
}

/// The default path: every Larust crate - `larust-cli` included - is
/// published, so "upgrade" is just "reinstall whatever's newest from the
/// registry". `cargo install larust-cli` already no-ops (prints "already
/// installed") when nothing's newer, without needing `--force` to detect
/// that itself - `--force` here only matters for an unconditional
/// reinstall of the *same* version (a corrupted binary, a `rustc` bump
/// worth rebuilding against), not for detecting that an upgrade exists.
fn run_from_crates_io(force: bool, stop_running: bool) -> Result<()> {
    ensure_binary_not_locked(stop_running)?;
    println!("xr upgrade: reinstalling larust-cli from crates.io...");
    let mut command = Command::new("cargo");
    command.args(["install", "larust-cli"]);
    if force {
        command.arg("--force");
    }
    let status = command
        .status()
        .context("failed to run cargo install larust-cli")?;
    anyhow::ensure!(
        status.success(),
        "cargo install larust-cli failed - see the output above"
    );
    println!("xr upgrade: done - `xr --version` will show the new version on next run");
    Ok(())
}

fn run_legacy(force: bool, stop_running: bool) -> Result<()> {
    dotenvy::from_filename(".env").ok();
    let checkout = checkout_root()?;

    if force {
        println!("xr upgrade: reinstalling from {} ...", checkout.display());
        return reinstall(&checkout, stop_running);
    }

    println!("xr upgrade: checking {} for updates...", checkout.display());
    run_git(&checkout, &["fetch"])?;

    let local_head = run_git_output(&checkout, &["rev-parse", "HEAD"])?;
    let upstream = run_git_output(&checkout, &["rev-parse", "@{u}"]).context(
        "the current branch in that checkout has no upstream tracking branch configured - \
         set one (e.g. `git branch --set-upstream-to=origin/main`) or use `xr upgrade --legacy \
         --force` to reinstall from the checkout's current state without checking",
    )?;

    match plan(&local_head, &upstream, BUILT_COMMIT) {
        Plan::UpToDate => {
            println!(
                "xr upgrade: already up to date (built from commit {})",
                short(BUILT_COMMIT)
            );
            Ok(())
        }
        Plan::ReinstallOnly => {
            // The checkout has nothing new to *pull* - but it's already
            // ahead of whatever's actually installed, so comparing only
            // `local_head` against `upstream` (the original, and only,
            // check here) would report "already up to date" forever. Real
            // bug this fixes, not hypothetical: reported directly - a
            // checkout fast-forwarded to the latest commit by something
            // other than a successful `xr upgrade` run (a plain `git
            // pull`, or an earlier `xr upgrade` that pulled but then
            // failed partway through `cargo install`) left the installed
            // binary permanently stale, with `xr upgrade` reporting "up to
            // date" on every later run since it never once compared itself
            // against the checkout it was supposedly checking.
            println!(
                "xr upgrade: the checkout is already at {} but the installed xr was built from \
                 {} - reinstalling...",
                short(&local_head),
                short(BUILT_COMMIT)
            );
            reinstall(&checkout, stop_running)
        }
        Plan::PullAndReinstall => {
            println!(
                "xr upgrade: new commits available ({} -> {}) - pulling...",
                short(&local_head),
                short(&upstream)
            );
            // Fast-forward only - see this module's own doc comment on why
            // nothing here is allowed to rewrite or discard local history.
            let status = Command::new("git")
                .args(["merge", "--ff-only", "@{u}"])
                .current_dir(&checkout)
                .status()
                .context("failed to run git merge --ff-only")?;
            anyhow::ensure!(
                status.success(),
                "git merge --ff-only failed - the checkout at {} likely has local changes or \
                 diverged history; resolve that yourself, then re-run `xr upgrade`",
                checkout.display()
            );
            reinstall(&checkout, stop_running)
        }
    }
}

/// What `run()` should do, decided purely from three commit hashes - split
/// out so it's unit-testable without any real git/process I/O. Checked in
/// this order: a checkout behind its own upstream always needs a pull
/// (regardless of what's currently installed - the merge below will move
/// `local_head` past `built_commit` too); only once the checkout matches
/// its upstream does whether the *installed binary* also matches become
/// the deciding factor.
#[derive(Debug, PartialEq, Eq)]
enum Plan {
    UpToDate,
    ReinstallOnly,
    PullAndReinstall,
}

fn plan(local_head: &str, upstream: &str, built_commit: &str) -> Plan {
    if local_head != upstream {
        Plan::PullAndReinstall
    } else if local_head != built_commit {
        Plan::ReinstallOnly
    } else {
        Plan::UpToDate
    }
}

fn reinstall(checkout: &Path, stop_running: bool) -> Result<()> {
    ensure_binary_not_locked(stop_running)?;
    println!("xr upgrade: rebuilding and reinstalling xr...");
    let status = Command::new("cargo")
        .args(["install", "--path", "crates/larust-cli", "--force"])
        .current_dir(checkout)
        .status()
        .context("failed to run cargo install")?;
    anyhow::ensure!(
        status.success(),
        "cargo install failed - see the output above"
    );
    println!("xr upgrade: done - `xr --version` will show the new commit on next run");
    Ok(())
}

/// Resolves the checkout to operate on - `LARUST_CHECKOUT_ROOT` (env var or
/// `.env`, checked by the caller before this runs) if set, otherwise the
/// path baked in at build time. Either way, validates it still looks like a
/// real Larust git checkout before touching it: the compile-time default
/// can go stale (moved, deleted, or this binary copied to a machine that
/// never had it) since it was captured once and never re-checked, and an
/// override is just as capable of pointing at a typo'd or since-deleted
/// path - both deserve the same clear failure rather than a confusing
/// `git`/`cargo` error several steps further in.
fn checkout_root() -> Result<PathBuf> {
    let (root, source) = resolve_checkout_root(std::env::var("LARUST_CHECKOUT_ROOT").ok());
    anyhow::ensure!(
        root.join("Cargo.toml").is_file() && root.join(".git").exists(),
        "{source} ({}) no longer looks like a Larust git checkout - cd there yourself and run \
         `git pull && cargo install --path crates/larust-cli --force` (or re-clone and re-run \
         install.sh/install.ps1), or fix/unset LARUST_CHECKOUT_ROOT if it's pointing at the \
         wrong place",
        root.display()
    );
    Ok(root)
}

/// The pure decision behind [`checkout_root`], split out so it's
/// unit-testable without touching the real process environment - mutating
/// `LARUST_CHECKOUT_ROOT` for a test would race every other test in this
/// binary reading environment state concurrently (`cargo test` runs them
/// on shared threads in one process), the same hazard `dev.rs`'s own
/// `LARUST_DEV_RELOAD` set-once-at-startup comment already documents for
/// the identical reason.
fn resolve_checkout_root(env_override: Option<String>) -> (PathBuf, &'static str) {
    match env_override {
        Some(value) if !value.is_empty() => (PathBuf::from(value), "LARUST_CHECKOUT_ROOT"),
        _ => (
            PathBuf::from(CHECKOUT_ROOT),
            "the checkout this `xr` was built from",
        ),
    }
}

fn run_git(dir: &Path, args: &[&str]) -> Result<()> {
    let status = Command::new("git")
        .args(args)
        .current_dir(dir)
        .status()
        .with_context(|| format!("failed to run git {}", args.join(" ")))?;
    anyhow::ensure!(status.success(), "git {} failed", args.join(" "));
    Ok(())
}

fn run_git_output(dir: &Path, args: &[&str]) -> Result<String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(dir)
        .output()
        .with_context(|| format!("failed to run git {}", args.join(" ")))?;
    anyhow::ensure!(output.status.success(), "git {} failed", args.join(" "));
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

fn short(commit: &str) -> &str {
    &commit[..commit.len().min(12)]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plan_pulls_and_reinstalls_when_the_checkout_is_behind_its_upstream() {
        assert_eq!(plan("aaa", "bbb", "aaa"), Plan::PullAndReinstall);
    }

    #[test]
    fn plan_reinstalls_only_when_the_checkout_matches_upstream_but_not_the_installed_binary() {
        // The exact bug this closes: nothing to *pull* (checkout already
        // matches its own upstream), but the installed binary was built
        // from an older commit - reported directly, from a checkout that
        // had been fast-forwarded by something other than `xr upgrade`
        // itself.
        assert_eq!(plan("ccc", "ccc", "aaa"), Plan::ReinstallOnly);
    }

    #[test]
    fn plan_reports_up_to_date_only_when_all_three_commits_match() {
        assert_eq!(plan("aaa", "aaa", "aaa"), Plan::UpToDate);
    }

    #[test]
    fn resolve_checkout_root_uses_the_override_when_set() {
        let (root, source) = resolve_checkout_root(Some("/somewhere/else".to_string()));
        assert_eq!(root, PathBuf::from("/somewhere/else"));
        assert_eq!(source, "LARUST_CHECKOUT_ROOT");
    }

    #[test]
    fn resolve_checkout_root_falls_back_to_the_baked_in_default_when_unset() {
        let (root, source) = resolve_checkout_root(None);
        assert_eq!(root, PathBuf::from(CHECKOUT_ROOT));
        assert_eq!(source, "the checkout this `xr` was built from");
    }

    #[test]
    fn resolve_checkout_root_treats_an_empty_override_the_same_as_unset() {
        // `LARUST_CHECKOUT_ROOT=` (set but empty) - e.g. a `.env` line left
        // as a commented-out-looking placeholder that got uncommented by
        // mistake - degrades to the default rather than trying to treat an
        // empty path as a real checkout.
        let (root, source) = resolve_checkout_root(Some(String::new()));
        assert_eq!(root, PathBuf::from(CHECKOUT_ROOT));
        assert_eq!(source, "the checkout this `xr` was built from");
    }

    #[test]
    fn short_truncates_a_full_hash_to_twelve_characters() {
        let full = "a1b2c3d4e5f60789abcdef0123456789abcdef0";
        assert_eq!(short(full).len(), 12);
        assert_eq!(short(full), "a1b2c3d4e5f6");
    }

    #[test]
    fn short_leaves_a_shorter_string_untouched() {
        assert_eq!(short("unknown"), "unknown");
        assert_eq!(short(""), "");
    }
}