onelf 0.3.0

Packer CLI for creating onelf single-binary packages
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
//! XDG desktop integration: install/remove .desktop files and icons.
//!
//! `integrate` extracts the icon and desktop file from a packed binary,
//! installs them to XDG-compliant paths, and patches the desktop file's
//! `Exec=` and `Icon=` fields. `unintegrate` reverses the process.

use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use onelf_format::{Footer, Manifest};

use crate::extract::decompress_entry;
use crate::info::read_footer_and_manifest;
use crate::metadata::{resolve_desktop, resolve_icon};

struct IntegrationContext {
    footer: Footer,
    manifest: Manifest,
    binary: PathBuf,
    pkg_name: String,
    ep_name: String,
}

impl IntegrationContext {
    fn load(binary: &Path, entrypoint: Option<&str>) -> io::Result<Self> {
        let binary = binary.canonicalize()?;
        let (footer, manifest) = read_footer_and_manifest(&binary)?;

        let ep_name = match entrypoint {
            Some(name) => {
                // Validate that the entrypoint exists
                if !manifest
                    .entrypoints
                    .iter()
                    .any(|ep| manifest.get_string(ep.name) == name)
                {
                    return Err(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("entrypoint '{name}' not found"),
                    ));
                }
                name.to_string()
            }
            None => {
                let idx = manifest.header.default_entrypoint as usize;
                let ep = &manifest.entrypoints[idx];
                manifest.get_string(ep.name).to_string()
            }
        };

        let name = manifest.name();
        let pkg_name = if name.is_empty() {
            ep_name.clone()
        } else {
            name.to_string()
        };

        Ok(Self {
            footer,
            manifest,
            binary,
            pkg_name,
            ep_name,
        })
    }

    fn read_entry(&self, entry_idx: usize) -> io::Result<Vec<u8>> {
        let entry = &self.manifest.entries[entry_idx];
        let mut file = fs::File::open(&self.binary)?;

        let dict = crate::info::read_dict(&mut file, &self.footer)?;

        decompress_entry(&mut file, &self.footer, entry, dict.as_deref())
    }
}

fn xdg_data_home() -> io::Result<PathBuf> {
    if let Some(val) = std::env::var_os("XDG_DATA_HOME") {
        return Ok(PathBuf::from(val));
    }
    if let Some(home) = std::env::var_os("HOME") {
        return Ok(PathBuf::from(home).join(".local/share"));
    }
    Err(io::Error::new(
        io::ErrorKind::NotFound,
        "neither $XDG_DATA_HOME nor $HOME is set",
    ))
}

/// Sanitize package name into a safe desktop entry name: `onelf-{name}`.
fn integration_name(pkg_name: &str) -> String {
    let sanitized: String = pkg_name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    format!("onelf-{sanitized}")
}

/// Read width and height from a PNG IHDR chunk.
fn png_dimensions(data: &[u8]) -> Option<(u32, u32)> {
    if data.len() < 24 || data[0..8] != *b"\x89PNG\r\n\x1a\n" {
        return None;
    }
    let w = u32::from_be_bytes(data[16..20].try_into().ok()?);
    let h = u32::from_be_bytes(data[20..24].try_into().ok()?);
    Some((w, h))
}

/// Install the icon and return the icon theme name for the `Icon=` field.
fn install_icon(
    ctx: &IntegrationContext,
    data_home: &Path,
    int_name: &str,
) -> io::Result<Option<String>> {
    let icon_idx = match resolve_icon(&ctx.manifest, &ctx.ep_name) {
        Some(idx) => idx,
        None => return Ok(None),
    };

    let icon_data = ctx.read_entry(icon_idx)?;
    let icon_path = ctx.manifest.entry_path(icon_idx);
    let is_svg = icon_path.ends_with(".svg");

    let dest = if is_svg {
        let dir = data_home.join("icons/hicolor/scalable/apps");
        fs::create_dir_all(&dir)?;
        dir.join(format!("{int_name}.svg"))
    } else {
        let (w, h) = png_dimensions(&icon_data).unwrap_or((256, 256));
        let dir = data_home.join(format!("icons/hicolor/{w}x{h}/apps"));
        fs::create_dir_all(&dir)?;
        dir.join(format!("{int_name}.png"))
    };

    fs::write(&dest, &icon_data)?;
    eprintln!("  Icon: {}", dest.display());

    Ok(Some(int_name.to_string()))
}

/// Install the desktop file, patching or generating as needed.
fn install_desktop(
    ctx: &IntegrationContext,
    data_home: &Path,
    int_name: &str,
    icon_name: Option<&str>,
) -> io::Result<()> {
    let desktop_dir = data_home.join("applications");
    fs::create_dir_all(&desktop_dir)?;
    let dest = desktop_dir.join(format!("{int_name}.desktop"));

    let exec_path = ctx.binary.to_str().unwrap_or("");

    let content = match resolve_desktop(&ctx.manifest, &ctx.ep_name) {
        Some(idx) => {
            let raw = ctx.read_entry(idx)?;
            let text = String::from_utf8(raw).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    "desktop file is not valid UTF-8",
                )
            })?;
            patch_desktop_file(&text, exec_path, icon_name)
        }
        None => generate_desktop_file(&ctx.pkg_name, exec_path, icon_name),
    };

    fs::write(&dest, content.as_bytes())?;
    eprintln!("  Desktop: {}", dest.display());
    Ok(())
}

/// Quote a single `Exec=` field argument per the Desktop Entry spec: a
/// value containing whitespace or a reserved character is double-quoted,
/// with `"`, `` ` ``, `$`, and `\` backslash-escaped inside the quotes.
fn desktop_exec_arg(s: &str) -> String {
    let reserved = |c: char| c.is_whitespace() || "\"'\\<>~|&;$*?#()`".contains(c);
    if !s.is_empty() && !s.chars().any(reserved) {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        if matches!(c, '"' | '`' | '$' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    out
}

/// Given the value of an `Exec=` line (everything after `Exec=`), return the
/// argument tail after the first argument (the executable), honoring Desktop
/// Entry double-quote quoting so a quoted or space-containing executable path
/// is removed as one whole argument rather than split on its spaces.
fn exec_arg_tail(value: &str) -> &str {
    let bytes = value.as_bytes();
    let mut i = 0;
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    if i < bytes.len() && bytes[i] == b'"' {
        // Quoted argument: skip to the matching unescaped closing quote.
        i += 1;
        while i < bytes.len() {
            match bytes[i] {
                b'\\' if i + 1 < bytes.len() => i += 2,
                b'"' => {
                    i += 1;
                    break;
                }
                _ => i += 1,
            }
        }
    } else {
        // Unquoted argument: skip to the next whitespace.
        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
            i += 1;
        }
    }
    // Skip the whitespace separating the first argument from the tail.
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    &value[i..]
}

/// Patch `Exec=`, `TryExec=`, and `Icon=` in an existing desktop file.
fn patch_desktop_file(content: &str, exec_path: &str, icon_name: Option<&str>) -> String {
    let quoted = desktop_exec_arg(exec_path);
    let mut lines: Vec<String> = content.lines().map(String::from).collect();
    let mut has_exec = false;
    let mut has_tryexec = false;

    for line in &mut lines {
        if line.starts_with("Exec=") {
            // Replace the executable (the first argument), keeping the rest of
            // the command line (arguments / field codes) verbatim.
            let tail = exec_arg_tail(&line[5..]);
            if tail.is_empty() {
                *line = format!("Exec={quoted}");
            } else {
                *line = format!("Exec={quoted} {tail}");
            }
            has_exec = true;
        } else if line.starts_with("TryExec=") {
            *line = format!("TryExec={quoted}");
            has_tryexec = true;
        } else if line.starts_with("Icon=") {
            if let Some(name) = icon_name {
                *line = format!("Icon={name}");
            }
        }
    }

    // Insert any missing keys right after the `[Desktop Entry]` header, so
    // they land in that group. A desktop file can have several groups
    // (`[Desktop Action ...]`), and appending at EOF could put the key in a
    // trailing group where it has no effect.
    let mut insert_at = lines
        .iter()
        .position(|l| l.trim() == "[Desktop Entry]")
        .map(|h| h + 1)
        .unwrap_or(lines.len());
    if !has_exec {
        lines.insert(insert_at, format!("Exec={quoted}"));
        insert_at += 1;
    }
    if !has_tryexec {
        lines.insert(insert_at, format!("TryExec={quoted}"));
    }

    let mut result = lines.join("\n");
    if !result.ends_with('\n') {
        result.push('\n');
    }
    result
}

/// Generate a minimal `.desktop` file.
fn generate_desktop_file(name: &str, exec_path: &str, icon_name: Option<&str>) -> String {
    let mut lines = vec![
        "[Desktop Entry]".to_string(),
        "Type=Application".to_string(),
        format!("Name={name}"),
        format!("Exec={exec_path}"),
        format!("TryExec={exec_path}"),
    ];
    if let Some(icon) = icon_name {
        lines.push(format!("Icon={icon}"));
    }
    lines.push("Terminal=false".to_string());
    lines.push(String::new());
    lines.join("\n")
}

/// Scan `hicolor/*/apps/` and remove icons matching `int_name`.
fn remove_icons(hicolor: &Path, int_name: &str) -> io::Result<bool> {
    let entries = match fs::read_dir(hicolor) {
        Ok(e) => e,
        Err(_) => return Ok(false),
    };

    let target_svg = format!("{int_name}.svg");
    let target_png = format!("{int_name}.png");
    let mut removed = false;

    for entry in entries.flatten() {
        if !entry.file_type().map_or(false, |ft| ft.is_dir()) {
            continue;
        }
        let apps_dir = entry.path().join("apps");
        if !apps_dir.is_dir() {
            continue;
        }
        for name in [&target_svg, &target_png] {
            let path = apps_dir.join(name);
            if path.exists() {
                fs::remove_file(&path)?;
                eprintln!("  Removed: {}", path.display());
                removed = true;
            }
        }
    }

    Ok(removed)
}

fn update_desktop_database(data_home: &Path) {
    let _ = std::process::Command::new("update-desktop-database")
        .arg(data_home.join("applications"))
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
}

pub fn integrate(binary: &Path, entrypoint: Option<&str>) -> io::Result<()> {
    let ctx = IntegrationContext::load(binary, entrypoint)?;
    let data_home = xdg_data_home()?;
    let int_name = integration_name(&ctx.pkg_name);

    // Remove any stale icons first (handles format changes on re-integrate)
    let hicolor = data_home.join("icons/hicolor");
    if hicolor.exists() {
        let _ = remove_icons(&hicolor, &int_name);
    }

    let icon_name = install_icon(&ctx, &data_home, &int_name)?;
    install_desktop(&ctx, &data_home, &int_name, icon_name.as_deref())?;
    update_desktop_database(&data_home);

    eprintln!("Integrated '{}'", ctx.pkg_name);
    Ok(())
}

pub fn unintegrate(binary: &Path, entrypoint: Option<&str>) -> io::Result<()> {
    let ctx = IntegrationContext::load(binary, entrypoint)?;
    let data_home = xdg_data_home()?;
    let int_name = integration_name(&ctx.pkg_name);

    let mut removed = false;

    let desktop_path = data_home
        .join("applications")
        .join(format!("{int_name}.desktop"));
    if desktop_path.exists() {
        fs::remove_file(&desktop_path)?;
        eprintln!("  Removed: {}", desktop_path.display());
        removed = true;
    }

    let hicolor = data_home.join("icons/hicolor");
    if hicolor.exists() {
        removed |= remove_icons(&hicolor, &int_name)?;
    }

    update_desktop_database(&data_home);

    if removed {
        eprintln!("Unintegrated '{}'", ctx.pkg_name);
    } else {
        eprintln!("Nothing to unintegrate for '{}'", ctx.pkg_name);
    }

    Ok(())
}

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

    #[test]
    fn exec_arg_tail_handles_quoting() {
        // Unquoted executable, arguments preserved.
        assert_eq!(exec_arg_tail("/usr/bin/foo %U"), "%U");
        // Quoted executable containing a space: removed whole, tail kept.
        assert_eq!(exec_arg_tail("\"/opt/my app/bin\" %F extra"), "%F extra");
        // No arguments.
        assert_eq!(exec_arg_tail("/usr/bin/foo"), "");
        assert_eq!(exec_arg_tail("\"/opt/my app/bin\""), "");
        // Leading whitespace tolerated.
        assert_eq!(exec_arg_tail("  /usr/bin/foo  %U"), "%U");
    }

    #[test]
    fn patch_replaces_quoted_exec_without_fragments() {
        let desktop = "[Desktop Entry]\nType=Application\nExec=\"/opt/my app/bin\" %F\nIcon=old\n";
        let out = patch_desktop_file(desktop, "/new/path/app", Some("newicon"));
        // The old quoted path is gone (no leftover `app/bin"` fragment) and
        // the field code is preserved.
        assert!(out.contains("Exec=/new/path/app %F"), "got:\n{out}");
        assert!(!out.contains("app/bin"), "stale path fragment left:\n{out}");
        assert!(out.contains("Icon=newicon"));
    }

    #[test]
    fn patch_quotes_exec_path_with_spaces() {
        let desktop = "[Desktop Entry]\nExec=/usr/bin/old %U\n";
        let out = patch_desktop_file(desktop, "/opt/has space/app", None);
        assert!(
            out.contains("Exec=\"/opt/has space/app\" %U"),
            "got:\n{out}"
        );
    }
}