rsmultigit 0.1.16

Manage multiple git repositories at once
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
use std::collections::BTreeMap;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::Deserialize;
use sha2::{Digest, Sha256};

#[derive(Debug, Deserialize)]
pub struct CheckConfig {
    /// Glob patterns (with shell expansion) identifying repo roots.
    /// Non-git directories matching the pattern are filtered out.
    #[serde(default)]
    pub repos: Vec<String>,
    #[serde(default)]
    pub check: Vec<Rule>,
}

#[derive(Debug, Deserialize)]
pub struct Rule {
    pub name: String,
    pub select: String,
    #[serde(default)]
    pub exclude: Option<String>,
    #[serde(default)]
    pub marker: Option<String>,
    pub path: String,
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    /// When true, every in-scope repo must contain `path`. Missing files become
    /// rule violations (reported as "missing in: ..." and counted as mismatches).
    /// When false (default), missing files are silently skipped.
    #[serde(default)]
    pub must_have: bool,
}

fn default_enabled() -> bool {
    true
}

/// Outcome of evaluating a single rule.
pub struct RuleResult {
    pub name: String,
    /// The file inside each repo that was hashed (the rule's `path`).
    pub path: String,
    /// Files grouped by SHA-256 digest, ordered by group size descending
    /// (largest group first — the presumed "canonical" version).
    pub groups: Vec<Vec<PathBuf>>,
    /// Total number of files considered.
    pub total_files: usize,
    /// Repos that matched selection but lacked `path`. When the rule has
    /// `must_have = false`, they're treated as "skipped" (not a violation).
    pub skipped: Vec<PathBuf>,
    /// Repos that matched selection but lacked `path` *and* the rule has
    /// `must_have = true`. These are rule violations.
    pub must_have_violations: Vec<PathBuf>,
}

impl RuleResult {
    pub fn is_consistent(&self) -> bool {
        self.groups.len() <= 1 && self.must_have_violations.is_empty()
    }

    /// True when the rule hashed no files and has no must_have violations to
    /// report — i.e. it checked nothing at all. Usually a stale `select`/`path`,
    /// so check-same treats this as a failure unless --allow-empty is passed.
    pub fn matched_nothing(&self) -> bool {
        self.total_files == 0 && self.must_have_violations.is_empty()
    }
}

/// Environment variable used to override the config path (tests set this).
pub const CONFIG_PATH_ENV: &str = "RSMULTIGIT_CONFIG";

/// Resolve the path of the config file. Tests can override via `RSMULTIGIT_CONFIG`.
pub fn default_config_path() -> Result<PathBuf> {
    if let Ok(p) = std::env::var(CONFIG_PATH_ENV) {
        return Ok(PathBuf::from(p));
    }
    let expanded = shellexpand::full("~/.config/rsmultigit/config.toml")
        .context("failed to expand default config path")?;
    Ok(PathBuf::from(expanded.into_owned()))
}

/// Parse a config file from disk.
pub fn load_config(path: &Path) -> Result<CheckConfig> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read config file {}", path.display()))?;
    let config: CheckConfig = toml::from_str(&text)
        .with_context(|| format!("failed to parse config file {}", path.display()))?;
    Ok(config)
}

/// Expand globs in `config.repos`, filter to directories containing `.git/`,
/// dedupe, and sort. Returns an error if `repos` is empty or no matches exist.
pub fn resolve_repos(config: &CheckConfig) -> Result<Vec<PathBuf>> {
    if config.repos.is_empty() {
        anyhow::bail!("config must set `repos = [...]` with at least one entry");
    }

    let mut out: Vec<PathBuf> = Vec::new();
    for entry in &config.repos {
        let expanded = shellexpand::full(entry)
            .with_context(|| format!("failed to expand `{entry}` in repos"))?;
        let matches =
            glob::glob(&expanded).with_context(|| format!("invalid glob pattern `{entry}`"))?;
        for m in matches {
            let path = m.with_context(|| format!("error iterating glob `{entry}`"))?;
            if path.is_dir() && path.join(".git").is_dir() {
                out.push(path);
            }
        }
    }

    out.sort();
    out.dedup();

    if out.is_empty() {
        anyhow::bail!("no git repositories matched `repos` patterns");
    }
    Ok(out)
}

fn match_glob(pattern: &str, name: &str) -> Result<bool> {
    glob::Pattern::new(pattern)
        .map(|p| p.matches(name))
        .with_context(|| format!("invalid glob pattern: {pattern}"))
}

/// Apply `select`, `exclude`, and `marker` filters to the discovered repo list.
/// `repos` are absolute or relative paths to repo roots.
fn select_repos(rule: &Rule, repos: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    for repo in repos {
        let name = match repo.file_name() {
            Some(n) => n.to_string_lossy().into_owned(),
            None => continue,
        };
        if !match_glob(&rule.select, &name)? {
            continue;
        }
        if let Some(ex) = &rule.exclude
            && match_glob(ex, &name)?
        {
            continue;
        }
        if let Some(marker) = &rule.marker
            && !repo.join(marker).exists()
        {
            continue;
        }
        out.push(repo.clone());
    }
    Ok(out)
}

fn hash_file(path: &Path) -> Result<[u8; 32]> {
    let file = File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
    let mut reader = BufReader::with_capacity(64 * 1024, file);
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 64 * 1024];
    loop {
        let n = reader
            .read(&mut buf)
            .with_context(|| format!("failed to read {}", path.display()))?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hasher.finalize().into())
}

/// Evaluate a single rule against the set of discovered repos.
pub fn evaluate_rule(rule: &Rule, repos: &[PathBuf]) -> Result<RuleResult> {
    let candidates = select_repos(rule, repos)?;

    let mut files: Vec<PathBuf> = Vec::new();
    let mut missing: Vec<PathBuf> = Vec::new();
    for repo in candidates {
        let target = repo.join(&rule.path);
        if target.is_file() {
            files.push(target);
        } else {
            missing.push(repo);
        }
    }

    let mut buckets: BTreeMap<[u8; 32], Vec<PathBuf>> = BTreeMap::new();
    for file in &files {
        let digest = hash_file(file)?;
        buckets.entry(digest).or_default().push(file.clone());
    }

    let mut groups: Vec<Vec<PathBuf>> = buckets.into_values().collect();
    groups.sort_by_key(|g| std::cmp::Reverse(g.len()));

    let (skipped, must_have_violations) = if rule.must_have {
        (Vec::new(), missing)
    } else {
        (missing, Vec::new())
    };

    Ok(RuleResult {
        name: rule.name.clone(),
        path: rule.path.clone(),
        groups,
        total_files: files.len(),
        skipped,
        must_have_violations,
    })
}

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

    fn write(path: &Path, content: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, content).unwrap();
    }

    #[test]
    fn config_parses() {
        let toml = r#"
            [[check]]
            name = "gi"
            select = "*"
            path = ".gitignore"

            [[check]]
            name = "py-make"
            select = "py*"
            exclude = "pydraft*"
            marker = ".veltzer.tag"
            path = "Makefile"
        "#;
        let config: CheckConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.check.len(), 2);
        assert_eq!(config.check[0].name, "gi");
        assert_eq!(config.check[1].exclude.as_deref(), Some("pydraft*"));
        assert_eq!(config.check[1].marker.as_deref(), Some(".veltzer.tag"));
    }

    #[test]
    fn empty_config_has_no_checks() {
        let config: CheckConfig = toml::from_str("").unwrap();
        assert!(config.check.is_empty());
    }

    #[test]
    fn enabled_defaults_to_true() {
        let toml = r#"
            [[check]]
            name = "a"
            select = "*"
            path = "x"
        "#;
        let config: CheckConfig = toml::from_str(toml).unwrap();
        assert!(config.check[0].enabled);
    }

    #[test]
    fn resolve_repos_requires_non_empty() {
        let cfg = CheckConfig {
            repos: vec![],
            check: vec![],
        };
        assert!(resolve_repos(&cfg).is_err());
    }

    #[test]
    fn resolve_repos_filters_to_git_dirs() {
        let tmp = TempDir::new().unwrap();
        // Two git repos, one plain dir.
        fs::create_dir_all(tmp.path().join("a/.git")).unwrap();
        fs::create_dir_all(tmp.path().join("b/.git")).unwrap();
        fs::create_dir_all(tmp.path().join("c")).unwrap();

        let cfg = CheckConfig {
            repos: vec![format!("{}/*", tmp.path().display())],
            check: vec![],
        };
        let repos = resolve_repos(&cfg).unwrap();
        assert_eq!(repos.len(), 2);
        assert!(repos.iter().all(|p| p.join(".git").is_dir()));
    }

    #[test]
    fn resolve_repos_dedupes() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("a/.git")).unwrap();

        let cfg = CheckConfig {
            repos: vec![
                format!("{}/a", tmp.path().display()),
                format!("{}/*", tmp.path().display()),
            ],
            check: vec![],
        };
        let repos = resolve_repos(&cfg).unwrap();
        assert_eq!(repos.len(), 1);
    }

    #[test]
    fn resolve_repos_no_matches_errors() {
        let tmp = TempDir::new().unwrap();
        let cfg = CheckConfig {
            repos: vec![format!("{}/nonexistent*", tmp.path().display())],
            check: vec![],
        };
        assert!(resolve_repos(&cfg).is_err());
    }

    #[test]
    fn enabled_can_be_disabled() {
        let toml = r#"
            [[check]]
            name = "a"
            select = "*"
            path = "x"
            enabled = false
        "#;
        let config: CheckConfig = toml::from_str(toml).unwrap();
        assert!(!config.check[0].enabled);
    }

    #[test]
    fn identical_files_form_one_group() {
        let tmp = TempDir::new().unwrap();
        for r in ["a", "b", "c"] {
            write(&tmp.path().join(r).join(".gitignore"), "target\n");
        }
        let repos: Vec<PathBuf> = ["a", "b", "c"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert_eq!(result.groups.len(), 1);
        assert_eq!(result.total_files, 3);
    }

    #[test]
    fn divergent_files_form_multiple_groups() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("a/.gitignore"), "x\n");
        write(&tmp.path().join("b/.gitignore"), "x\n");
        write(&tmp.path().join("c/.gitignore"), "y\n");
        let repos: Vec<PathBuf> = ["a", "b", "c"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(!result.is_consistent());
        assert_eq!(result.groups.len(), 2);
        // Largest group (2 files) first.
        assert_eq!(result.groups[0].len(), 2);
        assert_eq!(result.groups[1].len(), 1);
    }

    #[test]
    fn missing_files_are_skipped_not_flagged() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("a/.gitignore"), "x\n");
        write(&tmp.path().join("b/.gitignore"), "x\n");
        fs::create_dir_all(tmp.path().join("c")).unwrap();
        let repos: Vec<PathBuf> = ["a", "b", "c"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert_eq!(result.total_files, 2);
        assert_eq!(result.skipped.len(), 1);
    }

    #[test]
    fn select_filters_by_repo_name_glob() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("pyalpha/Makefile"), "PY\n");
        write(&tmp.path().join("pybeta/Makefile"), "PY\n");
        write(&tmp.path().join("go-proj/Makefile"), "GO\n");
        let repos: Vec<PathBuf> = ["pyalpha", "pybeta", "go-proj"]
            .iter()
            .map(|r| tmp.path().join(r))
            .collect();
        let rule = Rule {
            name: "py-make".into(),
            select: "py*".into(),
            exclude: None,
            marker: None,
            path: "Makefile".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert_eq!(result.total_files, 2);
    }

    #[test]
    fn exclude_drops_matching_repos() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("pyalpha/Makefile"), "A\n");
        write(&tmp.path().join("pybeta/Makefile"), "A\n");
        write(&tmp.path().join("pydraft/Makefile"), "B\n");
        let repos: Vec<PathBuf> = ["pyalpha", "pybeta", "pydraft"]
            .iter()
            .map(|r| tmp.path().join(r))
            .collect();
        let rule = Rule {
            name: "py-make".into(),
            select: "py*".into(),
            exclude: Some("pydraft*".into()),
            marker: None,
            path: "Makefile".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert_eq!(result.total_files, 2);
    }

    #[test]
    fn must_have_defaults_to_false() {
        let toml = r#"
            [[check]]
            name = "a"
            select = "*"
            path = "x"
        "#;
        let config: CheckConfig = toml::from_str(toml).unwrap();
        assert!(!config.check[0].must_have);
    }

    #[test]
    fn must_have_false_keeps_missing_in_skipped() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("a/.gitignore"), "x\n");
        write(&tmp.path().join("b/.gitignore"), "x\n");
        fs::create_dir_all(tmp.path().join("c")).unwrap();
        let repos: Vec<PathBuf> = ["a", "b", "c"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert_eq!(result.skipped.len(), 1);
        assert!(result.must_have_violations.is_empty());
    }

    #[test]
    fn must_have_true_moves_missing_to_violations() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("a/.gitignore"), "x\n");
        write(&tmp.path().join("b/.gitignore"), "x\n");
        fs::create_dir_all(tmp.path().join("c")).unwrap();
        let repos: Vec<PathBuf> = ["a", "b", "c"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: true,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(!result.is_consistent());
        assert!(result.skipped.is_empty());
        assert_eq!(result.must_have_violations.len(), 1);
        assert!(result.must_have_violations[0].ends_with("c"));
    }

    #[test]
    fn must_have_true_all_present_is_consistent() {
        let tmp = TempDir::new().unwrap();
        for r in ["a", "b", "c"] {
            write(&tmp.path().join(r).join(".gitignore"), "same\n");
        }
        let repos: Vec<PathBuf> = ["a", "b", "c"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: true,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert!(result.must_have_violations.is_empty());
    }

    #[test]
    fn rule_matching_no_files_reports_matched_nothing() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("a")).unwrap();
        fs::create_dir_all(tmp.path().join("b")).unwrap();
        let repos: Vec<PathBuf> = ["a", "b"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.matched_nothing());
        assert_eq!(result.total_files, 0);
        // A must_have rule with the same emptiness has violations to report,
        // so it is not "matched nothing" — it's a plain failure.
        let must_have_rule = Rule {
            must_have: true,
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
        };
        let result = evaluate_rule(&must_have_rule, &repos).unwrap();
        assert!(!result.matched_nothing());
    }

    #[test]
    fn rule_with_files_is_not_matched_nothing() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("a/.gitignore"), "x\n");
        let repos = vec![tmp.path().join("a")];
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: None,
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(!result.matched_nothing());
    }

    #[test]
    fn marker_filters_by_presence() {
        let tmp = TempDir::new().unwrap();
        write(&tmp.path().join("a/.tag"), "");
        write(&tmp.path().join("a/.gitignore"), "x\n");
        write(&tmp.path().join("b/.gitignore"), "y\n");
        let repos: Vec<PathBuf> = ["a", "b"].iter().map(|r| tmp.path().join(r)).collect();
        let rule = Rule {
            name: "gi".into(),
            select: "*".into(),
            exclude: None,
            marker: Some(".tag".into()),
            path: ".gitignore".into(),
            enabled: true,
            must_have: false,
        };
        let result = evaluate_rule(&rule, &repos).unwrap();
        assert!(result.is_consistent());
        assert_eq!(result.total_files, 1);
    }
}