repolens 2.0.0

A CLI tool to audit and prepare repositories for open source or enterprise standards
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
//! Git history quality rules
//!
//! This module provides rules for analyzing Git history quality:
//! - Non-conventional commit messages (HIST001)
//! - Giant commits (HIST002)
//! - Unsigned commits (HIST003)
//! - Force push detected on protected branch (HIST004)

use crate::config::Config;
use crate::error::RepoLensError;
use crate::providers::github::GitHubProvider;
use crate::rules::engine::RuleCategory;
use crate::rules::results::{Finding, Severity};
use crate::scanner::Scanner;

use regex::Regex;
use std::process::Command;

/// Number of recent commits to analyze
const COMMITS_TO_ANALYZE: usize = 100;
/// Threshold for giant commits (number of files changed)
const GIANT_COMMIT_THRESHOLD: usize = 50;

/// Rules for checking Git history quality
pub struct HistoryRules;

#[async_trait::async_trait]
impl RuleCategory for HistoryRules {
    fn name(&self) -> &'static str {
        "history"
    }

    async fn run(&self, scanner: &Scanner, config: &Config) -> Result<Vec<Finding>, RepoLensError> {
        let mut findings = Vec::new();
        let root = scanner.root().to_path_buf();

        if config.is_rule_enabled("history/conventional-commits") {
            findings.extend(check_conventional_commits(&root));
        }

        if config.is_rule_enabled("history/giant-commits") {
            findings.extend(check_giant_commits(&root));
        }

        if config.is_rule_enabled("history/unsigned-commits") {
            findings.extend(check_unsigned_commits(&root));
        }

        if config.is_rule_enabled("history/force-push") {
            findings.extend(check_force_push());
        }

        Ok(findings)
    }
}

/// HIST001: Check for non-conventional commit messages
fn check_conventional_commits(root: &std::path::Path) -> Vec<Finding> {
    let mut findings = Vec::new();

    let output = Command::new("git")
        .args(["log", &format!("-{}", COMMITS_TO_ANALYZE), "--format=%s"])
        .current_dir(root)
        .output();

    let output = match output {
        Ok(out) if out.status.success() => out,
        _ => return findings,
    };

    let messages = String::from_utf8_lossy(&output.stdout);
    let conventional_re = Regex::new(
        r"^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?!?:\s",
    )
    .expect("Invalid regex");

    let total = messages.lines().count();
    let non_conventional = messages
        .lines()
        .filter(|line| !line.is_empty() && !conventional_re.is_match(line))
        .count();

    if total > 0 && non_conventional > 0 {
        let percentage = (non_conventional as f64 / total as f64 * 100.0).round() as u32;
        findings.push(
            Finding::new(
                "HIST001",
                "history",
                Severity::Info,
                format!(
                    "{}/{} commits ({percentage}%) do not follow conventional commit format",
                    non_conventional, total
                ),
            )
            .with_description(
                "Conventional Commits provide a structured format for commit messages \
                 (e.g., feat:, fix:, docs:). This enables automatic changelog generation, \
                 semantic versioning, and better git history readability.",
            )
            .with_remediation(
                "Adopt the Conventional Commits specification (https://www.conventionalcommits.org). \
                 Consider using commitlint or similar tools to enforce the format.",
            ),
        );
    }

    findings
}

/// HIST002: Check for giant commits (> 50 files changed)
fn check_giant_commits(root: &std::path::Path) -> Vec<Finding> {
    let mut findings = Vec::new();

    // Get commit hashes and file counts using numstat
    let output = Command::new("git")
        .args([
            "log",
            &format!("-{}", COMMITS_TO_ANALYZE),
            "--format=%H",
            "--shortstat",
        ])
        .current_dir(root)
        .output();

    let output = match output {
        Ok(out) if out.status.success() => out,
        _ => return findings,
    };

    let text = String::from_utf8_lossy(&output.stdout);
    let files_changed_re = Regex::new(r"(\d+) files? changed").expect("Invalid regex");

    let mut giant_count = 0;

    for line in text.lines() {
        if let Some(caps) = files_changed_re.captures(line) {
            if let Ok(files) = caps[1].parse::<usize>() {
                if files > GIANT_COMMIT_THRESHOLD {
                    giant_count += 1;
                }
            }
        }
    }

    if giant_count > 0 {
        findings.push(
            Finding::new(
                "HIST002",
                "history",
                Severity::Warning,
                format!(
                    "{} commit(s) with more than {} files changed",
                    giant_count, GIANT_COMMIT_THRESHOLD
                ),
            )
            .with_description(
                "Large commits changing many files are harder to review, understand, \
                 and bisect. They often indicate that multiple logical changes were \
                 bundled into a single commit.",
            )
            .with_remediation(
                "Break large changes into smaller, focused commits. Each commit should \
                 represent a single logical change. Use interactive rebase to split commits.",
            ),
        );
    }

    findings
}

/// HIST003: Check for unsigned commits (no GPG/SSH signature)
fn check_unsigned_commits(root: &std::path::Path) -> Vec<Finding> {
    let mut findings = Vec::new();

    let output = Command::new("git")
        .args(["log", &format!("-{}", COMMITS_TO_ANALYZE), "--format=%G?"])
        .current_dir(root)
        .output();

    let output = match output {
        Ok(out) if out.status.success() => out,
        _ => return findings,
    };

    let signatures = String::from_utf8_lossy(&output.stdout);
    let total = signatures.lines().count();
    // G = good signature, U = good but untrusted, E = expired, X = expired key
    // N = no signature, B = bad signature
    let unsigned = signatures.lines().filter(|line| *line == "N").count();

    if total > 0 && unsigned > 0 {
        let percentage = (unsigned as f64 / total as f64 * 100.0).round() as u32;
        findings.push(
            Finding::new(
                "HIST003",
                "history",
                Severity::Info,
                format!(
                    "{}/{} commits ({percentage}%) are not signed",
                    unsigned, total
                ),
            )
            .with_description(
                "Signed commits provide cryptographic verification of authorship. \
                 This helps prevent commit spoofing and increases trust in the code history.",
            )
            .with_remediation(
                "Configure GPG or SSH commit signing: \
                 git config commit.gpgsign true. \
                 See https://docs.github.com/en/authentication/managing-commit-signature-verification",
            ),
        );
    }

    findings
}

/// HIST004: Check for force push on protected branches (via reflog)
fn check_force_push() -> Vec<Finding> {
    let mut findings = Vec::new();

    if !GitHubProvider::is_available() {
        return findings;
    }

    let provider = match GitHubProvider::new() {
        Ok(p) => p,
        Err(_) => return findings,
    };

    // Check GitHub audit log for force pushes via the events API
    let output = Command::new("gh")
        .args([
            "api",
            &format!("repos/{}/{}/events", provider.owner(), provider.name()),
            "--jq",
            r#"[.[] | select(.type == "PushEvent" and .payload.forced == true)] | length"#,
        ])
        .output();

    match output {
        Ok(out) if out.status.success() => {
            let count_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if let Ok(count) = count_str.parse::<u64>() {
                if count > 0 {
                    findings.push(
                        Finding::new(
                            "HIST004",
                            "history",
                            Severity::Warning,
                            format!(
                                "{} force push event(s) detected in recent activity",
                                count
                            ),
                        )
                        .with_description(
                            "Force pushes rewrite Git history and can cause data loss \
                             for other contributors. They should be avoided on shared branches, \
                             especially protected ones.",
                        )
                        .with_remediation(
                            "Enable branch protection rules to block force pushes on main branches. \
                             Use --force-with-lease instead of --force when necessary.",
                        ),
                    );
                }
            }
        }
        _ => {} // Skip if API call fails
    }

    findings
}

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

    fn init_git_repo(dir: &std::path::Path) {
        Command::new("git")
            .args(["init"])
            .current_dir(dir)
            .output()
            .expect("Failed to init git repo");
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(dir)
            .output()
            .expect("Failed to set git config");
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(dir)
            .output()
            .expect("Failed to set git config");
    }

    #[test]
    fn test_conventional_commits_all_valid() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        init_git_repo(root);

        // Create conventional commits
        std::fs::write(root.join("file1.txt"), "content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "feat: add feature"])
            .current_dir(root)
            .output()
            .unwrap();

        std::fs::write(root.join("file2.txt"), "content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "fix: resolve bug"])
            .current_dir(root)
            .output()
            .unwrap();

        let findings = check_conventional_commits(root);
        assert!(
            findings.is_empty(),
            "Expected no findings for valid conventional commits"
        );
    }

    #[test]
    fn test_conventional_commits_some_invalid() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        init_git_repo(root);

        std::fs::write(root.join("file1.txt"), "content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "feat: valid commit"])
            .current_dir(root)
            .output()
            .unwrap();

        std::fs::write(root.join("file2.txt"), "content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "just a random message"])
            .current_dir(root)
            .output()
            .unwrap();

        let findings = check_conventional_commits(root);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "HIST001");
    }

    #[test]
    fn test_giant_commits_none() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        init_git_repo(root);

        // Create a small commit
        std::fs::write(root.join("file.txt"), "content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "feat: small change"])
            .current_dir(root)
            .output()
            .unwrap();

        let findings = check_giant_commits(root);
        assert!(findings.is_empty());
    }

    #[test]
    fn test_unsigned_commits() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        init_git_repo(root);

        std::fs::write(root.join("file.txt"), "content").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "feat: unsigned commit"])
            .current_dir(root)
            .output()
            .unwrap();

        let findings = check_unsigned_commits(root);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "HIST003");
    }

    #[test]
    fn test_thresholds() {
        assert_eq!(COMMITS_TO_ANALYZE, 100);
        assert_eq!(GIANT_COMMIT_THRESHOLD, 50);
    }
}