retch-cli 0.1.4

A fast, feature-rich system information fetcher written in Rust (similar to fastfetch or neofetch)
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
// Exact Fastfetch ASCII logos (intact, unmodified)
// Source: https://github.com/fastfetch-cli/fastfetch/src/logo/ascii/

// Embedded distro logos (PNG)
// Place real logos in assets/logos/<distro>.png
// Example: assets/logos/arch.png, assets/logos/fedora.png, assets/logos/tux.png

/// Returns the raw PNG bytes for an embedded distro logo.
///
/// If the distro is not recognized, it falls back to the Tux (Linux) logo.
/// Only available when the `graphics` feature is enabled.
#[cfg(feature = "graphics")]
pub fn get_embedded_logo(distro: Option<&str>) -> Option<&'static [u8]> {
    let d = distro.map(|s| s.to_lowercase());
    match d.as_deref() {
        Some("arch") => Some(include_bytes!("../assets/logos/arch.png")),
        Some("debian") => Some(include_bytes!("../assets/logos/debian.png")),
        Some("fedora") => Some(include_bytes!("../assets/logos/fedora.png")),
        Some("nixos") => Some(include_bytes!("../assets/logos/nixos.png")),
        Some("ubuntu") => Some(include_bytes!("../assets/logos/ubuntu.png")),
        _ => Some(include_bytes!("../assets/logos/tux.png")),
    }
}

/// Fallback for non-graphics build to provide Tux bytes for Chafa if needed.
#[cfg(not(feature = "graphics"))]
pub fn get_embedded_logo(_distro: Option<&str>) -> Option<&'static [u8]> {
    Some(include_bytes!("../assets/logos/tux.png"))
}

/// Attempts to detect the current Linux distribution by reading `/etc/os-release`.
pub fn detect_distro() -> Option<String> {
    if let Ok(content) = std::fs::read_to_string("/etc/os-release") {
        for line in content.lines() {
            if line.starts_with("ID=") {
                let id = line.trim_start_matches("ID=").trim_matches('"');
                return Some(id.to_string());
            }
        }
    }
    None
}

/// Returns a list of strings representing the ASCII art for a given distro.
///
/// All ASCII logos are sourced from or compatible with Fastfetch.
pub fn get_ascii_logo(distro: Option<&str>) -> Vec<String> {
    let d = distro.map(|s| s.to_lowercase());

    match d.as_deref() {
        // Arch Linux - exact from Fastfetch
        Some("arch") => vec![
            "               -`".to_string(),
            "                 .o+`".to_string(),
            "                `ooo/".to_string(),
            "               `+oooo:".to_string(),
            "              `+oooooo:".to_string(),
            "              -+oooooo+:".to_string(),
            "            `/:-:++oooo+:".to_string(),
            "           `/++++/+++++++:".to_string(),
            "          `/++++++++++++++:".to_string(),
            "         `/+++ooooooooooooo/`".to_string(),
            "        ./ooosssso++osssssso+`".to_string(),
            "       .oossssso-````/ossssss+`".to_string(),
            "      -osssssso.      :ssssssso.".to_string(),
            "     :osssssss/        osssso+++.".to_string(),
            "    /ossssssss/        +ssssooo/-".to_string(),
            "  `/ossssso+/:-        -:/+osssso+-".to_string(),
            " `+sso+:-`                 `.-/+oso:".to_string(),
            "`++:.                           `-/+/".to_string(),
            ".`                                 `".to_string(),
        ],

        // Debian - exact from Fastfetch
        Some("debian") => vec![
            " _,met$$$$$$$$$$gg.".to_string(),
            "      ,g$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$P.".to_string(),
            "    ,g$$$$P\"\"       \"\"\"Y$$$$.\".".to_string(),
            "   ,$$$$P'              `$$$$$$.".to_string(),
            "',$$$$P       ,ggs.     `$$$$b:".to_string(),
            "`d$$$$'     ,$P\"'   .    $$$$$$".to_string(),
            " $$$$P      d$'     ,    $$$$P".to_string(),
            " $$$$:      $$$.   -    ,d$$$$'".to_string(),
            " $$$$;      Y$b._   _,d$P'".to_string(),
            " Y$$$$.    .`\"Y$$$$$$$$P\"'".to_string(),
            " `$$$$b      \"-.__".to_string(),
            "  `Y$$$$b".to_string(),
            "   `Y$$$$.".to_string(),
            "     `$$$$b.".to_string(),
            "       `Y$$$$b.".to_string(),
            "         `\"Y$$b._".to_string(),
            "             `\"\"\"\"".to_string(),
        ],

        // Fedora - exact from Fastfetch
        Some("fedora") => vec![
            "             .',;::::;,'.".to_string(),
            "         .';:cccccccccccc:;,.".to_string(),
            "      .;cccccccccccccccccccccc;.".to_string(),
            "    .:cccccccccccccccccccccc:.".to_string(),
            "  .;ccccccccccccc;.:dddl:.;ccccccc;.".to_string(),
            " .:ccccccccccccc;OWMKOOXMWd;ccccccc:.".to_string(),
            ".:ccccccccccccc;KMMc;cc;xMMc;ccccccc:.".to_string(),
            ",cccccccccccccc;MMM.;cc;;WW:;cccccccc,".to_string(),
            ":cccccccccccccc;MMM.;cccccccccccccccc:".to_string(),
            ":ccccccc;oxOOOo;MMM000k.;cccccccccccc:".to_string(),
            "cccccc;0MMKxdd:;MMMkddc.;cccccccccccc;".to_string(),
            "ccccc;XMO';cccc;MMM.;cccccccccccccccc'".to_string(),
            "ccccc;MMo;ccccc;MMW.;ccccccccccccccc;".to_string(),
            "ccccc;0MNc.ccc.xMMd;ccccccccccccccc;".to_string(),
            "cccccc;dNMWXXXWM0:;cccccccccccccc:,".to_string(),
            "cccccccc;.:odl:.;cccccccccccccc:,.".to_string(),
            "ccccccccccccccccccccccccccccc:'.".to_string(),
            ":ccccccccccccccccccccccc:;,..".to_string(),
        ],

        // NixOS - exact from Fastfetch
        Some("nixos") => vec![
            "          ::::.    ':::::".to_string(),
            "      ':::::::::.   ':::::::::".to_string(),
            "  .:::::::::::::     ::::::::::::.".to_string(),
            "  :::::::::::'        ::::::::::::".to_string(),
            " .::::::::::'          :::::::::::.".to_string(),
            " ::::::::::             :::::::::::".to_string(),
            " :::::::::              :::::::::::".to_string(),
            " ::::::::                ::::::::::".to_string(),
            " '::::::.                '::::::::'".to_string(),
            "  ':::::                  '::::::'".to_string(),
            "   ':::                    '::::'".to_string(),
            "    ':                      ':".to_string(),
        ],

        // Ubuntu - exact from Fastfetch
        Some("ubuntu") => vec![
            "                          ....".to_string(),
            "          ....,,:::::ccccclllclllcc:::;,,....".to_string(),
            "      ..,;::cccllllllllllllllllllllllllcc::;..".to_string(),
            "    ..,;::cccllllllllllllllllllllllllllllcc::;..".to_string(),
            "  ..,;::cccllllllllllllllllllllllllllllllllcc::;..".to_string(),
            " ..,;::cccllllllllllllllllllllllllllllllllllcc::;..".to_string(),
            "..,;::cccllllllllllllllllllllllllllllllllllllcc::;.".to_string(),
            "..,;::cccllllllllllllllllllllllllllllllllllllcc::;.".to_string(),
            "..,;::cccllllllllllllllllllllllllllllllllllllcc::;.".to_string(),
            "..,;::cccllllllllllllllllllllllllllllllllllllcc::;.".to_string(),
            "..,;::cccllllllllllllllllllllllllllllllllllllcc::;.".to_string(),
            "..,;::cccllllllllllllllllllllllllllllllllllllcc::;.".to_string(),
        ],

        // Fallback: Tux (Linux)
        _ => vec![
            "    .--.".to_string(),
            "   |o_o |".to_string(),
            "   |:_/ |".to_string(),
            "  //   \\ \\".to_string(),
            " (|     | )".to_string(),
            "/'\\_   _/`\\".to_string(),
            "\\___)=(___/".to_string(),
        ],
    }
}

/// Checks if the terminal supports the Kitty inline image protocol.
pub fn supports_kitty() -> bool {
    std::env::var("TERM")
        .map(|t| t == "xterm-kitty")
        .unwrap_or(false)
        || std::env::var("TERMINAL_EMULATOR")
            .map(|t| t == "iterm-kitty" || t == "iTerm.app")
            .unwrap_or(false)
        || std::env::var("TERM_PROGRAM")
            .map(|t| t == "rio")
            .unwrap_or(false)
}

/// Checks if the terminal supports the iTerm2 inline image protocol.
pub fn supports_iterm2() -> bool {
    if let Ok(prog) = std::env::var("TERM_PROGRAM") {
        if prog == "iTerm.app" || prog == "WezTerm" || prog == "rio" {
            return true;
        }
    }
    false
}

/// Checks if the terminal supports Sixel graphics (heuristic based on environment).
pub fn supports_sixel() -> bool {
    if let Ok(term) = std::env::var("TERM") {
        let term = term.to_lowercase();
        if term.contains("sixel") || term.contains("foot") || term.contains("mlterm") {
            return true;
        }
    }

    if let Ok(prog) = std::env::var("TERM_PROGRAM") {
        if prog == "WezTerm" || prog == "iTerm.app" || prog == "rio" {
            return true;
        }
    }

    if std::env::var("WT_SESSION").is_ok() {
        return true;
    }

    false
}

/// Checks if the `chafa` command-line tool is available in the system path.
pub fn chafa_available() -> bool {
    std::process::Command::new("chafa")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Write embedded logo bytes to a temporary file and return the path.
fn write_temp_logo(bytes: &[u8]) -> std::io::Result<std::path::PathBuf> {
    let temp_path = std::env::temp_dir().join(format!("retch_logo_{}.png", std::process::id()));
    std::fs::write(&temp_path, bytes)?;
    Ok(temp_path)
}

/// Attempts to render an image using the `chafa` utility.
///
/// Chafa renders images using high-quality Unicode symbols, providing a
/// good graphical fallback for many terminal emulators.
pub fn print_with_chafa(path: &std::path::Path) -> bool {
    let output = std::process::Command::new("chafa")
        .arg("--format")
        .arg("symbols")
        .arg("--size")
        .arg("40x20")
        .arg(path)
        .output();

    match output {
        Ok(out) if out.status.success() => {
            print!("{}", String::from_utf8_lossy(&out.stdout));
            true
        }
        _ => false,
    }
}

/// Print logo for a distro following the strict priority:
/// 1. Real graphic logo (if terminal supports it and embedded logo exists)
/// 2. Chafa high-quality symbols (if chafa is available)
/// 3. Real Fastfetch ASCII logo (always available)
pub fn print_distro_logo(distro: Option<&str>) {
    print_distro_logo_with_ascii(distro, false);
}

/// Renders the distribution logo with an option to force ASCII mode.
///
/// This is the primary entry point for logo rendering, handling the entire
/// priority chain from high-res graphics down to text-based ASCII.
pub fn print_distro_logo_with_ascii(distro: Option<&str>, ascii_only: bool) {
    if ascii_only {
        // Force ASCII path
        let art = get_ascii_logo(distro);
        for line in art {
            println!("{}", line);
        }
        return;
    }

    let supports_kitty = supports_kitty();
    let supports_iterm2 = supports_iterm2();
    let supports_sixel = supports_sixel();
    let has_chafa = chafa_available();

    // 1. Try embedded graphical logo (Kitty)
    #[cfg(feature = "graphics")]
    if supports_kitty {
        if let Some(bytes) = get_embedded_logo(distro) {
            if !bytes.is_empty() {
                print_graphical_logo(bytes);
                return;
            }
        }
    }

    // 2. Try embedded graphical logo (iTerm2)
    #[cfg(feature = "graphics")]
    if supports_iterm2 {
        if let Some(bytes) = get_embedded_logo(distro) {
            if !bytes.is_empty() {
                print_iterm2_logo(bytes);
                return;
            }
        }
    }

    // 3. Try embedded graphical logo (Sixel)
    #[cfg(feature = "graphics")]
    if supports_sixel {
        if let Some(bytes) = get_embedded_logo(distro) {
            if !bytes.is_empty() {
                print_sixel_logo(bytes);
                return;
            }
        }
    }

    // 3. Try chafa using embedded distro logo
    if has_chafa {
        if let Some(bytes) = get_embedded_logo(distro) {
            if bytes.len() > 100 {
                if let Ok(temp_path) = write_temp_logo(bytes) {
                    if print_with_chafa(&temp_path) {
                        let _ = std::fs::remove_file(&temp_path);
                        return;
                    }
                    let _ = std::fs::remove_file(&temp_path);
                }
            }
        }
    }

    // 4. Final fallback: Real Fastfetch ASCII logo
    let art = get_ascii_logo(distro);
    for line in art {
        println!("{}", line);
    }
}

/// Renders a raw image buffer using the iTerm2 inline image protocol.
#[cfg(feature = "graphics")]
pub fn print_iterm2_logo(image_data: &[u8]) {
    use base64::Engine;
    let encoded = base64::engine::general_purpose::STANDARD.encode(image_data);
    print!(
        "\x1b]1337;File=inline=1;preserveAspectRatio=1:{}\x07",
        encoded
    );
    println!(); // iTerm2 typically needs a newline after the logo
}

/// Loads an image from a file and prints it using the iTerm2 protocol.
#[cfg(feature = "graphics")]
pub fn print_iterm2_logo_from_path(path: &std::path::Path) {
    if let Ok(bytes) = std::fs::read(path) {
        print_iterm2_logo(&bytes);
    } else {
        println!("[Could not read logo for iTerm2 from {}]", path.display());
    }
}

/// Placeholder for iTerm2 logo rendering when the `graphics` feature is disabled.
#[cfg(not(feature = "graphics"))]
pub fn print_iterm2_logo(_image_data: &[u8]) {
    println!("[iTerm2 logo support requires --features graphics]");
}

/// Renders a raw image buffer using the Kitty graphics protocol.
#[cfg(feature = "graphics")]
pub fn print_graphical_logo(image_data: &[u8]) {
    use base64::Engine;

    let (width, height) = image::load_from_memory(image_data)
        .map(|img| (img.width(), img.height()))
        .unwrap_or((0, 0));

    let encoded = base64::engine::general_purpose::STANDARD.encode(image_data);

    if width > 0 && height > 0 {
        println!("\x1b_Gf=100,s={},v={},a=T;{}\x1b\\", width, height, encoded);
    } else {
        println!("\x1b_Gf=100,a=T;{}", encoded);
    }
}

/// Renders a raw image buffer (e.g. PNG bytes) using the Sixel graphics protocol.
#[cfg(feature = "graphics")]
pub fn print_sixel_logo(image_data: &[u8]) {
    if let Ok(img) = image::load_from_memory(image_data) {
        let rgba = img.to_rgba8();
        let (width, height) = rgba.dimensions();
        print_sixel_rgba(rgba.as_raw(), width, height);
    }
}

/// Renders raw RGBA pixels using the Sixel graphics protocol.
#[cfg(feature = "graphics")]
pub fn print_sixel_rgba(rgba: &[u8], width: u32, height: u32) {
    use icy_sixel::SixelImage;

    match SixelImage::try_from_rgba(rgba.to_vec(), width as usize, height as usize) {
        Ok(sixel_img) => match sixel_img.encode() {
            Ok(sixel_str) => {
                print!("{}", sixel_str);
            }
            Err(e) => eprintln!("[Sixel Encoding Error: {}]", e),
        },
        Err(e) => eprintln!("[Sixel Creation Error: {}]", e),
    }
}

/// Placeholder for graphical logo rendering when the `graphics` feature is disabled.
#[cfg(not(feature = "graphics"))]
pub fn print_graphical_logo(_image_data: &[u8]) {
    println!("[Graphical logo support requires --features graphics]");
}

/// Placeholder for sixel logo rendering when the `graphics` feature is disabled.
#[cfg(not(feature = "graphics"))]
pub fn print_sixel_logo(_image_data: &[u8]) {
    println!("[Sixel logo support requires --features graphics]");
}

/// Loads an image from a file, resizes it, and prints it using the graphics protocol.
#[cfg(feature = "graphics")]
pub fn print_graphical_logo_from_path(path: &std::path::Path) {
    use image::ImageFormat;
    match image::open(path) {
        Ok(img) => {
            let resized = img.resize(128, 128, image::imageops::FilterType::Lanczos3);
            let mut png_data = Vec::new();
            if resized
                .write_to(&mut std::io::Cursor::new(&mut png_data), ImageFormat::Png)
                .is_ok()
            {
                print_graphical_logo(&png_data);
            } else {
                println!("[Failed to encode logo as PNG]");
            }
        }
        Err(_) => {
            println!("[Could not load graphical logo from {}]", path.display());
        }
    }
}

/// Loads an image from a file, resizes it, and prints it using the Sixel protocol.
#[cfg(feature = "graphics")]
pub fn print_sixel_logo_from_path(path: &std::path::Path) {
    match image::open(path) {
        Ok(img) => {
            let resized = img.resize(128, 128, image::imageops::FilterType::Lanczos3);
            let rgba = resized.to_rgba8();
            let (width, height) = rgba.dimensions();
            print_sixel_rgba(rgba.as_raw(), width, height);
        }
        Err(_) => {
            println!("[Could not load logo for Sixel from {}]", path.display());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_ascii_logo_arch() {
        let logo = get_ascii_logo(Some("arch"));
        assert!(!logo.is_empty());
        assert!(logo[0].contains("`"));
    }

    #[test]
    fn test_get_ascii_logo_unknown() {
        let logo = get_ascii_logo(Some("unknown_distro"));
        assert!(!logo.is_empty());
        // Should fall back to Tux
        assert!(logo.iter().any(|line| line.contains("o_o")));
    }

    #[test]
    fn test_get_ascii_logo_none() {
        let logo = get_ascii_logo(None);
        assert!(!logo.is_empty());
    }
}