proj-janitor 0.7.16

Scan, back up, restore, prune, and clean old projects safely
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
use anyhow::{Context, Result};
use serde::Deserialize;
use std::path::{Path, PathBuf};

const CONFIG_NAME: &str = ".proj-janitor.toml";

/// User configuration loaded from a `.proj-janitor.toml` file.
///
/// Provides defaults for command options. Command-line flags take precedence
/// over environment variables, which take precedence over this file.
#[derive(Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct Config {
    #[serde(default)]
    pub(crate) backup: BackupConfig,
    #[serde(default)]
    pub(crate) prune: PruneConfig,
    #[serde(default)]
    pub(crate) verify: VerifyConfig,
    #[serde(default)]
    pub(crate) restore: RestoreConfig,
}

#[derive(Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct BackupConfig {
    /// Default destination for `backup --backup-dest`.
    #[serde(default)]
    pub(crate) dest: Option<PathBuf>,
    /// Default retention count for `backup --keep`.
    #[serde(default)]
    pub(crate) keep: Option<usize>,
    /// Exclusion glob patterns for the archive strategy (matched per path component).
    #[serde(default)]
    pub(crate) exclude: Vec<String>,
    /// Whether to create incremental (delta) backups for the archive strategy.
    #[serde(default)]
    pub(crate) incremental: bool,
    /// Refuse archive backups when common secret paths are detected.
    #[serde(default)]
    pub(crate) fail_on_secrets: bool,
    /// Omit common secret paths from archive backups.
    #[serde(default)]
    pub(crate) exclude_secrets: bool,
    /// Emit archive packing / dry-run size progress on stderr.
    #[serde(default)]
    pub(crate) progress: bool,
    /// Refuse archive backups when free space on dest is below the estimate.
    #[serde(default)]
    pub(crate) check_space: bool,
    /// Refuse backups when the destination directory is group/world-accessible.
    #[serde(default)]
    pub(crate) fail_on_insecure_dest: bool,
    /// Encrypt archive/bundle payloads with openssl using this passphrase file.
    #[serde(default)]
    pub(crate) encrypt_passphrase_file: Option<std::path::PathBuf>,
}

#[derive(Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct PruneConfig {
    /// Default retention count for `prune --keep`.
    #[serde(default)]
    pub(crate) keep: Option<usize>,
}

#[derive(Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct VerifyConfig {
    /// Default for `verify --check-remote` when neither flag is passed.
    #[serde(default)]
    pub(crate) check_remote: bool,
}

#[derive(Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct RestoreConfig {
    /// Default for `restore --check-remote` when neither flag is passed.
    #[serde(default)]
    pub(crate) check_remote: bool,
    /// Require `--dest` so restore never writes to manifest `source` paths.
    #[serde(default)]
    pub(crate) require_dest: bool,
    /// Passphrase file used to decrypt openssl-encrypted archives.
    #[serde(default)]
    pub(crate) decrypt_passphrase_file: Option<std::path::PathBuf>,
    /// Replace an existing restore target directory after staging succeeds.
    #[serde(default)]
    pub(crate) force: bool,
    /// Keep restoring remaining projects after a per-project failure.
    #[serde(default)]
    pub(crate) continue_on_error: bool,
}

/// Resolve an optional CLI `--flag` / `--no-flag` pair against a config default.
/// Explicit flags always win; otherwise use `config_default`.
pub(crate) fn resolve_tri_state(enable: bool, disable: bool, config_default: bool) -> bool {
    if enable {
        true
    } else if disable {
        false
    } else {
        config_default
    }
}

/// Resolve an optional CLI `--check-remote` / `--no-check-remote` pair against
/// a config default. Explicit flags always win; otherwise use `config_default`.
pub(crate) fn resolve_check_remote(
    check_remote: bool,
    no_check_remote: bool,
    config_default: bool,
) -> bool {
    resolve_tri_state(check_remote, no_check_remote, config_default)
}

/// Load configuration from an explicit path, or discover `.proj-janitor.toml`
/// by walking up from the current directory. Returns `Ok(None)` when no config
/// file is present and no explicit path was given.
pub(crate) fn discover_config(explicit: Option<&Path>) -> Result<Option<Config>> {
    let path = match explicit {
        Some(path) => Some(path.to_path_buf()),
        None => find_config(&std::env::current_dir()?),
    };
    let Some(path) = path else {
        return Ok(None);
    };
    let text = std::fs::read_to_string(&path)
        .with_context(|| format!("cannot read config {}", path.display()))?;
    let config: Config =
        toml::from_str(&text).with_context(|| format!("invalid config {}", path.display()))?;
    anyhow::ensure!(
        config.backup.keep.is_none_or(|keep| keep >= 1),
        "invalid config {}: [backup].keep must be a positive integer",
        path.display()
    );
    anyhow::ensure!(
        config.prune.keep.is_none_or(|keep| keep >= 1),
        "invalid config {}: [prune].keep must be a positive integer",
        path.display()
    );
    for pattern in &config.backup.exclude {
        anyhow::ensure!(
            !pattern.is_empty(),
            "invalid config {}: [backup].exclude entries must not be empty",
            path.display()
        );
        anyhow::ensure!(
            !pattern.contains('{') && !pattern.contains('}'),
            "invalid config {}: [backup].exclude brace expansion is not supported: {}",
            path.display(),
            pattern
        );
    }
    Ok(Some(config))
}

fn find_config(start: &Path) -> Option<PathBuf> {
    start.ancestors().find_map(|dir| {
        let candidate = dir.join(CONFIG_NAME);
        candidate.is_file().then_some(candidate)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::atomic::{AtomicU32, Ordering};

    static NEXT_TEMP: AtomicU32 = AtomicU32::new(0);

    struct TempDir(PathBuf);
    impl TempDir {
        fn new() -> Self {
            let path = std::env::temp_dir().join(format!(
                "projjan-config-test-{}-{}",
                std::process::id(),
                NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
            ));
            fs::create_dir_all(&path).unwrap();
            Self(path)
        }
    }
    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn write_config(dir: &Path, content: &str) -> PathBuf {
        let path = dir.join(CONFIG_NAME);
        fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn explicit_path_loads_backup_dest() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\ndest = \"/tmp/backups\"\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert_eq!(config.backup.dest, Some(PathBuf::from("/tmp/backups")));
        assert_eq!(config.prune.keep, None);
    }

    #[test]
    fn explicit_path_loads_prune_keep() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[prune]\nkeep = 7\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert_eq!(config.prune.keep, Some(7));
        assert_eq!(config.backup.dest, None);
    }

    #[test]
    fn explicit_path_loads_backup_keep() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nkeep = 5\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert_eq!(config.backup.keep, Some(5));
    }

    #[test]
    fn explicit_path_loads_backup_exclude() {
        let temp = TempDir::new();
        let path = write_config(
            temp.0.as_path(),
            "[backup]\nexclude = [\"node_modules\", \"*.log\"]\n",
        );
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert_eq!(config.backup.exclude, vec!["node_modules", "*.log"]);
        assert_eq!(config.backup.dest, None);
        assert_eq!(config.backup.keep, None);
    }

    #[test]
    fn empty_exclude_entry_is_rejected() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nexclude = [\"\"]\n");
        let err = discover_config(Some(&path)).unwrap_err().to_string();
        assert!(
            err.contains("[backup].exclude entries must not be empty"),
            "{err}"
        );
    }

    #[test]
    fn brace_expansion_is_rejected_for_exclude() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nexclude = [\"{a,b}\"]\n");
        let err = discover_config(Some(&path)).unwrap_err().to_string();
        assert!(err.contains("brace expansion is not supported"), "{err}");
    }

    #[test]
    fn explicit_path_loads_backup_incremental() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nincremental = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.backup.incremental);
        assert_eq!(config.backup.dest, None);
        assert_eq!(config.backup.keep, None);
        assert_eq!(config.backup.exclude, Vec::<String>::new());
    }

    #[test]
    fn explicit_path_loads_verify_and_restore_check_remote() {
        let temp = TempDir::new();
        let path = write_config(
            temp.0.as_path(),
            "[verify]\ncheck_remote = true\n[restore]\ncheck_remote = true\n",
        );
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.verify.check_remote);
        assert!(config.restore.check_remote);
        assert!(!config.restore.require_dest);
        assert!(!resolve_check_remote(false, true, true));
        assert!(resolve_check_remote(true, false, false));
        assert!(resolve_check_remote(false, false, true));
        assert!(!resolve_check_remote(false, false, false));
    }

    #[test]
    fn explicit_path_loads_restore_require_dest() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[restore]\nrequire_dest = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.restore.require_dest);
        assert!(!config.restore.check_remote);
    }

    #[test]
    fn explicit_path_loads_restore_force() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[restore]\nforce = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.restore.force);
        assert!(!config.restore.continue_on_error);
    }

    #[test]
    fn explicit_path_loads_restore_continue_on_error() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[restore]\ncontinue_on_error = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.restore.continue_on_error);
    }

    #[test]
    fn incremental_defaults_to_false() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\ndest = \"/tmp/x\"\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(!config.backup.incremental);
    }

    #[test]
    fn explicit_path_loads_backup_fail_on_secrets() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nfail_on_secrets = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.backup.fail_on_secrets);
        assert!(!resolve_tri_state(false, true, true));
        assert!(resolve_tri_state(true, false, false));
        assert!(resolve_tri_state(false, false, true));
        assert!(!resolve_tri_state(false, false, false));
    }

    #[test]
    fn fail_on_secrets_defaults_to_false() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\ndest = \"/tmp/x\"\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(!config.backup.fail_on_secrets);
    }

    #[test]
    fn explicit_path_loads_backup_exclude_secrets() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nexclude_secrets = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.backup.exclude_secrets);
    }

    #[test]
    fn explicit_path_loads_backup_progress() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nprogress = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.backup.progress);
    }

    #[test]
    fn explicit_path_loads_backup_check_space() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\ncheck_space = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.backup.check_space);
    }

    #[test]
    fn explicit_path_loads_backup_fail_on_insecure_dest() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nfail_on_insecure_dest = true\n");
        let config = discover_config(Some(&path)).unwrap().unwrap();
        assert!(config.backup.fail_on_insecure_dest);
    }

    #[test]
    fn zero_keep_is_rejected_for_backup_and_prune() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nkeep = 0\n");
        let err = discover_config(Some(&path)).unwrap_err().to_string();
        assert!(
            err.contains("[backup].keep must be a positive integer"),
            "{err}"
        );
        let path = write_config(temp.0.as_path(), "[prune]\nkeep = 0\n");
        let err = discover_config(Some(&path)).unwrap_err().to_string();
        assert!(
            err.contains("[prune].keep must be a positive integer"),
            "{err}"
        );
    }

    #[test]
    fn explicit_path_missing_is_error() {
        let temp = TempDir::new();
        let missing = temp.0.join("nope.toml");
        assert!(discover_config(Some(&missing)).is_err());
    }

    #[test]
    fn invalid_toml_is_error() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "backup = [not toml\n");
        let err = discover_config(Some(&path)).unwrap_err().to_string();
        assert!(err.contains("invalid config"));
    }

    #[test]
    fn unknown_field_is_rejected() {
        let temp = TempDir::new();
        let path = write_config(temp.0.as_path(), "[backup]\nunknown = 1\n");
        assert!(discover_config(Some(&path)).is_err());
    }

    #[test]
    fn no_config_anywhere_returns_none() {
        assert!(discover_config(None).unwrap().is_none());
    }

    #[test]
    fn find_config_walks_up_ancestors() {
        let temp = TempDir::new();
        let nested = temp.0.join("a/b/c");
        fs::create_dir_all(&nested).unwrap();
        write_config(temp.0.as_path(), "[prune]\nkeep = 3\n");
        let found = find_config(&nested).unwrap();
        assert_eq!(found, temp.0.join(CONFIG_NAME));
    }
}