Skip to main content

smriti/services/
install_method.rs

1//! Detect *how* Smriti was installed, so the update UI can take
2//! the right action when the user clicks "Download".
3//!
4//! We deliberately avoid self-replacing package-manager-managed
5//! binaries (apt, Homebrew, winget, Flatpak, Snap) — that path is
6//! the package manager's job, and stomping on it would confuse the
7//! system. Instead, for those users the update banner shows the
8//! matching upgrade command.
9//!
10//! Detection is path-based because it's cheap and robust. False
11//! negatives map to `Unknown`, which the update handler turns into
12//! an "open release page in browser" fallback, so a wrong answer
13//! here fails safely rather than corrupting an install.
14
15use std::path::Path;
16
17/// How Smriti was installed on this machine.
18///
19/// Several variants are only constructed on specific target OSes
20/// (`MsiInstaller` on Windows, `MacOsApp` on macOS); allow dead-code
21/// at the type level so non-target-OS builds don't fail `-D warnings`.
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[allow(dead_code)]
24pub enum InstallMethod {
25    /// Self-contained binary — AppImage on Linux, portable zip on
26    /// Windows, or the tar.gz unpacked anywhere. `self_replace` can
27    /// atomically swap the running binary with a newly-downloaded one.
28    Portable,
29
30    /// Installed via a Windows MSI. The self-replace path invokes
31    /// msiexec on the newly-downloaded MSI with a UAC prompt.
32    MsiInstaller,
33
34    /// Installed via the NSIS `-setup.exe`. Tauri's NSIS installer is
35    /// per-user by default (`%LOCALAPPDATA%\Smriti`) and always leaves an
36    /// `uninstall.exe` beside the binary. Updating re-runs the new setup.
37    NsisInstaller,
38
39    /// A `.deb` or `.rpm` from the GitHub release. Smriti is not in any
40    /// distro repository, so there is no upgrade command to suggest; the
41    /// update flow opens the release page and names the file to grab.
42    LinuxPackage { format: String },
43
44    /// macOS `.app` bundle in /Applications. The self-replace path
45    /// downloads the new .dmg and opens it so the user can drag the
46    /// new bundle in. Automating the copy is fragile under Gatekeeper
47    /// + SIP, especially before notarization is set up.
48    MacOsApp,
49
50    /// System package manager owns the binary. We show the matching
51    /// upgrade command in the banner instead of downloading.
52    PackageManager { name: String, upgrade_cmd: String },
53
54    /// Running a `cargo build` binary from the source tree. Show a
55    /// `git pull && cargo build --release` hint.
56    SourceBuild,
57
58    /// Couldn't tell. Falls back to opening the release page in the
59    /// user's browser.
60    Unknown,
61}
62
63/// Detect the install method for the currently-running executable.
64/// Uses `std::env::current_exe` internally.
65pub fn detect() -> InstallMethod {
66    let exe = match std::env::current_exe() {
67        Ok(p) => p,
68        Err(_) => return InstallMethod::Unknown,
69    };
70    classify_path(&exe)
71}
72
73/// Pure, testable version of the detection heuristic.
74#[allow(clippy::needless_return)]
75pub(crate) fn classify_path(exe: &Path) -> InstallMethod {
76    let path_str = exe.to_string_lossy();
77    let lower = path_str.to_lowercase();
78
79    // --- source build is checked first so `target/release/smriti`
80    //     on a Windows box doesn't get mis-bucketed as portable.
81    if lower.contains("/target/debug/") || lower.contains("/target/release/") {
82        return InstallMethod::SourceBuild;
83    }
84    if lower.contains("\\target\\debug\\") || lower.contains("\\target\\release\\") {
85        return InstallMethod::SourceBuild;
86    }
87
88    // --- Nix (NixOS, or Nix on another Linux or macOS) --------------
89    // The store is read-only and Nix owns what's in it, so an update has to
90    // come through Nix too.
91    #[cfg(unix)]
92    if lower.starts_with("/nix/store/") {
93        let upgrade_cmd = if Path::new("/run/current-system").exists() {
94            "sudo nixos-rebuild switch --upgrade"
95        } else {
96            "nix profile upgrade smriti"
97        };
98        return InstallMethod::PackageManager {
99            name: "nix".into(),
100            upgrade_cmd: upgrade_cmd.into(),
101        };
102    }
103
104    // --- Linux ----------------------------------------------------
105    #[cfg(target_os = "linux")]
106    {
107        if lower.ends_with(".appimage") || lower.contains("/squashfs-root/") {
108            return InstallMethod::Portable;
109        }
110        if lower.contains("/var/lib/flatpak/") || lower.starts_with("/app/bin/") {
111            return InstallMethod::PackageManager {
112                name: "flatpak".into(),
113                upgrade_cmd: "flatpak update in.smriti.app".into(),
114            };
115        }
116        if lower.starts_with("/snap/") {
117            return InstallMethod::PackageManager {
118                name: "snap".into(),
119                upgrade_cmd: "snap refresh smriti".into(),
120            };
121        }
122        // Tauri's .deb and .rpm both put the binary in /usr/bin and the
123        // resources in /usr/lib/<productName>. Neither comes from a distro
124        // repository, so tell them apart only to name the right download.
125        if lower.starts_with("/usr/bin/") {
126            let format = if Path::new("/var/lib/dpkg/info/smriti.list").exists() {
127                "deb"
128            } else if Path::new("/var/lib/rpm").exists()
129                || Path::new("/usr/lib/sysimage/rpm").exists()
130            {
131                "rpm"
132            } else {
133                "deb"
134            };
135            return InstallMethod::LinuxPackage {
136                format: format.into(),
137            };
138        }
139    }
140
141    // --- macOS ----------------------------------------------------
142    #[cfg(target_os = "macos")]
143    {
144        if lower.contains("/opt/homebrew/") || lower.contains("/usr/local/cellar/") {
145            return InstallMethod::PackageManager {
146                name: "brew".into(),
147                upgrade_cmd: "brew update && brew upgrade --cask smriti".into(),
148            };
149        }
150        if lower.contains(".app/contents/macos/")
151            && (lower.contains("/applications/") || lower.contains("/users/"))
152        {
153            return InstallMethod::MacOsApp;
154        }
155    }
156
157    // --- Windows --------------------------------------------------
158    #[cfg(target_os = "windows")]
159    {
160        // The NSIS installer (per-user or per-machine) leaves its
161        // uninstaller next to the binary; MSI installs never do.
162        if exe.with_file_name("uninstall.exe").is_file() {
163            return InstallMethod::NsisInstaller;
164        }
165        // MSI-installed binaries typically land under Program Files.
166        if lower.contains("\\program files\\") || lower.contains("\\program files (x86)\\") {
167            return InstallMethod::MsiInstaller;
168        }
169        // Microsoft Store (MSIX) installs live under WindowsApps.
170        if lower.contains("\\windowsapps\\") {
171            return InstallMethod::PackageManager {
172                name: "msstore".into(),
173                upgrade_cmd: "Microsoft Store -> Updates".into(),
174            };
175        }
176        // Scoop drops binaries under the user's scoop root.
177        if lower.contains("\\scoop\\apps\\") {
178            return InstallMethod::PackageManager {
179                name: "scoop".into(),
180                upgrade_cmd: "scoop update smriti".into(),
181            };
182        }
183        // Everything else on Windows: portable zip extracted somewhere.
184        return InstallMethod::Portable;
185    }
186
187    // Cross-platform fallback: any .exe that wasn't caught above, or
188    // an unrecognized Linux layout, or an unrecognized macOS bundle.
189    #[cfg(not(target_os = "windows"))]
190    {
191        InstallMethod::Unknown
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use std::path::PathBuf;
199
200    #[test]
201    fn source_build_detected_unix() {
202        let p = PathBuf::from("/home/user/code/smriti/target/release/smriti");
203        assert_eq!(classify_path(&p), InstallMethod::SourceBuild);
204    }
205
206    #[test]
207    fn source_build_detected_debug() {
208        let p = PathBuf::from("/home/user/code/smriti/target/debug/smriti");
209        assert_eq!(classify_path(&p), InstallMethod::SourceBuild);
210    }
211
212    #[test]
213    fn source_build_detected_windows() {
214        let p = PathBuf::from("C:\\Users\\foo\\smriti\\target\\release\\smriti.exe");
215        assert_eq!(classify_path(&p), InstallMethod::SourceBuild);
216    }
217
218    #[cfg(target_os = "linux")]
219    #[test]
220    fn appimage_detected() {
221        let p = PathBuf::from("/home/user/Applications/Smriti-x86_64.AppImage");
222        assert_eq!(classify_path(&p), InstallMethod::Portable);
223    }
224
225    #[cfg(target_os = "linux")]
226    #[test]
227    fn flatpak_detected() {
228        let p = PathBuf::from(
229            "/var/lib/flatpak/app/in.smriti.app/x86_64/stable/current/files/bin/smriti",
230        );
231        match classify_path(&p) {
232            InstallMethod::PackageManager { name, .. } => assert_eq!(name, "flatpak"),
233            other => panic!("expected flatpak, got {:?}", other),
234        }
235    }
236
237    #[cfg(unix)]
238    #[test]
239    fn nix_store_install_updates_through_nix() {
240        let p = PathBuf::from("/nix/store/0a1b2c-smriti-0.5.0/bin/.smriti-tauri-wrapped");
241        match classify_path(&p) {
242            InstallMethod::PackageManager { name, .. } => assert_eq!(name, "nix"),
243            other => panic!("expected nix, got {:?}", other),
244        }
245    }
246
247    #[cfg(target_os = "linux")]
248    #[test]
249    fn snap_detected() {
250        let p = PathBuf::from("/snap/smriti/current/usr/bin/smriti");
251        match classify_path(&p) {
252            InstallMethod::PackageManager { name, .. } => assert_eq!(name, "snap"),
253            other => panic!("expected snap, got {:?}", other),
254        }
255    }
256
257    #[cfg(target_os = "windows")]
258    #[test]
259    fn msi_installer_detected() {
260        let p = PathBuf::from("C:\\Program Files\\Smriti\\smriti.exe");
261        assert_eq!(classify_path(&p), InstallMethod::MsiInstaller);
262    }
263
264    #[cfg(target_os = "windows")]
265    #[test]
266    fn nsis_install_detected_by_its_uninstaller() {
267        // Tauri's NSIS default is per-user, outside Program Files.
268        let dir = tempfile::tempdir().unwrap();
269        let exe = dir.path().join("smriti.exe");
270        std::fs::write(&exe, b"").unwrap();
271        assert_eq!(classify_path(&exe), InstallMethod::Portable);
272        std::fs::write(dir.path().join("uninstall.exe"), b"").unwrap();
273        assert_eq!(classify_path(&exe), InstallMethod::NsisInstaller);
274    }
275
276    #[cfg(target_os = "linux")]
277    #[test]
278    fn system_package_never_suggests_a_repository_upgrade() {
279        let p = PathBuf::from("/usr/bin/smriti");
280        assert!(matches!(
281            classify_path(&p),
282            InstallMethod::LinuxPackage { .. }
283        ));
284    }
285
286    #[cfg(target_os = "windows")]
287    #[test]
288    fn scoop_detected() {
289        let p = PathBuf::from("C:\\Users\\user\\scoop\\apps\\smriti\\current\\smriti.exe");
290        match classify_path(&p) {
291            InstallMethod::PackageManager { name, .. } => assert_eq!(name, "scoop"),
292            other => panic!("expected scoop, got {:?}", other),
293        }
294    }
295
296    #[cfg(target_os = "macos")]
297    #[test]
298    fn macos_app_bundle_detected() {
299        let p = PathBuf::from("/Applications/Smriti.app/Contents/MacOS/smriti");
300        assert_eq!(classify_path(&p), InstallMethod::MacOsApp);
301    }
302
303    #[cfg(target_os = "macos")]
304    #[test]
305    fn homebrew_cask_detected() {
306        let p = PathBuf::from("/opt/homebrew/Caskroom/smriti/1.0.0/smriti");
307        match classify_path(&p) {
308            InstallMethod::PackageManager { name, .. } => assert_eq!(name, "brew"),
309            other => panic!("expected brew, got {:?}", other),
310        }
311    }
312}