upstream-rs 1.18.0

Fetch package updates directly from the source.
Documentation
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use crate::services::{integration::CompletionManager, storage::config_storage::ConfigStorage};
use crate::utils::static_paths::UpstreamPaths;
#[cfg(windows)]
use anyhow::Context;
use anyhow::Result;
#[cfg(unix)]
use std::collections::BTreeSet;
use std::fs;
use std::io;
#[cfg(unix)]
use std::io::Write;
#[cfg(unix)]
use std::path::Path;

// Unix shell source lines
#[cfg(unix)]
const SOURCE_LINE_BASH: &str =
    "[ -f $HOME/.upstream/metadata/paths.sh ] && source $HOME/.upstream/metadata/paths.sh";
#[cfg(unix)]
const SOURCE_LINE_FISH: &str =
    "test -f $HOME/.upstream/metadata/paths.sh; and source $HOME/.upstream/metadata/paths.sh";

pub struct InitCheckReport {
    pub ok: bool,
    pub messages: Vec<String>,
}

#[cfg(windows)]
fn normalize_windows_path(path: &str) -> String {
    let mut normalized = path.replace('/', "\\").trim().to_ascii_lowercase();
    while normalized.ends_with('\\') {
        normalized.pop();
    }
    normalized
}

pub fn initialize(paths: &UpstreamPaths) -> Result<()> {
    create_package_dirs(paths)?;
    create_metadata_files(paths)?;
    create_default_config_file(paths)?;

    #[cfg(windows)]
    add_to_windows_path(paths)?;

    #[cfg(unix)]
    update_shell_profiles(paths)?;

    Ok(())
}

pub fn purge_data(paths: &UpstreamPaths) -> Result<()> {
    if paths.dirs.data_dir.exists() {
        fs::remove_dir_all(&paths.dirs.data_dir)?;
    }
    Ok(())
}

pub fn check(paths: &UpstreamPaths) -> Result<InitCheckReport> {
    let mut report = InitCheckReport {
        ok: true,
        messages: Vec::new(),
    };

    for (label, path) in [
        ("config directory", &paths.dirs.config_dir),
        ("data directory", &paths.dirs.data_dir),
        ("metadata directory", &paths.dirs.metadata_dir),
        ("symlinks directory", &paths.integration.symlinks_dir),
        ("appimages directory", &paths.install.appimages_dir),
        ("binaries directory", &paths.install.binaries_dir),
        ("archives directory", &paths.install.archives_dir),
    ] {
        if path.exists() {
            report
                .messages
                .push(format!("[OK] {} exists: {}", label, path.display()));
        } else {
            report.ok = false;
            report
                .messages
                .push(format!("[FAIL] {} missing: {}", label, path.display()));
        }
    }

    let completion_manager = CompletionManager::new(paths);
    let completion_dirs = completion_manager.installed_shell_completion_dirs();
    if completion_dirs.is_empty() {
        report
            .messages
            .push("[OK] no supported shells detected for completion installation".to_string());
    }
    for (shell, path) in completion_dirs {
        let label = format!("{shell} completions directory");
        if path.exists() {
            report
                .messages
                .push(format!("[OK] {} exists: {}", label, path.display()));
        } else {
            report.ok = false;
            report
                .messages
                .push(format!("[FAIL] {} missing: {}", label, path.display()));
        }
    }

    if paths.config.config_file.exists() {
        report.messages.push(format!(
            "[OK] config file exists: {}",
            paths.config.config_file.display()
        ));
    } else {
        report.ok = false;
        report.messages.push(format!(
            "[FAIL] config file missing: {}",
            paths.config.config_file.display()
        ));
    }

    #[cfg(unix)]
    check_unix_integration(paths, &mut report)?;

    #[cfg(windows)]
    check_windows_integration(paths, &mut report)?;

    Ok(report)
}

#[cfg(unix)]
fn get_installed_shells() -> io::Result<Vec<String>> {
    const SHELLS_FILE: &str = "/etc/shells";
    if !Path::new(SHELLS_FILE).exists() {
        return Ok(Vec::new());
    }
    let content = fs::read_to_string(SHELLS_FILE)?;
    let shells = content
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .map(|l| l.to_string())
        .collect();
    Ok(shells)
}

#[cfg(windows)]
fn add_to_windows_path(paths: &UpstreamPaths) -> Result<()> {
    use winreg::RegKey;
    use winreg::enums::*;

    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let env_key = hkcu
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .context("Failed to open registry key")?;

    let symlinks_path = paths.integration.symlinks_dir.display().to_string();
    let symlinks_norm = normalize_windows_path(&symlinks_path);

    // Get current PATH
    let current_path: String = env_key.get_value("Path").unwrap_or_else(|_| String::new());

    // Check if our path is already in PATH
    let path_entries: Vec<&str> = current_path.split(';').collect();
    if path_entries
        .iter()
        .any(|&p| normalize_windows_path(p) == symlinks_norm)
    {
        return Ok(()); // Already in PATH
    }

    // Add our path to the beginning
    let new_path = if current_path.is_empty() {
        symlinks_path
    } else {
        format!("{};{}", symlinks_path, current_path)
    };

    env_key
        .set_value("Path", &new_path)
        .context("Failed to set PATH")?;

    // Broadcast WM_SETTINGCHANGE to notify other applications
    broadcast_environment_change();

    Ok(())
}

#[cfg(windows)]
fn broadcast_environment_change() {
    use std::ptr;
    use winapi::shared::minwindef::LPARAM;
    use winapi::um::winuser::{
        HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_SETTINGCHANGE,
    };

    unsafe {
        let env_string: Vec<u16> = "Environment\0".encode_utf16().collect();
        SendMessageTimeoutW(
            HWND_BROADCAST,
            WM_SETTINGCHANGE,
            0,
            env_string.as_ptr() as LPARAM,
            SMTO_ABORTIFHUNG,
            5000,
            ptr::null_mut(),
        );
    }
}

fn create_package_dirs(paths: &UpstreamPaths) -> io::Result<()> {
    fs::create_dir_all(&paths.dirs.config_dir)?;
    fs::create_dir_all(&paths.dirs.data_dir)?;
    fs::create_dir_all(&paths.dirs.metadata_dir)?;
    fs::create_dir_all(&paths.install.appimages_dir)?;
    fs::create_dir_all(&paths.install.binaries_dir)?;
    fs::create_dir_all(&paths.install.archives_dir)?;
    fs::create_dir_all(&paths.integration.icons_dir)?;
    fs::create_dir_all(&paths.integration.symlinks_dir)?;
    for (_shell, dir) in CompletionManager::new(paths).installed_shell_completion_dirs() {
        fs::create_dir_all(dir)?;
    }
    Ok(())
}

fn create_default_config_file(paths: &UpstreamPaths) -> Result<()> {
    if paths.config.config_file.exists() {
        return Ok(());
    }

    let storage = ConfigStorage::new(&paths.config.config_file)?;
    storage.save_config()?;
    Ok(())
}

#[cfg(unix)]
fn create_metadata_files(paths: &UpstreamPaths) -> io::Result<()> {
    if !paths.config.paths_file.exists() {
        let export_line = format!(
            r#"export PATH="{}:$PATH""#,
            paths.integration.symlinks_dir.display()
        );
        fs::write(
            &paths.config.paths_file,
            format!(
                "#!/bin/bash\n# Upstream managed PATH additions\n{}\n",
                export_line
            ),
        )?;
    }
    Ok(())
}

#[cfg(windows)]
fn create_metadata_files(_paths: &UpstreamPaths) -> io::Result<()> {
    // On Windows, we use registry-based PATH, so no metadata files needed
    Ok(())
}

#[cfg(unix)]
fn update_shell_profiles(paths: &UpstreamPaths) -> io::Result<()> {
    let shells = get_installed_shells()?;
    for shell_path in shells {
        let shell_name = Path::new(&shell_path)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        match shell_name.to_lowercase().as_str() {
            "bash" | "sh" => {
                add_line_to_profile(paths, ".bashrc", SOURCE_LINE_BASH)?;
            }
            "zsh" => {
                add_line_to_profile(paths, ".zshrc", SOURCE_LINE_BASH)?;
            }
            "fish" => {
                let fish_config = Path::new(".config").join("fish").join("config.fish");
                add_line_to_profile(paths, &fish_config.to_string_lossy(), SOURCE_LINE_FISH)?;
            }
            _ => {}
        }
    }
    Ok(())
}

#[cfg(unix)]
fn check_unix_integration(paths: &UpstreamPaths, report: &mut InitCheckReport) -> io::Result<()> {
    let expected_line = format!(
        r#"export PATH="{}:$PATH""#,
        paths.integration.symlinks_dir.display()
    );

    if !paths.config.paths_file.exists() {
        report.ok = false;
        report.messages.push(format!(
            "[FAIL] PATH metadata file missing: {}",
            paths.config.paths_file.display()
        ));
    } else {
        let content = fs::read_to_string(&paths.config.paths_file)?;
        if content.contains(&expected_line) {
            report.messages.push(format!(
                "[OK] PATH metadata file contains symlink export: {}",
                paths.config.paths_file.display()
            ));
        } else {
            report.ok = false;
            report.messages.push(format!(
                "[FAIL] PATH metadata file missing expected export line: {}",
                paths.config.paths_file.display()
            ));
        }
    }

    let mut profiles_to_check: BTreeSet<(String, String)> = BTreeSet::new();
    for shell_path in get_installed_shells()? {
        let shell_name = Path::new(&shell_path)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        match shell_name.as_str() {
            "bash" | "sh" => {
                profiles_to_check.insert((".bashrc".to_string(), SOURCE_LINE_BASH.to_string()));
            }
            "zsh" => {
                profiles_to_check.insert((".zshrc".to_string(), SOURCE_LINE_BASH.to_string()));
            }
            "fish" => {
                profiles_to_check.insert((
                    ".config/fish/config.fish".to_string(),
                    SOURCE_LINE_FISH.to_string(),
                ));
            }
            _ => {}
        }
    }

    for (profile_rel, expected_line) in profiles_to_check {
        let profile_path = paths.dirs.user_dir.join(&profile_rel);
        if !profile_path.exists() {
            report.ok = false;
            report.messages.push(format!(
                "[FAIL] Shell profile missing: {}",
                profile_path.display()
            ));
            continue;
        }

        let content = fs::read_to_string(&profile_path)?;
        if content.contains(&expected_line) {
            report.messages.push(format!(
                "[OK] Shell profile contains upstream hook: {}",
                profile_path.display()
            ));
        } else {
            report.ok = false;
            report.messages.push(format!(
                "[FAIL] Shell profile missing upstream hook: {}",
                profile_path.display()
            ));
        }
    }

    Ok(())
}

#[cfg(unix)]
fn add_line_to_profile(paths: &UpstreamPaths, relative_path: &str, line: &str) -> io::Result<()> {
    let profile_path = paths.dirs.user_dir.join(relative_path);

    // Ensure parent directory exists
    if let Some(parent) = profile_path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Backup original file
    if profile_path.exists() {
        let backup_path = profile_path.with_extension("bak");
        if !backup_path.exists() {
            fs::copy(&profile_path, &backup_path)?;
        }
    }

    if !profile_path.exists() {
        fs::write(&profile_path, format!("{}\n", line))?;
        return Ok(());
    }

    let content = fs::read_to_string(&profile_path)?;
    if !content.contains(line) {
        let mut file = fs::OpenOptions::new().append(true).open(&profile_path)?;
        writeln!(file, "\n{}", line)?;
    }

    Ok(())
}

#[cfg(unix)]
pub fn cleanup(paths: &UpstreamPaths) -> Result<()> {
    let shells = get_installed_shells()?;
    for shell_path in shells {
        let shell_name = Path::new(&shell_path)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        let profile = match shell_name.to_lowercase().as_str() {
            "bash" | "sh" => Some(".bashrc"),
            "zsh" => Some(".zshrc"),
            "fish" => Some(".config/fish/config.fish"),
            _ => None,
        };
        if let Some(profile_rel) = profile {
            let profile_path = paths.dirs.user_dir.join(profile_rel);
            if !profile_path.exists() {
                continue;
            }
            let mut content = fs::read_to_string(&profile_path)?;
            content = content
                .replace(&format!("{}\n", SOURCE_LINE_BASH), "")
                .replace(SOURCE_LINE_BASH, "")
                .replace(&format!("{}\n", SOURCE_LINE_FISH), "")
                .replace(SOURCE_LINE_FISH, "");
            fs::write(&profile_path, content)?;
        }
    }
    Ok(())
}

#[cfg(windows)]
pub fn cleanup(paths: &UpstreamPaths) -> Result<()> {
    remove_from_windows_path(paths)
}

#[cfg(windows)]
fn remove_from_windows_path(paths: &UpstreamPaths) -> Result<()> {
    use winreg::RegKey;
    use winreg::enums::*;

    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let env_key = hkcu
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .context("Failed to open registry key")?;

    let symlinks_path = paths.integration.symlinks_dir.display().to_string();
    let symlinks_norm = normalize_windows_path(&symlinks_path);

    // Get current PATH
    let current_path: String = env_key.get_value("Path").unwrap_or_else(|_| String::new());

    // Remove our path from PATH
    let path_entries: Vec<&str> = current_path
        .split(';')
        .filter(|&p| normalize_windows_path(p) != symlinks_norm)
        .collect();

    let new_path = path_entries.join(";");

    env_key
        .set_value("Path", &new_path)
        .context("Failed to set PATH")?;

    // Broadcast WM_SETTINGCHANGE to notify other applications
    broadcast_environment_change();

    Ok(())
}

#[cfg(windows)]
fn check_windows_integration(paths: &UpstreamPaths, report: &mut InitCheckReport) -> Result<()> {
    use winreg::RegKey;
    use winreg::enums::*;

    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    let env_key = hkcu
        .open_subkey_with_flags("Environment", KEY_READ)
        .context("Failed to open PATH")?;

    let symlinks_path = paths.integration.symlinks_dir.display().to_string();
    let symlinks_norm = normalize_windows_path(&symlinks_path);
    let current_path: String = env_key.get_value("Path").unwrap_or_else(|_| String::new());

    let in_path = current_path
        .split(';')
        .any(|p| normalize_windows_path(p) == symlinks_norm);

    if in_path {
        report
            .messages
            .push("[OK] Windows PATH contains upstream symlinks directory".to_string());
    } else {
        report.ok = false;
        report
            .messages
            .push("[FAIL] Windows PATH missing upstream symlinks directory".to_string());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::purge_data;
    use crate::utils::static_paths::{
        AppDirs, ConfigPaths, InstallPaths, IntegrationPaths, UpstreamPaths,
    };
    use std::path::{Path, PathBuf};
    use std::time::{SystemTime, UNIX_EPOCH};
    use std::{fs, io};

    fn temp_root(name: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        std::env::temp_dir().join(format!("upstream-init-test-{name}-{nanos}"))
    }

    fn test_paths(root: &Path) -> UpstreamPaths {
        let dirs = AppDirs {
            user_dir: root.to_path_buf(),
            config_dir: root.join("config"),
            data_dir: root.join(".upstream"),
            metadata_dir: root.join(".upstream/metadata"),
        };

        UpstreamPaths {
            config: ConfigPaths {
                config_file: dirs.config_dir.join("config.toml"),
                packages_file: dirs.metadata_dir.join("packages.json"),
                metadata_file: dirs.metadata_dir.join("metadata.json"),
                paths_file: dirs.metadata_dir.join("paths.sh"),
            },
            install: InstallPaths {
                appimages_dir: dirs.data_dir.join("appimages"),
                binaries_dir: dirs.data_dir.join("binaries"),
                archives_dir: dirs.data_dir.join("archives"),
                rollback_dir: dirs.data_dir.join("rollback"),
            },
            integration: IntegrationPaths {
                symlinks_dir: dirs.data_dir.join("symlinks"),
                xdg_applications_dir: dirs.user_dir.join(".local/share/applications"),
                icons_dir: dirs.data_dir.join("icons"),
                bash_completions_dir: dirs
                    .user_dir
                    .join(".local/share/bash-completion/completions"),
                fish_completions_dir: dirs.user_dir.join(".config/fish/completions"),
                zsh_completions_dir: dirs.user_dir.join(".local/share/zsh/site-functions"),
            },
            dirs,
        }
    }

    fn cleanup(path: &Path) -> io::Result<()> {
        if path.exists() {
            fs::remove_dir_all(path)?;
        }
        Ok(())
    }

    #[test]
    fn purge_data_removes_data_dir_but_keeps_config_dir() {
        let root = temp_root("purge");
        let paths = test_paths(&root);
        fs::create_dir_all(&paths.dirs.data_dir).expect("create data dir");
        fs::create_dir_all(&paths.dirs.config_dir).expect("create config dir");
        fs::write(paths.dirs.data_dir.join("data"), b"data").expect("write data");
        fs::write(paths.dirs.config_dir.join("config.toml"), b"").expect("write config");

        purge_data(&paths).expect("purge data");

        assert!(!paths.dirs.data_dir.exists());
        assert!(paths.dirs.config_dir.exists());

        cleanup(&root).expect("cleanup");
    }
}