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
//! Global configuration for this application.
//!
//! This module defines the core data structures and logic for managing
//! hbackup's persistent configuration, including backup jobs, compression formats,
//! and config file management. It provides serialization/deserialization for TOML and JSON,
//! and utilities for reading, writing, and migrating configuration files.

use crate::error::HbackupError;
use crate::{Result, constants::CONFIG_NAME, sysexits};
use hbackup::job::{BackupModel, CompressFormat, Job, Level};
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fs, io, process};

/// The main application configuration.
/// Stores the version and all backup jobs.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub(crate) struct Application {
    /// Configuration file version.
    pub version: String,
    /// List of backup jobs.
    pub jobs: Vec<Job>,
}

impl Default for Application {
    fn default() -> Self {
        Self {
            version: "1.0".to_string(),
            jobs: vec![],
        }
    }
}

impl Application {
    /// Creates a new, empty application configuration.
    pub(crate) fn new() -> Self {
        Self {
            version: "1.0".to_string(),
            jobs: vec![],
        }
    }

    /// Loads configuration from the config file, or returns a new config if not found.
    ///
    /// If the config file cannot be read, prints an error and exits.
    pub(crate) fn load_config() -> Self {
        if config_file_exists() {
            read_config_file()
        } else {
            Self::new()
        }
    }

    /// Adds a new backup job with a unique id.
    ///
    /// The id is automatically assigned to avoid conflicts.
    pub(crate) fn add_job(
        &mut self,
        source: PathBuf,
        target: PathBuf,
        compression: Option<CompressFormat>,
        level: Option<Level>,
        ignore: Option<Vec<String>>,
        model: Option<BackupModel>,
    ) -> Result<()> {
        let id = self
            .jobs
            .iter()
            .map(|job| job.id)
            .max()
            .unwrap_or(0)
            .checked_add(1)
            .ok_or(HbackupError::TooManyJobs(u32::MAX))?;
        self.jobs.push(Job {
            id,
            source,
            target,
            compression,
            level,
            ignore,
            model,
        });

        Ok(())
    }

    /// Removes all jobs from the configuration.
    pub(crate) fn reset_jobs(&mut self) {
        self.jobs = vec![];
    }

    /// Writes the current configuration to the config file.
    pub(crate) fn write(&self) -> Result<()> {
        write_config(self)?;
        Ok(())
    }

    /// Returns all jobs from the current configuration.
    pub(crate) fn get_jobs() -> Vec<Job> {
        Self::load_config().jobs
    }

    pub(crate) fn list_by_ids(ids: Vec<u32>) -> Vec<Job> {
        Self::get_jobs()
            .into_iter()
            .filter(|job| ids.contains(&job.id))
            .collect()
    }

    /// Lists backup jobs by their IDs.
    pub(crate) fn list_by_gte(id: u32) -> Vec<Job> {
        Self::get_jobs()
            .into_iter()
            .filter(|job| job.id >= id)
            .collect()
    }

    pub(crate) fn list_by_lte(id: u32) -> Vec<Job> {
        Self::get_jobs()
            .into_iter()
            .filter(|job| job.id <= id)
            .collect()
    }

    /// Removes a job by id. Returns Some if removed, None if not found.
    pub(crate) fn remove_job(&mut self, id: u32) -> Option<()> {
        if let Some(index) = self.jobs.iter().position(|j| j.id == id) {
            self.jobs.remove(index);
            Some(())
        } else {
            None
        }
    }
}

/// Returns the absolute path to the configuration file.
pub(crate) fn config_file() -> PathBuf {
    config_dir().join(CONFIG_NAME)
}

/// Returns the configuration directory for the application, platform-specific.
#[cfg(not(target_os = "macos"))]
fn config_dir() -> PathBuf {
    use crate::constants::PKG_NAME;

    let config_dir = dirs::config_dir().unwrap_or_else(|| {
        eprintln!("Couldn't get the home directory!!!");
        process::exit(sysexits::EX_UNAVAILABLE);
    });
    config_dir.join(PKG_NAME)
}

/// Returns the configuration directory for the application, platform-specific.
#[cfg(target_os = "macos")]
fn config_dir() -> PathBuf {
    use crate::constants::PKG_NAME;

    let home_dir = dirs::home_dir().unwrap_or_else(|| {
        eprintln!("Couldn't get the home directory!!!");
        process::exit(sysexits::EX_UNAVAILABLE);
    });
    home_dir.join(".config").join(PKG_NAME)
}

/// Checks if the configuration file exists.
fn config_file_exists() -> bool {
    config_file().exists()
}

/// Writes the application configuration to the config file in TOML format.
///
/// Creates the parent directory if it does not exist.
pub(crate) fn write_config(data: &Application) -> Result<()> {
    let file_path = config_file();
    if let Some(parent) = file_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let file = fs::File::create(file_path)?;
    let mut writer = io::BufWriter::new(file);
    let toml_str = toml::to_string_pretty(&data)?;
    writer.write_all(toml_str.as_bytes())?;
    writer.flush()?;
    Ok(())
}

/// Reads the default configuration file in TOML format.
fn read_config_file() -> Application {
    let file_path = config_file();
    let toml_str = fs::read_to_string(&file_path).unwrap_or_else(|e| {
        eprintln!("Error reading config file: {e}");
        std::process::exit(1);
    });
    toml::from_str(&toml_str).unwrap_or_else(|e| {
        eprintln!("Error parsing config file: {e}");
        std::process::exit(1);
    })
}

/// Initializes the configuration file for the application if it does not exist.
/// This ensures that the application always has a valid configuration file to work with.
pub(crate) fn init_config() {
    let config_file = config_file();
    if !config_file.exists() {
        let app = Application::new();

        let parent = config_file.parent().unwrap_or_else(|| Path::new(""));
        fs::create_dir_all(parent).unwrap();

        let file = fs::File::create(config_file).unwrap();
        let mut writer = io::BufWriter::new(file);
        let toml_str = toml::to_string_pretty(&app).unwrap();
        writer.write_all(toml_str.as_bytes()).unwrap();
        writer.flush().unwrap();
    }
}

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

    #[test]
    fn test_config_file() {
        let file = config_dir().join("hbackup").join("config.toml");
        assert_eq!(config_file(), file);
    }

    #[test]
    fn test_application_new() {
        let app = Application::new();
        assert_eq!(app.version, "1.0");
        assert!(app.jobs.is_empty());
    }

    #[test]
    fn test_application_add_job() -> Result<()> {
        let mut app = Application::new();
        let source = PathBuf::from("/test/source");
        let target = PathBuf::from("/test/target");

        app.add_job(
            source.clone(),
            target.clone(),
            Some(CompressFormat::Gzip),
            Some(Level::Default),
            None,
            None,
        )?;

        assert_eq!(app.jobs.len(), 1);
        assert_eq!(app.jobs[0].id, 1);
        assert_eq!(app.jobs[0].source, source);
        assert_eq!(app.jobs[0].target, target);
        assert!(matches!(
            app.jobs[0].compression,
            Some(CompressFormat::Gzip)
        ));
        assert!(matches!(app.jobs[0].level, Some(Level::Default)));
        Ok(())
    }

    #[test]
    fn test_application_add_multiple_jobs() -> Result<()> {
        let mut app = Application::new();

        // Add first job
        app.add_job(
            PathBuf::from("/test/source1"),
            PathBuf::from("/test/target1"),
            Some(CompressFormat::Zip),
            Some(Level::Fastest),
            None,
            None,
        )?;

        // Add second job
        app.add_job(
            PathBuf::from("/test/source2"),
            PathBuf::from("/test/target2"),
            Some(CompressFormat::Zstd),
            Some(Level::Best),
            Some(vec!["*.log".to_string()]),
            None,
        )?;

        assert_eq!(app.jobs.len(), 2);
        assert_eq!(app.jobs[0].id, 1);
        assert_eq!(app.jobs[1].id, 2);
        assert_ne!(app.jobs[0].id, app.jobs[1].id);

        Ok(())
    }

    #[test]
    fn test_application_remove_job() -> Result<()> {
        let mut app = Application::new();

        // Add jobs
        app.add_job(
            PathBuf::from("/test/source1"),
            PathBuf::from("/test/target1"),
            None,
            None,
            None,
            None,
        )?;
        app.add_job(
            PathBuf::from("/test/source2"),
            PathBuf::from("/test/target2"),
            None,
            None,
            None,
            None,
        )?;

        assert_eq!(app.jobs.len(), 2);

        // Remove first job
        let result = app.remove_job(1);
        assert!(result.is_some());
        assert_eq!(app.jobs.len(), 1);
        assert_eq!(app.jobs[0].id, 2);

        // Try to remove non-existent job
        let result = app.remove_job(999);
        assert!(result.is_none());
        assert_eq!(app.jobs.len(), 1);

        Ok(())
    }

    #[test]
    fn test_application_reset_jobs() -> Result<()> {
        let mut app = Application::new();

        // Add some jobs
        app.add_job(
            PathBuf::from("/test/source1"),
            PathBuf::from("/test/target1"),
            None,
            None,
            None,
            None,
        )?;
        app.add_job(
            PathBuf::from("/test/source2"),
            PathBuf::from("/test/target2"),
            None,
            None,
            None,
            None,
        )?;

        assert_eq!(app.jobs.len(), 2);

        app.reset_jobs();
        assert!(app.jobs.is_empty());

        Ok(())
    }

    #[test]
    fn test_application_serialization() -> Result<()> {
        let mut app = Application::new();
        app.add_job(
            PathBuf::from("/test/source"),
            PathBuf::from("/test/target"),
            Some(CompressFormat::Gzip),
            Some(Level::Default),
            Some(vec!["*.log".to_string()]),
            None,
        )?;

        // Test TOML serialization
        let toml_str = toml::to_string(&app).expect("Failed to serialize to TOML");
        assert!(toml_str.contains("version = \"1.0\""));
        assert!(toml_str.contains("id = 1"));
        assert!(toml_str.contains("Gzip"));

        // Test TOML deserialization
        let deserialized: Application =
            toml::from_str(&toml_str).expect("Failed to deserialize from TOML");
        assert_eq!(deserialized.version, app.version);
        assert_eq!(deserialized.jobs.len(), app.jobs.len());
        assert_eq!(deserialized.jobs[0].id, app.jobs[0].id);
        assert_eq!(deserialized.jobs[0].source, app.jobs[0].source);
        assert_eq!(deserialized.jobs[0].target, app.jobs[0].target);

        Ok(())
    }

    #[test]
    fn test_application_default() {
        let app = Application::default();
        assert_eq!(app.version, "1.0");
        assert!(app.jobs.is_empty());
    }

    /// Returns the configuration directory for testing, platform-specific.
    fn config_dir() -> PathBuf {
        if cfg!(target_os = "macos") {
            let home = env::var("HOME").unwrap();
            PathBuf::from(home).join(".config")
        } else {
            dirs::config_dir().unwrap()
        }
    }
}