qbak 1.5.1

A single-command backup helper for Linux and POSIX systems
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use clap::{Arg, ArgAction, Command};
use qbak::{backup_file, dump_config, load_config, QbakError};
use std::path::Path;
use std::process;

fn main() {
    let result = run();
    match result {
        Ok(exit_code) => process::exit(exit_code),
        Err(error) => {
            eprintln!("Error: {error}");

            // Show suggestions if available
            let suggestions = error.suggestions();
            if !suggestions.is_empty() {
                eprintln!("\nSuggestions:");
                for suggestion in suggestions {
                    eprintln!("  - {suggestion}");
                }
            }

            // If this was an interrupted operation, clean up partial backups before exit
            if matches!(error, QbakError::Interrupted) {
                qbak::signal::cleanup_active_operations();

                // Also clean up any temporary files
                if let Ok(current_dir) = std::env::current_dir() {
                    let _ = qbak::backup::cleanup_temp_files(&current_dir);
                }
            }

            process::exit(error.exit_code());
        }
    }
}

fn run() -> Result<i32, QbakError> {
    let matches = Command::new("qbak")
        .version(env!("CARGO_PKG_VERSION"))
        .author("Andreas Glaser <andreas.glaser@pm.me>")
        .about("A single-command backup helper for Linux and POSIX systems")
        .long_about(
            "qbak creates timestamped backup copies of files and directories.\n\
             Example: qbak example.txt → example-20250603T145231-qbak.txt",
        )
        .arg(
            Arg::new("targets")
                .help("Files or directories to back up")
                .required(false)
                .num_args(1..)
                .value_name("TARGET"),
        )
        .arg(
            Arg::new("dry-run")
                .short('n')
                .long("dry-run")
                .help("Show what would be backed up without doing it")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .help("Show detailed progress information")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("quiet")
                .short('q')
                .long("quiet")
                .help("Suppress all output except errors")
                .action(ArgAction::SetTrue)
                .conflicts_with_all(["verbose", "progress"]),
        )
        .arg(
            Arg::new("progress")
                .long("progress")
                .help("Force progress indication even for small operations")
                .action(ArgAction::SetTrue)
                .conflicts_with("no-progress"),
        )
        .arg(
            Arg::new("no-progress")
                .long("no-progress")
                .help("Disable progress indication completely")
                .action(ArgAction::SetTrue)
                .conflicts_with("progress"),
        )
        .arg(
            Arg::new("dump-config")
                .long("dump-config")
                .help("Display current configuration settings and exit")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    // Parse command line flags
    let dump_config_flag = matches.get_flag("dump-config");
    let dry_run = matches.get_flag("dry-run");
    let verbose = matches.get_flag("verbose");
    let quiet = matches.get_flag("quiet");
    let force_progress = matches.get_flag("progress");
    let no_progress = matches.get_flag("no-progress");

    // Load configuration
    let mut config = load_config()
        .map_err(|e| {
            if verbose {
                eprintln!("Warning: Could not load config, using defaults: {e}");
            }
            e
        })
        .unwrap_or_else(|_| qbak::default_config());

    // Apply command line progress flags (they override config)
    if quiet || no_progress {
        config.progress.enabled = false;
    } else if force_progress {
        config.progress.force_enabled = true;
    }

    // Handle dump-config flag early
    if dump_config_flag {
        dump_config(&config)?;
        return Ok(0);
    }

    // Parse targets (only needed if not dumping config)
    let targets: Vec<&str> = if let Some(target_values) = matches.get_many::<String>("targets") {
        target_values.map(|s| s.as_str()).collect()
    } else {
        return Err(QbakError::validation(
            "No targets specified. Use --help for usage information.",
        ));
    };

    // Set up signal handling for graceful cleanup
    setup_signal_handlers();

    let mut success_count = 0;
    let mut error_count = 0;

    // Process each target
    for target_str in targets {
        let target_path = Path::new(target_str);

        match process_target(
            target_path,
            &config,
            dry_run,
            verbose,
            quiet,
            force_progress,
        ) {
            Ok(_) => success_count += 1,
            Err(e) => {
                error_count += 1;

                if e.is_recoverable() {
                    // For recoverable errors, show error but continue
                    if !quiet {
                        eprintln!("Error processing {target_str}: {e}");

                        let suggestions = e.suggestions();
                        if !suggestions.is_empty() && verbose {
                            eprintln!("Suggestions:");
                            for suggestion in suggestions {
                                eprintln!("  - {suggestion}");
                            }
                        }
                    }
                } else {
                    // For non-recoverable errors, fail immediately
                    return Err(e);
                }
            }
        }
    }

    // Summary
    if !quiet && (success_count > 1 || error_count > 0) {
        println!("Backup summary: {success_count} succeeded, {error_count} failed");
    }

    // Return appropriate exit code
    if error_count > 0 {
        Ok(1) // Any failures
    } else {
        Ok(0) // All succeeded
    }
}

fn process_target(
    target: &Path,
    config: &qbak::Config,
    dry_run: bool,
    verbose: bool,
    quiet: bool,
    force_progress: bool,
) -> Result<(), QbakError> {
    if dry_run {
        // Dry run mode - just show what would be done
        let backup_path = qbak::generate_backup_name(target, config)?;
        let final_path = qbak::resolve_collision(&backup_path)?;

        if target.is_dir() {
            // For directories, potentially show scanning progress in dry run
            let should_show_progress =
                config.progress.should_show_progress(0, 0, force_progress) && !quiet;
            let (file_count, total_size) = if should_show_progress {
                qbak::count_files_and_size_with_progress(target, config)?
            } else {
                qbak::count_files_and_size(target, config)?
            };
            let size_str = qbak::utils::format_size(total_size);
            println!(
                "Would create backup: {} ({} files, {size_str})",
                final_path.display(),
                file_count
            );
        } else {
            let size = qbak::calculate_size(target)?;
            let size_str = qbak::utils::format_size(size);
            println!("Would create backup: {} ({size_str})", final_path.display());
        }
        return Ok(());
    }

    // Perform the actual backup
    let result = if target.is_dir() {
        qbak::backup_directory_with_progress(target, config, force_progress || verbose, quiet)?
    } else {
        backup_file(target, config)?
    };

    // Output results based on verbosity
    if verbose {
        println!("Processed: {}", target.display());
        println!("{}", result.backup_path.display());
        let files = result.files_processed;
        let size_str = qbak::utils::format_size(result.total_size);
        let duration = result.duration.as_secs_f64();
        println!("  Files: {files}");
        println!("  Size: {size_str}");
        println!("  Duration: {duration:.2}s");
    } else if !quiet {
        let summary = result.summary();
        println!("{summary}");
    }

    Ok(())
}

fn setup_signal_handlers() {
    // Set up signal handlers for graceful cleanup
    #[cfg(unix)]
    {
        use std::sync::atomic::Ordering;

        // Create a new backup context for this qbak instance
        let context = qbak::signal::BackupContext::new();
        let interrupt_flag = context.interrupt_flag();

        ctrlc::set_handler(move || {
            interrupt_flag.store(true, Ordering::SeqCst);
            eprintln!("\nInterrupted by user.");
        })
        .expect("Error setting Ctrl-C handler");

        // Set the global context for this qbak instance
        qbak::signal::set_global_context(context);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use tempfile::tempdir;

    #[test]
    fn test_process_target_file() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");
        File::create(&source_path).unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_dry_run() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");
        File::create(&source_path).unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, true, false, false, false);
        assert!(result.is_ok());

        // In dry run mode, no backup should be created
        let backup_path = qbak::generate_backup_name(&source_path, &config).unwrap();
        assert!(!backup_path.exists());
    }

    #[test]
    fn test_process_target_nonexistent() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("nonexistent.txt");

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);

        assert!(result.is_err());
        match result.unwrap_err() {
            QbakError::SourceNotFound { .. } => (),
            _ => panic!("Expected SourceNotFound error"),
        }
    }

    #[test]
    fn test_process_target_directory() {
        let dir = tempdir().unwrap();
        let source_dir = dir.path().join("test_dir");
        std::fs::create_dir_all(&source_dir).unwrap();

        // Add a file to the directory
        std::fs::write(source_dir.join("file.txt"), "content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_dir, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_verbose_mode() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");

        let mut file = File::create(&source_path).unwrap();
        writeln!(file, "Test content").unwrap();

        let config = qbak::default_config();
        // Test verbose mode (should not panic or error)
        let result = process_target(&source_path, &config, false, true, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_dry_run_directory() {
        let dir = tempdir().unwrap();
        let source_dir = dir.path().join("test_dir");
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(source_dir.join("file.txt"), "content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_dir, &config, true, false, false, false);
        assert!(result.is_ok());

        // Verify no backup was actually created
        let backup_path = qbak::generate_backup_name(&source_dir, &config).unwrap();
        assert!(!backup_path.exists());
    }

    #[test]
    fn test_process_target_quiet_mode() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");
        File::create(&source_path).unwrap();

        let config = qbak::default_config();
        // Test quiet mode
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_with_different_config() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");
        std::fs::write(&source_path, "test content").unwrap();

        let mut config = qbak::default_config();
        config.backup_suffix = "custom".to_string();
        config.preserve_permissions = false;

        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_large_file() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("large.txt");

        // Create a larger file
        let content = "x".repeat(50000);
        std::fs::write(&source_path, content).unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, true, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_empty_file() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("empty.txt");
        File::create(&source_path).unwrap(); // Creates empty file

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_special_characters_in_path() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("file with spaces.txt");
        std::fs::write(&source_path, "content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_unicode_filename() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("тест.txt"); // Cyrillic filename
        std::fs::write(&source_path, "unicode content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_no_extension() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("README");
        std::fs::write(&source_path, "readme content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_multiple_extensions() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("archive.tar.gz");
        std::fs::write(&source_path, "archive content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_hidden_file() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join(".hidden");
        std::fs::write(&source_path, "hidden content").unwrap();

        let config = qbak::default_config();
        let result = process_target(&source_path, &config, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_target_dry_run_verbose() {
        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");
        std::fs::write(&source_path, "content").unwrap();

        let config = qbak::default_config();
        // Test dry run with verbose output
        let result = process_target(&source_path, &config, true, true, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_signal_handler_cleanup_integration() {
        use qbak::signal::get_active_operations;

        let dir = tempdir().unwrap();
        let source_path = dir.path().join("test.txt");
        std::fs::write(&source_path, "test content").unwrap();

        let config = qbak::default_config();
        let backup_path = qbak::generate_backup_name(&source_path, &config).unwrap();
        let final_backup_path = qbak::resolve_collision(&backup_path).unwrap();

        // Simulate the exact sequence that happens during a real backup interruption
        {
            // This mimics what backup_file() does at the start
            let _guard = qbak::signal::create_backup_guard(final_backup_path.clone());

            // Simulate partial progress
            std::fs::copy(&source_path, &final_backup_path).unwrap();

            // Verify operation is tracked
            let active_ops = get_active_operations();
            assert!(active_ops.contains(&final_backup_path));
            assert!(final_backup_path.exists());

            // Simulate CTRL+C signal handler being called
            qbak::signal::cleanup_active_operations();

            // Verify cleanup happened
            assert!(!final_backup_path.exists());
            let remaining_ops = get_active_operations();
            assert!(remaining_ops.is_empty());

            // Guard will drop here, but cleanup already happened
        }

        // Verify final state - no partial backup should remain
        assert!(!final_backup_path.exists());
    }

    #[test]
    fn test_multiple_targets_with_interruption_simulation() {
        let dir = tempdir().unwrap();

        // Create multiple source files
        let source1 = dir.path().join("file1.txt");
        let source2 = dir.path().join("file2.txt");
        std::fs::write(&source1, "content1").unwrap();
        std::fs::write(&source2, "content2").unwrap();

        let config = qbak::default_config();

        // Generate backup paths
        let backup1 =
            qbak::resolve_collision(&qbak::generate_backup_name(&source1, &config).unwrap())
                .unwrap();
        let backup2 =
            qbak::resolve_collision(&qbak::generate_backup_name(&source2, &config).unwrap())
                .unwrap();

        // Simulate multiple concurrent backup operations being interrupted
        {
            let _guard1 = qbak::signal::create_backup_guard(backup1.clone());
            let _guard2 = qbak::signal::create_backup_guard(backup2.clone());

            // Start both operations
            std::fs::copy(&source1, &backup1).unwrap();
            std::fs::copy(&source2, &backup2).unwrap();

            // Verify both exist and are tracked
            assert!(backup1.exists());
            assert!(backup2.exists());

            // Simulate signal handler cleanup (CTRL+C)
            qbak::signal::cleanup_active_operations();

            // Both should be cleaned up
            assert!(!backup1.exists());
            assert!(!backup2.exists());
        }
    }
}