updt 0.1.37

Cross-platform update helper for npm, cargo, rustup, fnm, scoop, Homebrew, paru, flatpak, pacman, and pkg.
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use crate::command::{
    command_exists, run_capture, run_cargo_install_update_inherit, run_inherit,
    run_nvim_headless_inherit,
};
use crate::output::{err_text, ok_text, print_section};
use crate::profile::{desktop_linux_session, interactive_terminal};
use crate::state::{AppState, target_label};
use std::{env, fs, process};

#[cfg(windows)]
use std::io;
#[cfg(windows)]
use std::process::{Command, Stdio};

pub fn upgrade_selected(state: &AppState, selected: &[String]) -> bool {
    print_section("执行升级");
    let mut run_fail = false;
    let self_pkg = env!("CARGO_PKG_NAME");
    let mut cargo_self_needs_update = false;
    let pacman_selected = selected.iter().any(|s| s == "pacman");
    let run_pacman_first = state.is_arch_linux && pacman_selected;

    if run_pacman_first {
        run_fail |= !run_pacman_upgrade(state);
    }

    if selected.iter().any(|s| s == "brew") {
        println!("[brew] 正在刷新索引: brew update --quiet");
        match run_inherit("brew", &["update", "--quiet"]) {
            Ok(true) => {
                println!("[brew] 正在执行: brew upgrade --greedy");
                match run_inherit("brew", &["upgrade", "--greedy"]) {
                    Ok(true) => println!("[brew] 升级完成."),
                    _ => {
                        println!("[brew] 升级失败.");
                        run_fail = true;
                    }
                }
            }
            _ => {
                println!("[brew] 升级失败: brew update 失败.");
                run_fail = true;
            }
        }
    }

    if selected.iter().any(|s| s == "npm") {
        println!("[npm] 正在执行: npm update -g");
        match run_inherit("npm", &["update", "-g"]) {
            Ok(true) => println!("[npm] 全局包升级完成."),
            _ => {
                println!("[npm] 全局包升级失败.");
                run_fail = true;
            }
        }
    }

    if selected.iter().any(|s| s == "cargo") {
        cargo_self_needs_update = state
            .cargo
            .updatable_packages
            .iter()
            .any(|pkg| pkg.as_str() == self_pkg);
        let targets: Vec<String> = state
            .cargo
            .updatable_packages
            .iter()
            .filter(|pkg| pkg.as_str() != self_pkg)
            .cloned()
            .collect();

        if targets.is_empty() {
            if cargo_self_needs_update {
                println!("[cargo] 检测到 updt 自身可升级, 将在最后单独升级.");
            } else {
                println!("[cargo] 无可升级 crate, 跳过.");
            }
        } else {
            let mut args = Vec::with_capacity(targets.len());
            for pkg in &targets {
                args.push(pkg.as_str());
            }
            println!(
                "[cargo] 正在执行: cargo install-update --locked {}",
                targets.join(" ")
            );
            match run_cargo_install_update_inherit(&args) {
                Ok(true) => println!("[cargo] 其他已安装 crate 升级完成."),
                _ => {
                    println!("[cargo] 已安装 crate 升级失败.");
                    run_fail = true;
                }
            }
            if cargo_self_needs_update {
                println!("[cargo] updt 自身将放到最后单独升级.");
            }
        }
    }

    if selected.iter().any(|s| s == "nvim") {
        if !state.nvim.installed {
            println!("[nvim] 未安装 nvim, 跳过.");
        } else {
            if state.nvim.lazy_available {
                println!("[nvim] 正在执行: nvim --headless \"+Lazy! sync\" +qa");
                match run_nvim_headless_inherit(&["+Lazy! sync", "+qa"]) {
                    Ok(true) => println!("[nvim] Lazy 插件更新完成."),
                    _ => {
                        println!("[nvim] Lazy 插件更新失败.");
                        run_fail = true;
                    }
                }
            } else {
                println!("[nvim] 未检测到 Lazy 插件管理器, 跳过插件更新.");
            }

            if state.nvim.mason_available {
                println!(
                    "[nvim] 正在执行: nvim --headless \"+Lazy load mason.nvim\" \"+MasonUpdate\" +qa"
                );
                match run_nvim_headless_inherit(&["+Lazy load mason.nvim", "+MasonUpdate", "+qa"]) {
                    Ok(true) => println!("[nvim] Mason registry 更新完成."),
                    _ => {
                        println!("[nvim] Mason registry 更新失败.");
                        run_fail = true;
                    }
                }

                println!(
                    "[nvim] 正在执行: nvim --headless \"+Lazy load mason.nvim\" \"+lua ... MasonInstall <installed>\" +qa"
                );
                match run_nvim_headless_inherit(&[
                    "+Lazy load mason.nvim",
                    "+lua local root=vim.fn.stdpath('data')..'/mason/packages'; local ok,dir=pcall(vim.fs.dir,root); if not ok or not dir then return end; local pkgs={}; for name,t in dir do if t=='directory' then table.insert(pkgs,name) end end; table.sort(pkgs); if #pkgs>0 then vim.cmd('MasonInstall '..table.concat(pkgs,' ')) end",
                    "+qa",
                ]) {
                    Ok(true) => println!("[nvim] Mason 已安装工具更新完成."),
                    _ => {
                        println!("[nvim] Mason 已安装工具更新失败.");
                        run_fail = true;
                    }
                }
            } else {
                println!("[nvim] 未检测到 mason.nvim, 跳过 Mason 更新.");
            }
        }
    }

    if selected.iter().any(|s| s == "rustup") {
        println!("[rustup] 正在执行: rustup update");
        match run_inherit("rustup", &["update"]) {
            Ok(true) => println!("[rustup] toolchain 升级完成."),
            _ => {
                println!("[rustup] toolchain 升级失败.");
                run_fail = true;
            }
        }
    }

    if selected.iter().any(|s| s == "fnm") {
        println!("[fnm] 正在执行: fnm install --latest");
        match run_inherit("fnm", &["install", "--latest"]) {
            Ok(true) => println!("[fnm] latest Node.js 已安装/更新."),
            _ => {
                println!("[fnm] latest Node.js 更新失败.");
                run_fail = true;
            }
        }
        println!("[fnm] 正在执行: fnm install --lts");
        match run_inherit("fnm", &["install", "--lts"]) {
            Ok(true) => println!("[fnm] LTS Node.js 已安装/更新."),
            _ => {
                println!("[fnm] LTS Node.js 更新失败.");
                run_fail = true;
            }
        }
    }

    if selected.iter().any(|s| s == "scoop") {
        println!("[scoop] 正在执行: scoop update");
        match run_inherit("scoop", &["update"]) {
            Ok(true) => {
                println!("[scoop] 正在执行: scoop update *");
                match run_inherit("scoop", &["update", "*"]) {
                    Ok(true) => println!("[scoop] 包升级完成."),
                    _ => {
                        println!("[scoop] 包升级失败.");
                        run_fail = true;
                    }
                }
            }
            _ => {
                println!("[scoop] 升级失败: scoop update 失败.");
                run_fail = true;
            }
        }
    }

    if selected.iter().any(|s| s == "paru") {
        println!("[paru] 正在执行: paru -Sua");
        match run_inherit("paru", &["-Sua"]) {
            Ok(true) => println!("[paru] AUR 包升级完成."),
            _ => {
                println!("[paru] AUR 包升级失败.");
                run_fail = true;
            }
        }
    }

    if selected.iter().any(|s| s == "flatpak") {
        println!("[flatpak] 正在执行: flatpak update");
        match run_inherit("flatpak", &["update"]) {
            Ok(true) => println!("[flatpak] 应用升级完成."),
            _ => {
                println!("[flatpak] 应用升级失败.");
                run_fail = true;
            }
        }
    }

    if pacman_selected && !run_pacman_first {
        run_fail |= !run_pacman_upgrade(state);
    }

    if selected.iter().any(|s| s == "pkg") {
        println!("[pkg] 正在执行: pkg update");
        match run_inherit("pkg", &["update"]) {
            Ok(true) => {
                println!("[pkg] 正在执行: pkg upgrade");
                match run_inherit("pkg", &["upgrade"]) {
                    Ok(true) => println!("[pkg] 包升级完成."),
                    _ => {
                        println!("[pkg] 包升级失败.");
                        run_fail = true;
                    }
                }
            }
            _ => {
                println!("[pkg] 升级失败: pkg update 失败.");
                run_fail = true;
            }
        }
    }

    if cargo_self_needs_update {
        #[cfg(windows)]
        {
            println!(
                "[cargo] 即将单独升级 updt: 先退出当前 updt, 再执行 cargo install-update --locked updt"
            );
            match schedule_windows_self_update(self_pkg) {
                Ok(()) => {
                    println!("[cargo] 已启动前台自更新窗口, 本次 updt 退出后会显示升级过程.");
                }
                Err(err) => {
                    println!("[cargo] 启动前台自更新窗口失败: {err}");
                    println!("[cargo] 可手动执行: cargo install-update --locked updt");
                    run_fail = true;
                }
            }
        }

        #[cfg(not(windows))]
        {
            println!("[cargo] 正在执行: cargo install-update --locked updt");
            match run_cargo_install_update_inherit(&[self_pkg]) {
                Ok(true) => println!("[cargo] updt 自身升级完成."),
                _ => {
                    println!("[cargo] updt 自身升级失败.");
                    run_fail = true;
                }
            }
        }
    }

    print_section("汇总");
    println!(
        "已选择升级项: {}",
        selected
            .iter()
            .map(|id| target_label(id))
            .collect::<Vec<_>>()
            .join(", ")
    );
    if run_fail {
        println!("{}", err_text("存在升级失败项."));
        return false;
    }
    println!("{}", ok_text("所有已选升级项执行完成."));
    true
}

fn run_pacman_upgrade(state: &AppState) -> bool {
    let (privilege_command, reason) = pacman_privilege_command(state);

    if privilege_command == "pkexec" && !command_exists(privilege_command) {
        println!("[pacman] 未安装 pkexec, 无法使用 GUI 提权.");
        println!("[pacman] 包升级失败.");
        return false;
    }

    if let Some(reason) = reason {
        println!("[pacman] {reason}");
    }
    println!("[pacman] 正在执行: {privilege_command} pacman -Syu");
    match run_inherit(privilege_command, &["pacman", "-Syu"]) {
        Ok(true) => {
            println!("[pacman] 包升级完成.");
            true
        }
        _ => {
            println!("[pacman] 包升级失败.");
            false
        }
    }
}

fn pacman_privilege_command(state: &AppState) -> (&'static str, Option<&'static str>) {
    if !state.is_arch_linux || !desktop_linux_session() {
        return ("sudo", None);
    }

    match terminal_focus_state() {
        TerminalFocusState::Focused => ("sudo", None),
        TerminalFocusState::NotFocused => {
            ("pkexec", Some("terminal 未处于桌面焦点, 使用 GUI 提权."))
        }
        TerminalFocusState::Unknown => (
            "pkexec",
            Some("无法确认 terminal 处于桌面焦点, 使用 GUI 提权."),
        ),
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum TerminalFocusState {
    Focused,
    NotFocused,
    Unknown,
}

fn terminal_focus_state() -> TerminalFocusState {
    if !interactive_terminal() {
        return TerminalFocusState::NotFocused;
    }

    if let Some(focused) = terminal_focused_by_x11_window_id() {
        return if focused {
            TerminalFocusState::Focused
        } else {
            TerminalFocusState::NotFocused
        };
    }

    if let Some(pid) = active_window_pid() {
        return if current_process_belongs_to_window(pid) {
            TerminalFocusState::Focused
        } else {
            TerminalFocusState::NotFocused
        };
    }

    TerminalFocusState::Unknown
}

fn terminal_focused_by_x11_window_id() -> Option<bool> {
    let terminal_window_id = env::var("WINDOWID").ok()?.trim().parse::<u64>().ok()?;
    if terminal_window_id == 0 || !command_exists("xdotool") {
        return None;
    }

    let (status, output) = run_capture("xdotool", &["getactivewindow"]).ok()?;
    if status != 0 {
        return None;
    }
    let active_window_id = output.trim().parse::<u64>().ok()?;
    Some(active_window_id == terminal_window_id)
}

fn active_window_pid() -> Option<u32> {
    active_window_pid_from_hyprland().or_else(active_window_pid_from_x11)
}

fn active_window_pid_from_hyprland() -> Option<u32> {
    if env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_none() || !command_exists("hyprctl") {
        return None;
    }

    let (status, output) = run_capture("hyprctl", &["activewindow", "-j"]).ok()?;
    if status != 0 {
        return None;
    }
    let value = serde_json::from_str::<serde_json::Value>(&output).ok()?;
    value
        .get("pid")?
        .as_u64()
        .and_then(|pid| pid.try_into().ok())
}

fn active_window_pid_from_x11() -> Option<u32> {
    if env::var_os("DISPLAY").is_none() || !command_exists("xdotool") {
        return None;
    }

    let (status, output) = run_capture("xdotool", &["getactivewindow", "getwindowpid"]).ok()?;
    if status != 0 {
        return None;
    }
    output.trim().parse::<u32>().ok()
}

fn current_process_belongs_to_window(window_pid: u32) -> bool {
    process_ancestors(process::id()).any(|pid| pid == window_pid)
}

fn process_ancestors(pid: u32) -> impl Iterator<Item = u32> {
    std::iter::successors(Some(pid), |pid| parent_pid(*pid)).take(64)
}

fn parent_pid(pid: u32) -> Option<u32> {
    let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let after_comm = stat.rsplit_once(") ")?.1;
    let mut fields = after_comm.split_whitespace();
    fields.next()?;
    let parent = fields.next()?.parse::<u32>().ok()?;
    (parent != 0).then_some(parent)
}

#[cfg(windows)]
fn schedule_windows_self_update(pkg: &str) -> io::Result<()> {
    let parent_pid = process::id();
    let script = format!(
        "$ErrorActionPreference='Continue'; \
$parentPid={parent_pid}; \
while (Get-Process -Id $parentPid -ErrorAction SilentlyContinue) {{ Start-Sleep -Milliseconds 200 }}; \
cargo install-update --locked {pkg}; \
Write-Host ''; \
Write-Host 'Self-update finished. Press Enter to close this window.'; \
[void](Read-Host); \
exit"
    );

    let shell = if command_exists("pwsh") {
        "pwsh"
    } else {
        "powershell.exe"
    };

    let primary = Command::new("cmd.exe")
        .arg("/C")
        .arg("start")
        .arg("")
        .arg(shell)
        .arg("-NoLogo")
        .arg("-NoProfile")
        .arg("-Command")
        .arg(&script)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map(|_| ());

    if primary.is_ok() {
        return Ok(());
    }

    Command::new("cmd.exe")
        .arg("/C")
        .arg("start")
        .arg("")
        .arg("powershell.exe")
        .arg("-NoLogo")
        .arg("-NoProfile")
        .arg("-Command")
        .arg(&script)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map(|_| ())
}