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
use std::io::{BufRead, BufReader, Result};

use std::process::{Command, Stdio};
use std::time::Instant;

use colored::Colorize;
use spinoff::{spinners, Color, Spinner};

pub struct Package {
    name: String,
    version: String,
    new_version: Option<String>,
}

impl Package {
    fn to_formatted(&self) -> Self {
        let name = self.name.to_string();
        let old_version = format!("v{}", self.version).bright_red();
        let new_version = format!("v{}", self.new_version.as_ref().unwrap()).bright_green();

        Self {
            name,
            version: old_version.to_string(),
            new_version: Some(new_version.to_string()),
        }
    }
}

/// # Errors
/// Will return `Err` if the command fails to execute
///
/// # Panics
/// Will panic if the command fails to execute
pub fn get_installed_packages() -> Result<Vec<Package>> {
    let output = Command::new("cargo").args(["install", "--list"]).output()?;

    let text = String::from_utf8_lossy(&output.stdout);

    let mut packages = Vec::new();
    for line in text.lines() {
        if line.ends_with(':') {
            let parts: Vec<_> = line.splitn(2, ' ').collect();
            if parts.len() == 2 && parts[1].starts_with('v') {
                let name = parts[0].trim().to_string();
                let version = parts[1]
                    .trim()
                    .trim_end_matches(':')
                    .trim_start_matches('v')
                    .to_string();
                packages.push(Package {
                    name,
                    version,
                    new_version: None,
                });
            }
        }
    }

    Ok(packages)
}

/// # Errors
/// Will return `Err` if the command fails to execute
///
/// # Panics
/// Will panic if the command fails to execute
pub fn get_outdated_packages() -> Result<Vec<Package>> {
    let spinner = Spinner::new(
        spinners::Dots,
        "Scanning for outdated crates...",
        Color::Cyan,
    );

    let packages = get_installed_packages()?;

    let mut outdated_packages = Vec::new();

    for package in &packages {
        let output = Command::new("cargo")
            .args(["search", &package.name, "--limit=1", "--color=never", "-q"])
            .output()?;
        let text = String::from_utf8_lossy(&output.stdout);

        let prefix = format!("{} = \"", package.name);

        if !text.starts_with(&prefix) {
            continue;
        }

        let value_start = prefix.len();
        let quote_end = text[value_start..].find('"').unwrap();
        let latest_version = text[value_start..value_start + quote_end].to_string();

        if latest_version != package.version {
            outdated_packages.push(Package {
                name: package.name.to_string(),
                version: package.version.clone(),
                new_version: Some(latest_version),
            });
        }
    }

    spinner.clear();

    Ok(outdated_packages)
}

/// # Errors
/// Will return `Err` if the command fails to execute
///
/// # Panics
/// Will panic if the command fails to execute
pub fn show_outdated_packages() -> Result<()> {
    let outdated_packages = get_outdated_packages()?;
    if outdated_packages.is_empty() {
        return Ok(());
    }
    println!("Outdated global cargo crates:");
    println!("===============================");
    for package in outdated_packages {
        let formatted = package.to_formatted();

        println!(
            "📦 {}: {} -> {}",
            formatted.name,
            formatted.version,
            formatted.new_version.unwrap()
        );
    }

    Ok(())
}

/// # Errors
///
/// Will return `Err` if the command fails to execute
///
/// # Panics
/// Will panic if the command fails to execute
pub fn update_package(name: &str) -> Result<()> {
    let mut spinner = Spinner::new(spinners::Dots, "Loading...", Color::Cyan);

    let start_time = Instant::now();

    let mut cmd = Command::new("cargo")
        .args(["install", name, "--locked"])
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .stdin(Stdio::piped())
        .spawn()?;

    let reader = BufReader::new(cmd.stderr.take().unwrap());

    let mut last_line = String::new();

    for line in reader.lines() {
        last_line = line?;
        spinner.update_text(last_line.trim().to_string());
    }

    let status_code = cmd.wait()?;

    let status = format!("{} [{:.2?}]", last_line.trim(), start_time.elapsed());

    match status_code.code().unwrap_or(1) {
        0 => spinner.success(&status),
        1 => spinner.fail(&status),
        _ => spinner.warn(&status),
    }

    Ok(())
}

/// # Errors
/// Will return `Err` if the command fails to execute
///
/// # Panics
/// Will panic if the command fails to execute
pub fn update_all_packages() -> Result<()> {
    let packages = get_outdated_packages()?;

    let mut done_one = false;

    for package in packages {
        if package.new_version.is_none() {
            continue;
        }
        let formatted = package.to_formatted();
        if done_one {
            println!();
        }
        if package.name == env!("CARGO_PKG_NAME") {
            println!(
                "{name} is outdated [{old_v} -> {new_v}] but it cannot update itself.\nRun `cargo install {name}` to update it",
                name = formatted.name,
                old_v = formatted.version,
                new_v = formatted.new_version.unwrap()
            );
            continue;
        }
        println!(
            "Upgrading {} from {} to {}",
            formatted.name,
            formatted.version,
            formatted.new_version.unwrap()
        );
        update_package(&package.name)?;
        done_one = true;
    }

    Ok(())
}