installrs 0.1.0-rc10

Build self-contained software installers in plain Rust, with an optional native wizard GUI (Win32 / GTK3), component selection, progress, cancellation, and compression.
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
//! Cross-platform builder operations (file / dir / uninstaller / mkdir /
//! remove) plus the shared helpers that implement their file-system work.

use std::path::Path;

use anyhow::{anyhow, Context, Result};

use crate::embedded::{DirChild, DirChildKind, EmbeddedEntry};
use crate::types::{
    DirErrorHandler, DirErrorHandlerRef, DirFilter, DirFilterRef, ErrorAction, OverwriteMode,
};
use crate::{Installer, Source};

/// Implement the shared `status()`, `log()`, and `weight()` setters on a
/// builder op. The op struct must have `status: Option<String>`,
/// `log: Option<String>`, and `weight: u32` fields.
macro_rules! impl_common_op_setters {
    ($ty:ident) => {
        impl<'i> $ty<'i> {
            pub fn status(mut self, s: impl AsRef<str>) -> Self {
                self.status = Some(s.as_ref().to_string());
                self
            }
            pub fn log(mut self, s: impl AsRef<str>) -> Self {
                self.log = Some(s.as_ref().to_string());
                self
            }
            /// Step weight this op consumes from the component budget. Default 1.
            pub fn weight(mut self, w: u32) -> Self {
                self.weight = w;
                self
            }
        }
    };
}
#[allow(unused_imports)]
pub(crate) use impl_common_op_setters;

// ── Builder ops ─────────────────────────────────────────────────────────────

pub struct FileOp<'i> {
    pub(crate) installer: &'i mut Installer,
    pub(crate) source: Source,
    pub(crate) dst: String,
    pub(crate) status: Option<String>,
    pub(crate) log: Option<String>,
    pub(crate) overwrite: OverwriteMode,
    pub(crate) mode: Option<u32>,
    pub(crate) weight: u32,
}

impl_common_op_setters!(FileOp);

impl<'i> FileOp<'i> {
    pub fn overwrite(mut self, mode: OverwriteMode) -> Self {
        self.overwrite = mode;
        self
    }
    /// Unix file permissions (octal, e.g. `0o755`). No-op on Windows.
    pub fn mode(mut self, mode: u32) -> Self {
        self.mode = Some(mode);
        self
    }
    pub fn install(self) -> Result<()> {
        self.installer.check_cancelled()?;
        self.installer.emit_status(&self.status);
        self.installer.emit_log(&self.log);

        let (raw_bytes, compression) = find_file(self.installer.entries, self.source.0)?;
        let dest = self.installer.resolve_out_path(&self.dst)?;
        let overwrite = self.overwrite;
        let mode = self.mode;
        let weight = self.weight;

        self.installer.run_weighted_step(weight, || {
            if apply_overwrite_policy(&dest, overwrite)? {
                return Ok(());
            }
            let bytes = Installer::decompress(raw_bytes, compression)?;
            write_file(&dest, &bytes)?;
            apply_mode(&dest, mode)?;
            Ok(())
        })
    }
}

pub struct DirOp<'i> {
    pub(crate) installer: &'i mut Installer,
    pub(crate) source: Source,
    pub(crate) dst: String,
    pub(crate) status: Option<String>,
    pub(crate) log: Option<String>,
    pub(crate) overwrite: OverwriteMode,
    pub(crate) mode: Option<u32>,
    pub(crate) filter: Option<DirFilter>,
    pub(crate) on_error: Option<DirErrorHandler>,
    /// Weight applied per-file inside the directory tree. Default 1.
    pub(crate) weight: u32,
}

impl_common_op_setters!(DirOp);

impl<'i> DirOp<'i> {
    pub fn overwrite(mut self, mode: OverwriteMode) -> Self {
        self.overwrite = mode;
        self
    }
    /// Unix file permissions applied to each installed file. No-op on Windows.
    pub fn mode(mut self, mode: u32) -> Self {
        self.mode = Some(mode);
        self
    }
    /// Filter closure: receives relative path within the directory; return
    /// `true` to install the file.
    pub fn filter<F: Fn(&str) -> bool + 'static>(mut self, f: F) -> Self {
        self.filter = Some(Box::new(f));
        self
    }
    /// Per-file error handler: receives the relative path and error, returns
    /// [`ErrorAction::Skip`] to continue or [`ErrorAction::Abort`] to propagate.
    pub fn on_error<F: Fn(&str, &anyhow::Error) -> ErrorAction + 'static>(mut self, f: F) -> Self {
        self.on_error = Some(Box::new(f));
        self
    }
    pub fn install(self) -> Result<()> {
        self.installer.check_cancelled()?;
        self.installer.emit_status(&self.status);
        self.installer.emit_log(&self.log);

        let children = find_dir(self.installer.entries, self.source.0)?;
        let dest = self.installer.resolve_out_path(&self.dst)?;
        std::fs::create_dir_all(&dest)
            .with_context(|| format!("failed to create directory: {}", dest.display()))?;

        install_children(
            children,
            &dest,
            "",
            self.installer,
            self.overwrite,
            self.mode,
            self.filter.as_deref(),
            self.on_error.as_deref(),
            self.weight,
        )
    }
}

pub struct UninstallerOp<'i> {
    pub(crate) installer: &'i mut Installer,
    pub(crate) dst: String,
    pub(crate) status: Option<String>,
    pub(crate) log: Option<String>,
    pub(crate) overwrite: OverwriteMode,
    pub(crate) weight: u32,
}

impl_common_op_setters!(UninstallerOp);

impl<'i> UninstallerOp<'i> {
    pub fn overwrite(mut self, mode: OverwriteMode) -> Self {
        self.overwrite = mode;
        self
    }
    pub fn install(self) -> Result<()> {
        self.installer.check_cancelled()?;
        self.installer.emit_status(&self.status);
        self.installer.emit_log(&self.log);

        let dest = self.installer.resolve_out_path(&self.dst)?;
        let overwrite = self.overwrite;
        let weight = self.weight;
        let data_ptr = self.installer.uninstaller_data;
        let compression = self.installer.uninstaller_compression;

        self.installer.run_weighted_step(weight, || {
            if apply_overwrite_policy(&dest, overwrite)? {
                return Ok(());
            }
            let data = Installer::decompress(data_ptr, compression)?;
            write_file(&dest, &data)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))
                    .with_context(|| format!("failed to set permissions on: {}", dest.display()))?;
            }
            Ok(())
        })
    }
}

pub struct MkdirOp<'i> {
    pub(crate) installer: &'i mut Installer,
    pub(crate) dst: String,
    pub(crate) status: Option<String>,
    pub(crate) log: Option<String>,
    pub(crate) weight: u32,
}

impl_common_op_setters!(MkdirOp);

impl<'i> MkdirOp<'i> {
    pub fn install(self) -> Result<()> {
        self.installer.check_cancelled()?;
        self.installer.emit_status(&self.status);
        self.installer.emit_log(&self.log);
        let path = self.installer.resolve_out_path(&self.dst)?;
        self.installer.run_weighted_step(self.weight, || {
            std::fs::create_dir_all(&path)
                .with_context(|| format!("failed to create directory: {}", path.display()))
        })
    }
}

pub struct RemoveOp<'i> {
    pub(crate) installer: &'i mut Installer,
    pub(crate) path: String,
    pub(crate) status: Option<String>,
    pub(crate) log: Option<String>,
    pub(crate) weight: u32,
}

impl_common_op_setters!(RemoveOp);

impl<'i> RemoveOp<'i> {
    pub fn install(self) -> Result<()> {
        self.installer.check_cancelled()?;
        self.installer.emit_status(&self.status);
        self.installer.emit_log(&self.log);
        let p = self.installer.resolve_out_path(&self.path)?;
        self.installer.run_weighted_step(self.weight, || {
            if !p.exists() {
                return Ok(());
            }
            if p.is_dir() {
                std::fs::remove_dir_all(&p)
                    .with_context(|| format!("failed to remove directory: {}", p.display()))
            } else {
                std::fs::remove_file(&p)
                    .with_context(|| format!("failed to remove file: {}", p.display()))
            }
        })
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

pub(crate) fn find_file(
    entries: &'static [EmbeddedEntry],
    hash: u64,
) -> Result<(&'static [u8], &'static str)> {
    for entry in entries {
        if let EmbeddedEntry::File {
            source_path_hash,
            data,
            compression,
        } = entry
        {
            if *source_path_hash == hash {
                return Ok((data, compression));
            }
        }
    }
    Err(anyhow!(
        "file not embedded in installer (hash: {hash:#018x})"
    ))
}

pub(crate) fn find_dir(
    entries: &'static [EmbeddedEntry],
    hash: u64,
) -> Result<&'static [DirChild]> {
    for entry in entries {
        if let EmbeddedEntry::Dir {
            source_path_hash,
            children,
        } = entry
        {
            if *source_path_hash == hash {
                return Ok(children);
            }
        }
    }
    Err(anyhow!(
        "directory not embedded in installer (hash: {hash:#018x})"
    ))
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn install_children(
    children: &[DirChild],
    dest: &Path,
    rel_prefix: &str,
    installer: &Installer,
    overwrite: OverwriteMode,
    mode: Option<u32>,
    filter: Option<&DirFilterRef>,
    on_error: Option<&DirErrorHandlerRef>,
    weight: u32,
) -> Result<()> {
    for child in children {
        installer.check_cancelled()?;
        let target = dest.join(child.name);
        let rel = if rel_prefix.is_empty() {
            child.name.to_string()
        } else {
            format!("{rel_prefix}/{}", child.name)
        };

        match &child.kind {
            DirChildKind::File { data, compression } => {
                if let Some(f) = filter {
                    if !f(&rel) {
                        continue;
                    }
                }
                let res = installer.run_weighted_step(weight, || {
                    install_one_file(data, compression, &target, overwrite, mode)
                });
                if let Err(e) = res {
                    match on_error {
                        Some(h) => match h(&rel, &e) {
                            ErrorAction::Skip => continue,
                            ErrorAction::Abort => return Err(e),
                        },
                        None => return Err(e),
                    }
                }
            }
            DirChildKind::Dir { children } => {
                std::fs::create_dir_all(&target)
                    .with_context(|| format!("failed to create dir: {}", target.display()))?;
                install_children(
                    children, &target, &rel, installer, overwrite, mode, filter, on_error, weight,
                )?;
            }
        }
    }
    Ok(())
}

fn install_one_file(
    data: &[u8],
    compression: &str,
    dest: &Path,
    overwrite: OverwriteMode,
    mode: Option<u32>,
) -> Result<()> {
    if apply_overwrite_policy(dest, overwrite)? {
        return Ok(());
    }
    let bytes = Installer::decompress(data, compression)?;
    write_file(dest, &bytes)?;
    apply_mode(dest, mode)?;
    Ok(())
}

/// Apply the chosen [`OverwriteMode`] to `dest`. Returns `Ok(true)` when
/// the caller should skip writing (e.g. Skip mode and the file already
/// exists); `Ok(false)` when the caller should proceed; `Err` for Error
/// mode on an existing file or when a backup operation fails.
pub(crate) fn apply_overwrite_policy(dest: &Path, overwrite: OverwriteMode) -> Result<bool> {
    match overwrite {
        OverwriteMode::Overwrite => Ok(false),
        OverwriteMode::Skip => Ok(dest.exists()),
        OverwriteMode::Error => {
            if dest.exists() {
                Err(anyhow!("destination already exists: {}", dest.display()))
            } else {
                Ok(false)
            }
        }
        OverwriteMode::Backup => {
            if dest.exists() {
                backup_path(dest)?;
            }
            Ok(false)
        }
    }
}

pub(crate) fn backup_path(path: &Path) -> Result<()> {
    let backup = path.with_extension(match path.extension() {
        Some(ext) => format!("{}.bak", ext.to_string_lossy()),
        None => "bak".to_string(),
    });
    if backup.exists() {
        if backup.is_dir() {
            std::fs::remove_dir_all(&backup)
                .with_context(|| format!("failed to remove old backup: {}", backup.display()))?;
        } else {
            std::fs::remove_file(&backup)
                .with_context(|| format!("failed to remove old backup: {}", backup.display()))?;
        }
    }
    std::fs::rename(path, &backup)
        .with_context(|| format!("failed to back up: {}", path.display()))?;
    Ok(())
}

#[cfg(unix)]
pub(crate) fn apply_mode(path: &Path, mode: Option<u32>) -> Result<()> {
    if let Some(m) = mode {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(m))
            .with_context(|| format!("failed to set permissions on: {}", path.display()))?;
    }
    Ok(())
}

#[cfg(not(unix))]
pub(crate) fn apply_mode(_path: &Path, _mode: Option<u32>) -> Result<()> {
    Ok(())
}

pub(crate) fn write_file(dest: &Path, data: &[u8]) -> Result<()> {
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create parent dir for: {}", dest.display()))?;
    }
    std::fs::write(dest, data).with_context(|| format!("failed to write: {}", dest.display()))
}