navi-notifier 0.2.8

A friendly helper to guide you through the day-to-day noise of code review.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! `navi upgrade` / `navi downgrade`, plus a once-a-day "newer release" hint.
//!
//! Upgrades re-run the cargo-dist installer for the target release (the same
//! mechanism `curl .../sh/navi | bash` uses), so there's no bundled updater or
//! extra TLS stack. `cargo install` copies should upgrade through cargo instead.

use std::io::IsTerminal;
use std::path::PathBuf;
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{env, fs, sync::mpsc, thread};

use anyhow::{bail, Context, Result};

use crate::prompt::confirm;

/// Source repo for release discovery and the installer artifacts.
const REPO: &str = "lararosekelley/navi";
const REPO_URL: &str = "https://github.com/lararosekelley/navi";
/// The first release that shipped `downgrade`, and the floor it can reach: going
/// below would strand the user on a binary with no `downgrade`. v0.1.4 shipped
/// without these commands, so the first release with them is 0.1.5. Bump this if
/// they first land in a different version.
const MIN_DOWNGRADE_VERSION: &str = "0.1.5";

/// Stamp next to the receipt; one release check per day. Opt out with
/// `NAVI_NO_UPDATE_CHECK=1`.
const UPDATE_CHECK_FILE: &str = "update-check";
const CHECK_INTERVAL_SECS: u64 = 24 * 60 * 60;

/// navi's config directory (where the update-check stamp lives).
pub(crate) fn config_dir() -> Option<PathBuf> {
    let base = env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .or_else(|| env::var_os("LOCALAPPDATA").map(PathBuf::from))
        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
    Some(base.join("navi"))
}

pub fn upgrade(head: bool, force: bool, no_restart: bool) -> Result<()> {
    if head {
        // --head cargo-installs to ~/.cargo/bin, a different path than the service
        // runs, so a restart wouldn't pick it up; leave the service alone.
        return upgrade_to_head();
    }
    let installed = env!("CARGO_PKG_VERSION");
    // Skip a redundant re-download when we're already current, unless --force.
    // Compare against the latest *published* release (what the installer actually
    // fetches), not git tags: a release workflow pushes the tag minutes before it
    // publishes the release, and using tags would make us "upgrade" to a version
    // that isn't installable yet, reinstalling the current one in a loop.
    // Best-effort: if the lookup or parsing fails, fall through and install.
    let latest = if force {
        None
    } else {
        latest_release_version()
    };
    if let Some(installed_version) = parse_version(installed) {
        if !upgrade_needed(installed_version, latest, force) {
            println!(
                "navi {installed} is already the latest release; nothing to upgrade (use --force to reinstall)"
            );
            return Ok(());
        }
    }
    println!("upgrading navi to the latest release");
    run_installer(None)?;
    println!("upgraded (re-open your shell if the version looks stale)");
    crate::service::restart_after_upgrade(!no_restart)?;
    Ok(())
}

fn upgrade_to_head() -> Result<()> {
    println!("--head builds and installs the latest unreleased commit from {REPO_URL}");
    println!("HEAD is a pre-release snapshot: it may be broken or untested");
    if !confirm("continue? [y/N] ")? {
        println!("upgrade cancelled");
        return Ok(());
    }
    let status = Command::new("cargo")
        .args(["install", "--git", REPO_URL, "--locked", "navi-notifier"])
        .status()
        .context("failed to run cargo; --head requires a Rust toolchain")?;
    if !status.success() {
        bail!("cargo install exited with status {status}");
    }
    println!("installed navi from HEAD; to return to a release, run: navi upgrade");
    Ok(())
}

/// Step back to an earlier release. Riskier than upgrading (an older binary may
/// not understand state a newer one wrote), so it confirms first and never goes
/// below [`MIN_DOWNGRADE_VERSION`].
pub fn downgrade(to: Option<String>, yes: bool, no_restart: bool) -> Result<()> {
    let installed = env!("CARGO_PKG_VERSION");
    let installed_version = parse_version(installed)
        .with_context(|| format!("could not parse the installed version {installed}"))?;
    let floor = parse_version(MIN_DOWNGRADE_VERSION).expect("floor is a valid version");

    if installed_version <= floor {
        println!("navi {installed} is the earliest release `downgrade` can reach; nothing older");
        return Ok(());
    }

    let requested = match &to {
        Some(to) => Some(parse_version(to).with_context(|| format!("not a version: {to}"))?),
        None => None,
    };
    let available = match requested {
        Some(_) => Vec::new(),
        None => remote_release_versions()?,
    };
    let target = version_string(resolve_target(
        installed_version,
        floor,
        requested,
        &available,
    )?);

    println!("downgrade navi {installed} -> {target}");
    println!("a release older than {installed} may not understand state a newer one wrote");
    if !yes && !confirm("continue? [y/N] ")? {
        println!("downgrade cancelled");
        return Ok(());
    }
    run_installer(Some(&target))?;
    println!("downgraded to {target}; to move forward again, run: navi upgrade");
    crate::service::restart_after_upgrade(!no_restart)?;
    Ok(())
}

/// Re-run the cargo-dist installer for `version` (or the latest release when
/// `None`). Uses the shell installer on Unix and the PowerShell one on Windows.
fn run_installer(version: Option<&str>) -> Result<()> {
    let base = match version {
        Some(v) => format!("{REPO_URL}/releases/download/v{v}/navi-notifier-installer"),
        None => format!("{REPO_URL}/releases/latest/download/navi-notifier-installer"),
    };
    let status = if cfg!(windows) {
        Command::new("powershell")
            .args([
                "-ExecutionPolicy",
                "Bypass",
                "-c",
                &windows_install_script(&base),
            ])
            .status()
            .context("failed to run the PowerShell installer")?
    } else {
        Command::new("sh")
            .arg("-c")
            .arg(unix_install_script(&base))
            .status()
            .context("failed to run the installer; is curl available?")?
    };
    if !status.success() {
        bail!("installer exited with status {status}");
    }
    Ok(())
}

/// POSIX-sh installer command. Downloads the script to a temp file *first* (curl
/// with `-f` so an HTTP error is a non-zero exit), then runs it, so a failed or
/// rate-limited download is a hard error instead of an empty pipe into `sh` that
/// exits 0 and makes a no-op look like a successful upgrade. Not `curl | sh` with
/// `pipefail` because `/bin/sh` is often dash, which lacks it.
fn unix_install_script(base: &str) -> String {
    format!(
        "t=$(mktemp) || exit 1; \
         curl --proto '=https' --tlsv1.2 -fLsS \"{base}.sh\" -o \"$t\" && sh \"$t\"; \
         rc=$?; rm -f \"$t\"; exit $rc"
    )
}

/// PowerShell installer command. `$ErrorActionPreference='Stop'` makes a failed
/// download a terminating error rather than something `iex` shrugs off.
fn windows_install_script(base: &str) -> String {
    format!("$ErrorActionPreference = 'Stop'; irm {base}.ps1 | iex")
}

/// Once a day, after a common command, print one line when a newer release
/// exists. Best effort with a hard time cap; anything unusual prints nothing.
pub fn maybe_hint_update() {
    if !std::io::stderr().is_terminal() {
        return;
    }
    if env::var("NAVI_NO_UPDATE_CHECK").is_ok_and(|v| !v.is_empty() && v != "0") {
        return;
    }
    let Some(path) = config_dir().map(|d| d.join(UPDATE_CHECK_FILE)) else {
        return;
    };
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|e| e.as_secs())
        .unwrap_or(0);
    if !should_check(fs::read_to_string(&path).ok().as_deref(), now) {
        return;
    }

    let installed = parse_version(env!("CARGO_PKG_VERSION"));
    let (sender, receiver) = mpsc::channel();
    thread::spawn(move || {
        // Latest *published* release, so a release still building doesn't trip a
        // "newer release available" hint you can't yet install (same reason as upgrade).
        let behind = installed
            .zip(latest_release_version())
            .is_some_and(|(installed, latest)| latest > installed);
        let _ = sender.send(behind);
    });

    if let Ok(behind) = receiver.recv_timeout(Duration::from_secs(5)) {
        if let Some(parent) = path.parent() {
            let _ = fs::create_dir_all(parent);
        }
        let _ = fs::write(&path, format!("checked={now}\n"));
        if behind {
            eprintln!("a newer navi release is available; run `navi upgrade`");
        }
    }
}

fn should_check(cache: Option<&str>, now: u64) -> bool {
    let Some(cache) = cache else {
        return true;
    };
    cache
        .lines()
        .find_map(|line| line.strip_prefix("checked="))
        .and_then(|value| value.trim().parse::<u64>().ok())
        .is_none_or(|checked| now.saturating_sub(checked) >= CHECK_INTERVAL_SECS)
}

type Version3 = (u64, u64, u64);

fn resolve_target(
    installed: Version3,
    floor: Version3,
    requested: Option<Version3>,
    available: &[Version3],
) -> Result<Version3> {
    match requested {
        Some(target) => {
            if target >= installed {
                bail!(
                    "{} is not older than the installed {}; use `navi upgrade` to move forward",
                    version_string(target),
                    version_string(installed)
                );
            }
            if target < floor {
                bail!(
                    "{} is below {}, the earliest release `downgrade` can reach",
                    version_string(target),
                    version_string(floor)
                );
            }
            Ok(target)
        }
        None => available
            .iter()
            .copied()
            .filter(|v| *v < installed && *v >= floor)
            .max()
            .with_context(|| {
                format!(
                    "no release between {} and {} to downgrade to",
                    version_string(floor),
                    version_string(installed)
                )
            }),
    }
}

fn parse_version(text: &str) -> Option<Version3> {
    let mut parts = text.trim().split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }
    Some((major, minor, patch))
}

fn version_string((major, minor, patch): Version3) -> String {
    format!("{major}.{minor}.{patch}")
}

/// Whether `navi upgrade` should reinstall: always when forced, otherwise only
/// when the installed version is behind the latest. `latest = None` (we couldn't
/// determine it, e.g. offline) proceeds, keeping the version check best-effort.
fn upgrade_needed(installed: Version3, latest: Option<Version3>, force: bool) -> bool {
    force || latest.is_none_or(|latest| installed < latest)
}

/// The latest *published* release version - what `releases/latest` (and thus the
/// installer) resolves to. `None` on any failure, so the caller falls through and
/// installs. Unlike the tag list, this only reflects a release once it's published,
/// so we never try to upgrade to a version that isn't installable yet.
fn latest_release_version() -> Option<Version3> {
    // `releases/latest` 302-redirects to `.../releases/tag/vX.Y.Z`; follow it and
    // read the final URL. Reuses curl, already required for the installer.
    let output = Command::new("curl")
        .args([
            "-sSL",
            "-o",
            "/dev/null",
            "-w",
            "%{url_effective}",
            &format!("{REPO_URL}/releases/latest"),
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    version_from_release_url(&String::from_utf8_lossy(&output.stdout))
}

/// Parse the version from a `.../releases/tag/vX.Y.Z` URL.
fn version_from_release_url(url: &str) -> Option<Version3> {
    let tag = url.trim().trim_end_matches('/').rsplit('/').next()?;
    parse_version(tag.strip_prefix('v').unwrap_or(tag))
}

/// Released versions, from the repo's `vX.Y.Z` tags. Used by `downgrade`, which
/// legitimately wants every release, not just the latest.
fn remote_release_versions() -> Result<Vec<Version3>> {
    let output = Command::new("git")
        .args(["ls-remote", "--tags", REPO_URL])
        .output()
        .context("failed to list releases; check your network connection")?;
    if !output.status.success() {
        bail!("failed to fetch the release list from {REPO}");
    }
    let text = String::from_utf8_lossy(&output.stdout);
    Ok(text
        .lines()
        .filter_map(|line| line.split("refs/tags/").nth(1))
        .filter(|tag| !tag.ends_with("^{}"))
        .filter_map(|tag| parse_version(tag.strip_prefix('v').unwrap_or(tag)))
        .collect())
}

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

    #[test]
    fn version_from_release_url_parses_the_redirect_target() {
        assert_eq!(
            version_from_release_url("https://github.com/lararosekelley/navi/releases/tag/v0.2.1"),
            Some((0, 2, 1))
        );
        // Trailing slash tolerated.
        assert_eq!(
            version_from_release_url("https://github.com/x/y/releases/tag/v1.10.3/"),
            Some((1, 10, 3))
        );
        // A non-release URL yields nothing (we then fall through and install).
        assert_eq!(
            version_from_release_url("https://github.com/x/y/releases"),
            None
        );
    }

    #[test]
    fn unix_install_script_hard_fails_on_download_error() {
        let s = unix_install_script("https://ex/navi-notifier-installer");
        // `-f` => curl exits non-zero on an HTTP error (404/403/429)...
        assert!(s.contains("-fLsS"), "{s}");
        // ...downloaded to a temp file, and `sh` runs only if the download succeeded.
        assert!(s.contains("mktemp"), "{s}");
        assert!(s.contains("-o \"$t\" && sh \"$t\""), "{s}");
        assert!(s.contains("rm -f \"$t\""), "cleanup: {s}");
        // The old `curl ... | sh` (which swallows curl's exit) must be gone.
        assert!(
            !s.contains(".sh | sh"),
            "must not pipe curl straight into sh: {s}"
        );
    }

    #[test]
    fn windows_install_script_stops_on_error() {
        assert!(windows_install_script("https://ex/x").contains("ErrorActionPreference = 'Stop'"));
    }

    #[test]
    fn parse_version_accepts_plain_xyz_only() {
        assert_eq!(parse_version("0.1.4"), Some((0, 1, 4)));
        assert_eq!(parse_version("10.0.3"), Some((10, 0, 3)));
        assert_eq!(parse_version("0.1"), None);
        assert_eq!(parse_version("0.1.4.1"), None);
        assert_eq!(parse_version("v0.1.4"), None);
    }

    #[test]
    fn resolve_target_requires_explicit_to_be_older() {
        let (installed, floor) = ((0, 2, 0), (0, 1, 4));
        assert!(resolve_target(installed, floor, Some((0, 2, 0)), &[]).is_err());
        assert!(resolve_target(installed, floor, Some((0, 2, 1)), &[]).is_err());
    }

    #[test]
    fn resolve_target_refuses_below_the_floor() {
        let (installed, floor) = ((0, 2, 0), (0, 1, 4));
        assert!(resolve_target(installed, floor, Some((0, 1, 3)), &[]).is_err());
        assert_eq!(
            resolve_target(installed, floor, Some((0, 1, 4)), &[]).unwrap(),
            (0, 1, 4)
        );
    }

    #[test]
    fn resolve_target_default_picks_previous_release() {
        let (installed, floor) = ((0, 2, 0), (0, 1, 4));
        let available = [(0, 1, 4), (0, 1, 5), (0, 2, 0)];
        assert_eq!(
            resolve_target(installed, floor, None, &available).unwrap(),
            (0, 1, 5)
        );
    }

    #[test]
    fn upgrade_needed_skips_only_when_confirmed_current() {
        // Already on the latest → skip (the loop this fixes).
        assert!(!upgrade_needed((0, 1, 9), Some((0, 1, 9)), false));
        // Behind → upgrade.
        assert!(upgrade_needed((0, 1, 8), Some((0, 1, 9)), false));
        // Ahead of the latest release (e.g. a --head build) → don't reinstall.
        assert!(!upgrade_needed((0, 2, 0), Some((0, 1, 9)), false));
        // --force always reinstalls, even when current.
        assert!(upgrade_needed((0, 1, 9), Some((0, 1, 9)), true));
        // Couldn't determine the latest → proceed, best-effort.
        assert!(upgrade_needed((0, 1, 9), None, false));
    }

    #[test]
    fn should_check_missing_or_garbled() {
        assert!(should_check(None, 1_000_000));
        assert!(should_check(Some("checked=nope\n"), 1_000_000));
    }

    #[test]
    fn should_check_once_per_day() {
        let stamp = format!("checked={}\n", 1_000_000u64);
        assert!(!should_check(Some(&stamp), 1_000_000 + 60));
        assert!(should_check(Some(&stamp), 1_000_000 + CHECK_INTERVAL_SECS));
    }
}