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
mod application;
mod constants;
mod error;
mod sysexits;

use crate::application::{Application, config_file, init_config};
use anyhow::{Result, bail};
use clap::{Parser, Subcommand, ValueEnum};
use error::HbackupError;
use hbackup::job::{BackupModel, CompressFormat, Job, Level, display_jobs, run_job, run_jobs};
use std::io::{self, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::process;

/// Entry point for the hbackup CLI application.
/// Parses command-line arguments and dispatches to the appropriate command handler.
#[tokio::main]
async fn main() -> Result<()> {
    let subcommand = Opt::parse().subcommand.unwrap_or_else(|| {
        eprintln!("bk requires at least one command to execute. See 'bk --help' for usage.");
        process::exit(sysexits::EX_KEYWORD);
    });

    init_config();

    match subcommand {
        Command::Add {
            source,
            target,
            compression,
            level,
            ignore,
            model,
        } => {
            add(source, target, compression, level, ignore, model)?;
        }
        Command::Run {
            source,
            target,
            compression,
            id,
            level,
            ignore,
            model,
        } => {
            match (id, source, target) {
                (Some(ids), _, _) => {
                    run_by_id(ids);
                }
                (_, Some(source), Some(target)) => {
                    let source = canonicalize(source)?;
                    let target = canonicalize(target)?;
                    if compression.is_some() && model == Some(BackupModel::Mirror) {
                        bail!(HbackupError::InvalidCompressionForMirror);
                    }

                    // The temporary job id is set to 0
                    let job = Job::temp_job(source, target, compression, level, ignore, model);
                    run_job(&job)?;
                }
                _ => run()?,
            }
        }
        Command::List { id, gte, lte } => {
            let jobs = if let Some(ids) = id {
                Application::list_by_ids(ids)
            } else if let Some(gte) = gte {
                Application::list_by_gte(gte)
            } else if let Some(lte) = lte {
                Application::list_by_lte(lte)
            } else {
                Application::get_jobs()
            };
            println!("{}", display_jobs(jobs));
        }
        Command::Delete { id, all, yes } => {
            delete(id, all, yes)?;
        }
        Command::Edit {
            id,
            source,
            target,
            compression,
            level,
            ignore,
            clear,
            model,
            swap,
        } => {
            let edit_params = EditParams {
                id,
                source,
                target,
                compression,
                level,
                ignore,
                clear,
                model,
                swap,
            };
            edit(edit_params)?;
        }
        Command::Config => {
            println!("   {}", config_file().display());
        }
    }
    Ok(())
}

/// Command-line interface definition for hbackup.
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Opt {
    /// Subcommand to execute.
    #[command(subcommand)]
    pub subcommand: Option<Command>,
}

/// Supported hbackup commands.
#[derive(Subcommand, Debug)]
enum Command {
    /// Add a new backup job to the configuration.
    Add {
        /// Source file or directory path.
        source: PathBuf,
        /// Target file or directory path.
        target: PathBuf,
        /// Compression format.
        #[arg(short, long)]
        compression: Option<CompressFormat>,
        #[arg(short, long, requires = "compression")]
        level: Option<Level>,
        /// Ignore a specific list of files or directories
        #[arg(short = 'g', long, value_delimiter = ',')]
        ignore: Option<Vec<String>>,
        /// Backup model
        #[arg(short, long, required = false)]
        model: Option<BackupModel>,
    },
    /// Run backup jobs.
    Run {
        /// Source file or directory path (positional, optional). Must be used with target.
        #[arg(required = false, requires = "target")]
        source: Option<PathBuf>,
        /// Target file or directory path (positional, optional). Must be used with source.
        #[arg(required = false, requires = "source")]
        target: Option<PathBuf>,
        /// Compression format.
        #[arg(short, long, required = false)]
        compression: Option<CompressFormat>,
        /// Compression level
        #[arg(short, long, required = false, requires = "compression")]
        level: Option<Level>,
        /// Job id(s) to run.
        #[arg(short, long, required = false, value_delimiter = ',', conflicts_with_all = ["source", "target", "compression"])]
        id: Option<Vec<u32>>,
        /// Ignore a specific list of files or directories
        #[arg(short = 'g', long, value_delimiter = ',')]
        ignore: Option<Vec<String>>,
        /// Backup model
        #[arg(short, long, required = false)]
        model: Option<BackupModel>,
    },
    /// List all backup jobs.
    List {
        /// List jobs by ids.
        #[arg(short, long, required = false, value_delimiter = ',', conflicts_with_all = ["gte", "lte"])]
        id: Option<Vec<u32>>,
        /// List jobs by id greater than or equal to.
        #[arg(short = 'g', long, required = false, conflicts_with_all = ["id", "lte"])]
        gte: Option<u32>,
        /// List jobs by id less than or equal to.
        #[arg(short = 'l', long, required = false, conflicts_with_all = ["id", "gte"])]
        lte: Option<u32>,
    },
    /// Delete backup jobs by id or delete all jobs.
    Delete {
        /// Delete multiple jobs by ids. Cannot be used with --all.
        #[arg(value_delimiter = ',', conflicts_with = "all")]
        id: Option<Vec<u32>>,
        /// Delete all jobs. Cannot be used with --id.
        #[arg(short, long, conflicts_with = "id")]
        all: bool,
        /// Skip interactive confirmation when deleting all jobs
        #[arg(short = 'y', long, conflicts_with = "id")]
        yes: bool,
    },
    /// Edit a backup job by id. At least one of source/target/compression/level/ignore/clear must be provided.
    Edit {
        /// Edit job by id.
        id: u32,
        /// New source file or directory path
        #[arg(short, long, required_unless_present_any = ["target", "compression", "level", "ignore", "model", "clear", "swap"])]
        source: Option<PathBuf>,
        /// New target file or directory path
        #[arg(short, long, required_unless_present_any = ["source", "compression", "level", "ignore", "model", "clear", "swap"])]
        target: Option<PathBuf>,
        /// Compression format
        #[arg(short, long, required_unless_present_any = ["source", "target", "level", "ignore", "model", "clear", "swap"])]
        compression: Option<CompressFormat>,
        /// Compression level
        #[arg(short, long, required_unless_present_any = ["source", "target", "compression", "ignore", "model", "clear", "swap"])]
        level: Option<Level>,
        /// Ignore a specific list of files or directories
        #[arg(short = 'g', long, value_delimiter = ',', required_unless_present_any = ["source", "target", "compression", "level", "model", "clear", "swap"])]
        ignore: Option<Vec<String>>,
        /// Backup model
        #[arg(short, long, required_unless_present_any = ["source", "target", "compression", "level", "ignore", "clear", "swap"])]
        model: Option<BackupModel>,
        /// Clear specified fields (comma-separated: compression,level,ignore)
        #[arg(long, value_delimiter = ',', required_unless_present_any = ["source", "target", "compression", "level", "ignore", "model", "swap"])]
        clear: Option<Vec<ClearField>>,
        /// Swap source and target paths(only supports file-to-file swap)
        #[arg(long, conflicts_with_all = ["source", "target"], required_unless_present_any = ["source", "target", "compression", "level", "ignore", "model", "clear"])]
        swap: bool,
    },
    /// Display the absolute path of the configuration file and manage config backup/reset/rollback.
    Config,
}

/// Fields that can be cleared in the edit command
#[derive(Debug, Clone, ValueEnum)]
enum ClearField {
    /// Clear compression format
    Compression,
    /// Clear compression level
    Level,
    /// Clear ignore list
    Ignore,
    /// Clear backup model
    Model,
}

/// Parameters for editing a backup job
struct EditParams {
    pub id: u32,
    pub source: Option<PathBuf>,
    pub target: Option<PathBuf>,
    pub compression: Option<CompressFormat>,
    pub level: Option<Level>,
    pub ignore: Option<Vec<String>>,
    pub clear: Option<Vec<ClearField>>,
    pub model: Option<BackupModel>,
    pub swap: bool,
}

/// Adds a new backup job to the configuration file.
fn add(
    source: PathBuf,
    target: PathBuf,
    comp: Option<CompressFormat>,
    level: Option<Level>,
    ignore: Option<Vec<String>>,
    model: Option<BackupModel>,
) -> Result<()> {
    let source = canonicalize(source)?;
    let target = canonicalize(target)?;
    if comp.is_some() && model == Some(BackupModel::Mirror) {
        return Err(HbackupError::InvalidCompressionForMirror.into());
    }

    let mut app = Application::load_config();
    app.add_job(source, target, comp, level, ignore, model)?;
    app.write()?;

    Ok(())
}

/// Runs all backup jobs defined in the configuration.
fn run() -> Result<()> {
    let jobs = Application::get_jobs();
    if jobs.is_empty() {
        println!("No jobs are backed up!");
    } else if jobs.len() == 1 {
        run_job(&jobs[0])?;
    } else {
        run_jobs(jobs)?;
    }
    Ok(())
}

/// Runs a backup job by its id.
fn run_by_id(ids: Vec<u32>) {
    let jobs = Application::get_jobs();
    if jobs.is_empty() {
        println!("No jobs are backed up!");
        return;
    }
    let mut vec = vec![];
    for id in ids {
        match jobs.iter().find(|j| j.id == id) {
            Some(job) => {
                vec.push(job.clone());
            }
            None => {
                eprintln!("Job with id {id} not found.");
            }
        }
    }
    if vec.is_empty() {
        process::exit(1);
    } else if vec.len() == 1 {
        if let Err(e) = run_job(&vec[0]) {
            eprintln!("Failed to run job with id {}: {e}\n", vec[0].id);
            process::exit(sysexits::EX_IOERR);
        }
    } else if let Err(e) = run_jobs(vec) {
        eprintln!("Failed to run jobs: {e}\n");
        process::exit(sysexits::EX_IOERR);
    }
}

/// Deletes a job by id or deletes all jobs.
fn delete(id: Option<Vec<u32>>, all: bool, yes: bool) -> Result<()> {
    if all {
        let mut app = Application::load_config();
        if app.jobs.is_empty() {
            println!("No jobs to delete");
            return Ok(());
        }
        if yes {
            app.reset_jobs();
            app.write()?;
            println!("All jobs deleted successfully.");
            return Ok(());
        }
        loop {
            print!("Are you sure you want to delete all jobs? (y/n): ");
            io::stdout().flush()?;
            let mut input = String::new();
            io::stdin().read_line(&mut input)?;
            if input.trim().to_lowercase() == "n" {
                return Ok(());
            } else if input.trim().to_lowercase() == "y" {
                app.reset_jobs();
                app.write()?;
                println!("All jobs deleted successfully.");
                return Ok(());
            } else {
                println!("\nInvalid input. Please enter 'y' or 'n'.");
            }
        }
    } else if let Some(ids) = id {
        let mut app = Application::load_config();
        let mut msg = String::new();
        ids.into_iter().for_each(|id| match app.remove_job(id) {
            Some(_) => msg.push_str(&format!("Job with id {id} deleted successfully.\n")),
            None => msg.push_str(&format!(
                "Job deletion failed. Job with id {id} cannot be found.\n"
            )),
        });
        app.write()?;
        msg.remove(msg.len() - 1);
        println!("{}", msg);
    } else {
        bail!("Either --all or --id must be specified.");
    }
    Ok(())
}

/// Edits a job by id, updating its source, target, and/or compression settings.
fn edit(params: EditParams) -> Result<()> {
    let EditParams {
        id,
        source,
        target,
        compression,
        level,
        ignore,
        model,
        clear,
        swap,
    } = params;
    let source = source.map(canonicalize);
    let target = target.map(canonicalize);
    if compression.is_some() && model == Some(BackupModel::Mirror) {
        bail!(HbackupError::InvalidCompressionForMirror);
    }

    let mut app = Application::load_config();
    if app.jobs.is_empty() {
        println!("Job with id {id} not found.");
        return Ok(());
    }
    if let Some(job) = app.jobs.iter_mut().find(|j| j.id == id) {
        if let Some(path) = source {
            job.source = path?;
        }
        if let Some(path) = target {
            job.target = path?;
        }
        // Handle clear operations first
        if let Some(clear_fields) = &clear {
            for field in clear_fields {
                match field {
                    ClearField::Compression => {
                        job.compression = None;
                        job.level = None; // Clear level when clearing compression
                    }
                    ClearField::Level => {
                        job.level = None;
                    }
                    ClearField::Ignore => {
                        job.ignore = None;
                    }
                    ClearField::Model => {
                        job.model = None;
                    }
                }
            }
        }
        // Handle set operations
        if let Some(comp) = compression {
            job.compression = Some(comp);
        }
        if let Some(lvl) = level {
            if job.compression.is_none() {
                bail!(
                    "The compression format is not set, and the compression level cannot be updated."
                );
            }
            job.level = Some(lvl);
        }
        if let Some(ign) = ignore {
            job.ignore = Some(ign);
        }
        if let Some(model) = model {
            job.model = Some(model)
        }

        if job.compression.is_some() && job.model == Some(BackupModel::Mirror) {
            bail!(HbackupError::InvalidCompressionForMirror);
        }

        if swap {
            if !job.target.exists() {
                bail!(
                    "Cannot swap source and target paths for job id {id} because target path does not exist.\ntarget path: {:?}",
                    job.target
                );
            } else if !(job.target.is_file() && job.source.is_file()) {
                // only support: file-to-file swap for now
                bail!(
                    "Cannot swap source and target paths for job id {id} because both source and target paths must be files.\nsource path: {:?}\ntarget path: {:?}",
                    job.source,
                    job.target
                );
            }
            std::mem::swap(&mut job.source, &mut job.target);
        }

        app.write()?;
        println!("Job with id {id} edited successfully.");
    } else {
        println!("Job with id {id} not found.");
    }
    Ok(())
}

/// Returns the canonical, absolute form of the path with all intermediate
/// components normalized and symbolic links resolved.
fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
    let path = path.as_ref();
    match path.canonicalize() {
        Ok(p) => Ok(p),
        Err(e) => match e.kind() {
            ErrorKind::NotFound => Err(HbackupError::PathNotFound(path.to_path_buf()).into()),
            ErrorKind::PermissionDenied => {
                Err(HbackupError::PermissionDenied(path.to_path_buf()).into())
            }
            _ => Err(e.into()),
        },
    }
}