hbackup 0.5.6

hbackup is a sample, high-performance, cross-platform backup tool written in Rust. It is designed to be fast, efficient, and easy to use, with a focus on performance and reliability.
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
use crate::file_util;
use crate::item::{execute_item, execute_item_async, get_item, get_items};
use anyhow::{Result, bail};
use clap::ValueEnum;
use futures::{StreamExt, stream::FuturesUnordered};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::runtime::Builder as runtimeBuilder;

/// Represents a single backup job with a unique id, source, target, and optional compression.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Job {
    /// Unique job id.
    pub id: u32,
    /// Source file or directory path.
    pub source: PathBuf,
    /// Target file or directory path.
    pub target: PathBuf,
    /// Optional compression format for this job.
    pub compression: Option<CompressFormat>,
    /// Optional compression level for this job.
    pub level: Option<Level>,
    /// Optional ignore list
    pub ignore: Option<Vec<String>>,
    /// Backup model
    pub model: Option<BackupModel>,
}

/// Supported compression formats for backup jobs.
#[derive(ValueEnum, Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum CompressFormat {
    Gzip,
    Zip,
    Sevenz,
    Zstd,
    Bzip2,
    Xz,
    Lz4,
    Tar,
}

/// Supported compression level for backup jobs
#[derive(ValueEnum, Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Level {
    Fastest,
    Faster,
    Default,
    Better,
    Best,
}

#[derive(ValueEnum, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
pub enum BackupModel {
    #[default]
    Full,
    Mirror,
}

impl Job {
    pub fn temp_job(
        source: PathBuf,
        target: PathBuf,
        compression: Option<CompressFormat>,
        level: Option<Level>,
        ignore: Option<Vec<String>>,
        model: Option<BackupModel>,
    ) -> Job {
        Job {
            id: 0,
            source,
            target,
            compression,
            level,
            ignore,
            model,
        }
    }
}

pub fn display_jobs(jobs: Vec<Job>) -> String {
    if jobs.is_empty() {
        return String::new();
    }
    let mut s = String::from('[');
    for job in jobs {
        let comp = match job.compression {
            Some(CompressFormat::Gzip) => "Gzip",
            Some(CompressFormat::Zip) => "Zip",
            Some(CompressFormat::Sevenz) => "Sevenz",
            Some(CompressFormat::Zstd) => "Zstd",
            Some(CompressFormat::Bzip2) => "Bzip2",
            Some(CompressFormat::Xz) => "Xz",
            Some(CompressFormat::Lz4) => "Lz4",
            Some(CompressFormat::Tar) => "Tar",
            None => "",
        };
        let level = match job.level {
            Some(Level::Fastest) => "Fastest",
            Some(Level::Faster) => "Faster",
            Some(Level::Default) => "Default",
            Some(Level::Better) => "Better",
            Some(Level::Best) => "Best",
            None => "",
        };
        let model = match job.model {
            Some(BackupModel::Full) => "Full",
            Some(BackupModel::Mirror) => "Mirror",
            None => "",
        };
        s.push_str(&format!(
            "{{\n    id: {},\n    source: \"{}\",\n    target: \"{}\"",
            job.id,
            job.source.display(),
            job.target.display()
        ));
        if !comp.is_empty() {
            s.push_str(&format!(",\n    compression: \"{comp}\""));
        }
        if !level.is_empty() {
            s.push_str(&format!(",\n    level: \"{level}\""));
        }
        if let Some(ignore) = &job.ignore {
            s.push_str(&format!(",\n    ignore: {ignore:?}"));
        }
        if !model.is_empty() {
            s.push_str(&format!(",\n    model: \"{model}\""));
        }
        s.push_str("\n},");
    }
    s.pop();
    s.push(']');
    s
}

/// Runs a backup job (single file or directory copy, with optional compression).
pub fn run_job(job: &Job) -> Result<()> {
    if let Some(ref format) = job.compression {
        let level = job.level.as_ref().unwrap_or(&Level::Default);
        file_util::compression(
            &job.source,
            &job.target,
            format,
            level,
            job.ignore.as_deref(),
        )?;
    } else if job.source.is_dir() {
        let target = &job.target;
        if target.exists() && target.is_file() {
            bail!(
                "The file {target:?} already exists and a directory with the same name cannot be created."
            );
        }

        let items = get_items(job.clone())?;
        let rt = runtimeBuilder::new_multi_thread().enable_all().build()?;
        rt.block_on(async {
            let mut tasks = FuturesUnordered::new();
            for item in items {
                tasks.push(execute_item_async(item));
            }
            while let Some(res) = tasks.next().await {
                res?;
            }
            Ok::<(), anyhow::Error>(())
        })?;
    } else if let Some(item) = get_item(job.clone())? {
        execute_item(item)?;
    }
    Ok(())
}

/// Runs multiple backup jobs concurrently.
pub fn run_jobs(jobs: Vec<Job>) -> Result<()> {
    let rt = runtimeBuilder::new_multi_thread().enable_all().build()?;

    rt.block_on(async move {
        let mut set = tokio::task::JoinSet::new();
        for job in jobs {
            set.spawn(async move {
                if let Err(e) = run_job_async(&job).await {
                    eprintln!("Failed to run job with id {}: {}\n", job.id, e);
                }
            });
        }
        while let Some(res) = set.join_next().await {
            if let Err(e) = res {
                eprintln!("Failed to run job: {e}\n");
            }
        }
    });

    Ok(())
}

/// Runs a backup job (single file or directory copy, with optional compression).
async fn run_job_async(job: &Job) -> Result<()> {
    if let Some(ref format) = job.compression {
        let level = job.level.as_ref().unwrap_or(&Level::Default);
        let src = job.source.clone();
        let tgt = job.target.clone();
        let fmt = format.clone();
        let lvl = level.clone();
        let ignore = job.ignore.clone();
        tokio::task::spawn_blocking(move || {
            file_util::compression(&src, &tgt, &fmt, &lvl, ignore.as_deref())
        })
        .await??;
    } else if job.source.is_dir() {
        let target = &job.target;
        if target.exists() && target.is_file() {
            bail!(
                "The file {target:?} already exists and a directory with the same name cannot be created."
            );
        }
        let items = get_items(job.clone())?;
        let mut tasks = FuturesUnordered::new();
        for item in items {
            tasks.push(execute_item_async(item));
        }
        while let Some(res) = tasks.next().await {
            res?;
        }
    } else if let Some(item) = get_item(job.clone())? {
        execute_item_async(item).await?;
    }
    Ok(())
}

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

    #[test]
    fn test_job_list_display() {
        let jobs = vec![
            Job {
                id: 1,
                source: PathBuf::from("/test/source1"),
                target: PathBuf::from("/test/target1"),
                compression: Some(CompressFormat::Zip),
                level: Some(Level::Fastest),
                ignore: None,
                model: None,
            },
            Job {
                id: 2,
                source: PathBuf::from("/test/source2"),
                target: PathBuf::from("/test/target2"),
                compression: Some(CompressFormat::Zstd),
                level: Some(Level::Best),
                ignore: Some(vec!["*.tmp".to_string()]),
                model: None,
            },
        ];

        let display_str = display_jobs(jobs);

        assert!(display_str.starts_with('['));
        assert!(display_str.ends_with(']'));
        assert!(display_str.contains("id: 1"));
        assert!(display_str.contains("id: 2"));
        assert!(display_str.contains("Zip"));
        assert!(display_str.contains("Zstd"));
    }

    #[test]
    fn test_empty_job_list_display() {
        let jobs = vec![];
        let display_str = display_jobs(jobs);
        assert_eq!(display_str, "");
    }

    #[test]
    fn test_job_display_with_all_compression_formats() {
        let formats = [
            CompressFormat::Gzip,
            CompressFormat::Zip,
            CompressFormat::Sevenz,
            CompressFormat::Zstd,
            CompressFormat::Bzip2,
            CompressFormat::Xz,
            CompressFormat::Lz4,
            CompressFormat::Tar,
        ];

        for (i, format) in formats.iter().enumerate() {
            let job = Job {
                id: (i + 1) as u32,
                source: PathBuf::from("/test/source"),
                target: PathBuf::from("/test/target"),
                compression: Some(format.clone()),
                level: Some(Level::Default),
                ignore: None,
                model: None,
            };

            let display_str = display_jobs(vec![job]);
            assert!(display_str.contains(&format!("{:?}", format)));
        }
    }

    #[test]
    fn test_job_display_with_all_compression_levels() {
        let levels = [
            Level::Fastest,
            Level::Faster,
            Level::Default,
            Level::Better,
            Level::Best,
        ];

        for (i, level) in levels.iter().enumerate() {
            let job = Job {
                id: (i + 1) as u32,
                source: PathBuf::from("/test/source"),
                target: PathBuf::from("/test/target"),
                compression: Some(CompressFormat::Gzip),
                level: Some(level.clone()),
                ignore: None,
                model: None,
            };

            let display_str = display_jobs(vec![job]);
            assert!(display_str.contains(&format!("{:?}", level)));
        }
    }

    #[test]
    fn test_job_display_with_backup_models() {
        let models = [BackupModel::Full, BackupModel::Mirror];

        for (i, model) in models.iter().enumerate() {
            let job = Job {
                id: (i + 1) as u32,
                source: PathBuf::from("/test/source"),
                target: PathBuf::from("/test/target"),
                compression: None,
                level: None,
                ignore: None,
                model: Some(model.clone()),
            };

            let display_str = display_jobs(vec![job]);
            assert!(display_str.contains(&format!("{:?}", model)));
        }
    }

    #[test]
    fn test_job_display_without_optional_fields() {
        let job = Job {
            id: 1,
            source: PathBuf::from("/test/source"),
            target: PathBuf::from("/test/target"),
            compression: None,
            level: None,
            ignore: None,
            model: None,
        };

        let display_str = display_jobs(vec![job]);

        // Should contain required fields
        assert!(display_str.contains("id: 1"));
        assert!(display_str.contains("source: \"/test/source\""));
        assert!(display_str.contains("target: \"/test/target\""));

        // Should not contain optional fields when they're None
        assert!(!display_str.contains("compression:"));
        assert!(!display_str.contains("level:"));
        assert!(!display_str.contains("ignore:"));
        assert!(!display_str.contains("model:"));
    }

    #[test]
    fn test_job_display_with_ignore_patterns() {
        let job = Job {
            id: 1,
            source: PathBuf::from("/test/source"),
            target: PathBuf::from("/test/target"),
            compression: None,
            level: None,
            ignore: Some(vec![
                "*.log".to_string(),
                "*.tmp".to_string(),
                "cache/".to_string(),
            ]),
            model: None,
        };

        let display_str = display_jobs(vec![job]);

        assert!(display_str.contains("ignore:"));
        assert!(display_str.contains("*.log"));
        assert!(display_str.contains("*.tmp"));
        assert!(display_str.contains("cache/"));
    }

    #[test]
    fn test_temp_job_creation() {
        let source = PathBuf::from("/test/source");
        let target = PathBuf::from("/test/target");
        let compression = Some(CompressFormat::Gzip);
        let level = Some(Level::Best);
        let ignore = Some(vec!["*.log".to_string()]);
        let model = Some(BackupModel::Mirror);

        let job = Job::temp_job(
            source.clone(),
            target.clone(),
            compression.clone(),
            level.clone(),
            ignore.clone(),
            model.clone(),
        );

        assert_eq!(job.id, 0);
        assert_eq!(job.source, source);
        assert_eq!(job.target, target);
        assert_eq!(job.compression, compression);
        assert_eq!(job.level, level);
        assert_eq!(job.ignore, ignore);
        assert_eq!(job.model, model);
    }

    #[test]
    fn test_backup_model_default() {
        let model = BackupModel::default();
        assert_eq!(model, BackupModel::Full);
    }

    #[test]
    fn test_job_serialization() {
        let job = Job {
            id: 42,
            source: PathBuf::from("/home/user/documents"),
            target: PathBuf::from("/backup/documents"),
            compression: Some(CompressFormat::Zstd),
            level: Some(Level::Better),
            ignore: Some(vec!["*.tmp".to_string(), ".DS_Store".to_string()]),
            model: Some(BackupModel::Mirror),
        };

        // Test serialization to TOML
        let toml_str = toml::to_string(&job).expect("Failed to serialize job to TOML");
        assert!(toml_str.contains("id = 42"));
        assert!(toml_str.contains("Zstd"));
        assert!(toml_str.contains("Better"));
        assert!(toml_str.contains("Mirror"));

        // Test deserialization from TOML
        let deserialized: Job =
            toml::from_str(&toml_str).expect("Failed to deserialize job from TOML");
        assert_eq!(deserialized.id, job.id);
        assert_eq!(deserialized.source, job.source);
        assert_eq!(deserialized.target, job.target);
        assert_eq!(deserialized.compression, job.compression);
        assert_eq!(deserialized.level, job.level);
        assert_eq!(deserialized.ignore, job.ignore);
        assert_eq!(deserialized.model, job.model);
    }

    #[test]
    fn test_multiple_jobs_display_formatting() {
        let jobs = vec![
            Job {
                id: 1,
                source: PathBuf::from("/path1"),
                target: PathBuf::from("/target1"),
                compression: Some(CompressFormat::Gzip),
                level: Some(Level::Fastest),
                ignore: None,
                model: Some(BackupModel::Full),
            },
            Job {
                id: 2,
                source: PathBuf::from("/path2"),
                target: PathBuf::from("/target2"),
                compression: None,
                level: None,
                ignore: Some(vec!["*.log".to_string()]),
                model: Some(BackupModel::Mirror),
            },
        ];

        let display_str = display_jobs(jobs);

        // Should start with [ and end with ]
        assert!(display_str.starts_with('['));
        assert!(display_str.ends_with(']'));

        // Should contain both jobs
        assert!(display_str.contains("id: 1"));
        assert!(display_str.contains("id: 2"));

        // Should have proper structure with braces
        let open_braces = display_str.matches('{').count();
        let close_braces = display_str.matches('}').count();
        assert_eq!(open_braces, close_braces);
        assert_eq!(open_braces, 2); // One for each job
    }
}