Skip to main content

carch_cli/
commands.rs

1use carch_core::error::{CarchError, Result};
2use log::info;
3use std::fs;
4use std::io::{self, Write};
5use std::process::{Command, Stdio};
6use tempfile::Builder;
7
8use carch_core::version;
9
10pub fn check_for_updates() -> Result<()> {
11    println!("Checking for updates...");
12
13    let current_version = env!("CARGO_PKG_VERSION");
14
15    match version::get_latest_version() {
16        Ok(latest_version) => {
17            println!("Current version: {current_version}");
18            println!("Latest version: {latest_version}");
19
20            if latest_version != current_version {
21                println!("\nA new version of Carch is available!");
22                println!("Run 'carch update' to update to the latest version.");
23            } else {
24                println!("\nYou are using the latest version of Carch.");
25            }
26        }
27        Err(e) => {
28            eprintln!("Error checking for updates: {e}");
29            return Err(e);
30        }
31    }
32
33    Ok(())
34}
35
36enum Distro {
37    Termux,
38    Arch,
39    Fedora,
40    OpenSuse,
41}
42
43fn is_termux() -> bool {
44    std::env::var("TERMUX_VERSION").is_ok()
45        || std::path::Path::new("/data/data/com.termux").exists()
46}
47
48fn detect_distro() -> Result<Distro> {
49    if is_termux() {
50        return Ok(Distro::Termux);
51    }
52    if command_exists("pacman") {
53        return Ok(Distro::Arch);
54    }
55    if command_exists("dnf") {
56        return Ok(Distro::Fedora);
57    }
58    if command_exists("zypper") {
59        return Ok(Distro::OpenSuse);
60    }
61    Err(CarchError::Command(
62        "Unsupported distribution. Carch supports Arch, Fedora, openSUSE, and Termux.".into(),
63    ))
64}
65
66fn detect_termux_arch() -> Result<&'static str> {
67    let out = Command::new("uname").arg("-m").output()?;
68    let arch = String::from_utf8_lossy(&out.stdout);
69    let arch = arch.trim();
70    match arch {
71        "aarch64" | "arm64" => Ok("aarch64"),
72        a if a.starts_with("armv7") || a == "armv8l" || a == "arm" => Ok("arm"),
73        other => Err(CarchError::Command(format!("Unsupported Termux architecture: {other}"))),
74    }
75}
76
77fn command_exists(command: &str) -> bool {
78    Command::new("sh")
79        .arg("-c")
80        .arg(format!("command -v {command}"))
81        .stdout(Stdio::null())
82        .stderr(Stdio::null())
83        .status()
84        .is_ok_and(|s| s.success())
85}
86
87fn run_command(command: &mut Command) -> Result<()> {
88    let status = command.status()?;
89    if !status.success() {
90        return Err(CarchError::Command(format!("Command failed with exit code {status}")));
91    }
92    Ok(())
93}
94
95fn get_latest_release_url(asset_pattern: &str) -> Result<String> {
96    let client = reqwest::blocking::Client::new();
97    let body = client
98        .get("https://api.github.com/repos/harilvfs/carch/releases/latest")
99        .header("User-Agent", "carch-cli")
100        .send()?
101        .text()?;
102
103    for line in body.lines() {
104        if !line.contains("browser_download_url") {
105            continue;
106        }
107        for token in line.split('"') {
108            if token.starts_with("https://") && token.ends_with(asset_pattern) {
109                return Ok(token.to_string());
110            }
111        }
112    }
113
114    Err(CarchError::Command(format!("Could not find release asset matching '{asset_pattern}'")))
115}
116
117fn get_rpm_url() -> Result<String> {
118    get_latest_release_url(".rpm")
119}
120
121fn termux_install_deb(deb_arch: &str) -> Result<()> {
122    println!("==> Fetching latest .deb package for {deb_arch}...");
123
124    let pattern = format!("_{deb_arch}.deb");
125    let deb_url = get_latest_release_url(&pattern)?;
126
127    let tmp_dir =
128        std::env::var("PREFIX").map(|p| format!("{p}/tmp")).unwrap_or_else(|_| "/tmp".into());
129
130    let mut tmp_deb = Builder::new().prefix("carch_").suffix(".deb").tempfile_in(&tmp_dir)?;
131
132    println!("==> Downloading .deb package...");
133    let bytes = reqwest::blocking::get(&deb_url)?.bytes()?;
134    tmp_deb.write_all(&bytes)?;
135
136    let tmp_path = tmp_deb.path().to_path_buf();
137
138    println!("==> Installing .deb package...");
139    run_command(Command::new("dpkg").arg("-i").arg(&tmp_path))?;
140
141    fs::remove_file(&tmp_path).ok();
142    Ok(())
143}
144
145fn install_for_distro(distro: &Distro) -> Result<()> {
146    match distro {
147        Distro::Termux => {
148            let arch = detect_termux_arch()?;
149            println!("==> Detected Termux architecture: {arch}");
150            termux_install_deb(arch)
151        }
152        Distro::Arch => {
153            println!("==> Cloning PKGBUILD...");
154            let home = std::env::var("HOME")
155                .map_err(|_| CarchError::Command("$HOME is not set".into()))?;
156            let pkgs_dir = std::path::PathBuf::from(home).join("pkgs");
157
158            if pkgs_dir.exists() {
159                fs::remove_dir_all(&pkgs_dir)?;
160            }
161
162            run_command(
163                Command::new("git")
164                    .arg("clone")
165                    .arg("https://github.com/carch-org/pkgs")
166                    .arg(&pkgs_dir)
167                    .stdout(Stdio::null())
168                    .stderr(Stdio::null()),
169            )?;
170
171            let carch_bin_dir = pkgs_dir.join("carch-bin");
172            run_command(
173                Command::new("makepkg").arg("-si").arg("--noconfirm").current_dir(&carch_bin_dir),
174            )
175        }
176        Distro::Fedora | Distro::OpenSuse => {
177            println!("==> Downloading carch RPM...");
178            let rpm_url = get_rpm_url()?;
179
180            let bytes = reqwest::blocking::get(&rpm_url)?.bytes()?;
181            let rpm_path = std::path::PathBuf::from("/tmp/carch.rpm");
182            fs::write(&rpm_path, &bytes)?;
183
184            match distro {
185                Distro::Fedora => run_command(
186                    Command::new("sudo").arg("dnf").arg("install").arg("-y").arg(&rpm_path),
187                ),
188                Distro::OpenSuse => run_command(
189                    Command::new("sudo")
190                        .arg("zypper")
191                        .arg("install")
192                        .arg("-y")
193                        .arg("--allow-unsigned-rpm")
194                        .arg(&rpm_path),
195                ),
196                _ => unreachable!(),
197            }
198        }
199    }
200}
201
202fn uninstall_for_distro(distro: &Distro) -> Result<()> {
203    match distro {
204        Distro::Termux => {
205            let installed = Command::new("dpkg")
206                .args(["-s", "carch"])
207                .stdout(Stdio::null())
208                .stderr(Stdio::null())
209                .status()
210                .is_ok_and(|s| s.success());
211
212            if installed {
213                run_command(Command::new("dpkg").arg("-r").arg("carch"))?;
214                println!("==> carch has been removed.");
215            } else {
216                println!("==> carch is not installed.");
217            }
218            Ok(())
219        }
220        Distro::Arch => run_command(
221            Command::new("sudo")
222                .arg("pacman")
223                .arg("-R")
224                .arg("carch-bin")
225                .arg("carch-bin-debug")
226                .arg("--noconfirm"),
227        ),
228        Distro::Fedora => {
229            run_command(Command::new("sudo").arg("dnf").arg("remove").arg("carch").arg("-y"))
230        }
231        Distro::OpenSuse => {
232            run_command(Command::new("sudo").arg("zypper").arg("remove").arg("-y").arg("carch"))
233        }
234    }
235}
236
237enum InstallMethod {
238    Cargo,
239    PackageManager,
240}
241
242fn get_install_method() -> Result<InstallMethod> {
243    print!("Installed via (c)argo or (p)ackage manager? ");
244    io::stdout().flush()?;
245    let mut choice = String::new();
246    io::stdin().read_line(&mut choice)?;
247    match choice.trim().to_lowercase().as_str() {
248        "c" | "cargo" => Ok(InstallMethod::Cargo),
249        "p" | "package manager" => Ok(InstallMethod::PackageManager),
250        _ => Err(CarchError::Command("Invalid choice. Please run the command again.".into())),
251    }
252}
253
254pub fn update() -> Result<()> {
255    if !command_exists("carch") {
256        println!("Carch is not installed. Please install it first.");
257        return Ok(());
258    }
259
260    info!("Starting update...");
261    println!("==> Updating carch...");
262
263    match get_install_method()? {
264        InstallMethod::Cargo => {
265            run_command(Command::new("cargo").arg("install").arg("carch-cli").arg("--force"))?;
266        }
267        InstallMethod::PackageManager => {
268            let distro = detect_distro()?;
269            install_for_distro(&distro)?;
270        }
271    }
272
273    println!("Update done.");
274    Ok(())
275}
276
277pub fn uninstall() -> Result<()> {
278    if !command_exists("carch") {
279        println!("Carch is not installed.");
280        return Ok(());
281    }
282
283    info!("Starting uninstall...");
284
285    match get_install_method()? {
286        InstallMethod::Cargo => {
287            run_command(Command::new("cargo").arg("uninstall").arg("carch-cli"))?;
288        }
289        InstallMethod::PackageManager => {
290            let distro = detect_distro()?;
291            uninstall_for_distro(&distro)?;
292        }
293    }
294
295    println!("Uninstallation done.");
296    Ok(())
297}