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
//! Issues and Pull Requests hygiene rules
//!
//! This module provides rules for checking issue and PR hygiene:
//! - Stale issues (ISSUE001)
//! - Stale PRs (ISSUE002)
//! - Issues without labels (ISSUE003)
//! - PRs without reviewers (PR001)
//! - Abandoned draft PRs (PR002)

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 chrono::{DateTime, Utc};
use serde::Deserialize;

/// Threshold for stale issues (90 days)
const STALE_ISSUE_DAYS: i64 = 90;
/// Threshold for stale PRs (30 days)
const STALE_PR_DAYS: i64 = 30;
/// Threshold for abandoned draft PRs (14 days)
const ABANDONED_DRAFT_DAYS: i64 = 14;

#[derive(Debug, Deserialize)]
struct Issue {
    #[allow(dead_code)]
    number: u64,
    #[allow(dead_code)]
    title: String,
    #[serde(rename = "updatedAt")]
    updated_at: String,
    labels: Vec<Label>,
}

#[derive(Debug, Deserialize)]
struct Label {
    #[allow(dead_code)]
    name: String,
}

#[derive(Debug, Deserialize)]
struct PullRequest {
    #[allow(dead_code)]
    number: u64,
    #[allow(dead_code)]
    title: String,
    #[serde(rename = "updatedAt")]
    updated_at: String,
    #[serde(rename = "isDraft")]
    is_draft: bool,
    #[serde(rename = "reviewRequests")]
    review_requests: ReviewRequests,
    reviews: Reviews,
}

#[derive(Debug, Deserialize)]
struct ReviewRequests {
    #[serde(rename = "totalCount")]
    total_count: u64,
}

#[derive(Debug, Deserialize)]
struct Reviews {
    #[serde(rename = "totalCount")]
    total_count: u64,
}

/// Rules for checking issue and PR hygiene
pub struct IssuesRules;

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

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

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

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

        if config.is_rule_enabled("issues/stale-issues") {
            findings.extend(check_stale_issues(&provider));
        }

        if config.is_rule_enabled("issues/stale-prs") {
            findings.extend(check_stale_prs(&provider));
        }

        if config.is_rule_enabled("issues/unlabeled") {
            findings.extend(check_unlabeled_issues(&provider));
        }

        if config.is_rule_enabled("issues/pr-reviewers") {
            findings.extend(check_pr_reviewers(&provider));
        }

        if config.is_rule_enabled("issues/abandoned-drafts") {
            findings.extend(check_abandoned_drafts(&provider));
        }

        Ok(findings)
    }
}

/// ISSUE001: Check for stale issues (> 90 days without activity)
fn check_stale_issues(provider: &GitHubProvider) -> Vec<Finding> {
    let mut findings = Vec::new();

    let output = std::process::Command::new("gh")
        .args([
            "issue",
            "list",
            "--repo",
            &format!("{}/{}", provider.owner(), provider.name()),
            "--state",
            "open",
            "--json",
            "number,title,updatedAt,labels",
            "--limit",
            "100",
        ])
        .output();

    let issues: Vec<Issue> = match output {
        Ok(out) if out.status.success() => serde_json::from_slice(&out.stdout).unwrap_or_default(),
        _ => return findings,
    };

    let now = Utc::now();
    let mut stale_count = 0;

    for issue in &issues {
        if let Ok(updated) = issue.updated_at.parse::<DateTime<Utc>>() {
            let days_since = (now - updated).num_days();
            if days_since > STALE_ISSUE_DAYS {
                stale_count += 1;
            }
        }
    }

    if stale_count > 0 {
        findings.push(
            Finding::new(
                "ISSUE001",
                "issues",
                Severity::Info,
                format!(
                    "{} stale issue(s) with no activity for over {} days",
                    stale_count, STALE_ISSUE_DAYS
                ),
            )
            .with_description(
                "Stale issues may indicate abandoned features, forgotten bugs, or \
                 lack of triage. Regular cleanup improves project visibility and contributor experience.",
            )
            .with_remediation(
                "Review stale issues and close those that are no longer relevant. \
                 Consider using a stale bot (e.g., actions/stale) to automate cleanup.",
            ),
        );
    }

    findings
}

/// ISSUE002: Check for stale PRs (> 30 days without activity)
fn check_stale_prs(provider: &GitHubProvider) -> Vec<Finding> {
    let mut findings = Vec::new();

    let prs = match list_open_prs(provider) {
        Some(prs) => prs,
        None => return findings,
    };

    let now = Utc::now();
    let mut stale_count = 0;

    for pr in &prs {
        if let Ok(updated) = pr.updated_at.parse::<DateTime<Utc>>() {
            let days_since = (now - updated).num_days();
            if days_since > STALE_PR_DAYS {
                stale_count += 1;
            }
        }
    }

    if stale_count > 0 {
        findings.push(
            Finding::new(
                "ISSUE002",
                "issues",
                Severity::Info,
                format!(
                    "{} stale pull request(s) with no activity for over {} days",
                    stale_count, STALE_PR_DAYS
                ),
            )
            .with_description(
                "Stale pull requests can indicate blocked work, insufficient review bandwidth, \
                 or abandoned contributions. They accumulate merge conflicts over time.",
            )
            .with_remediation(
                "Review stale PRs: merge, close, or request updates from authors. \
                 Consider configuring branch protection rules with required reviews.",
            ),
        );
    }

    findings
}

/// ISSUE003: Check for issues without labels
fn check_unlabeled_issues(provider: &GitHubProvider) -> Vec<Finding> {
    let mut findings = Vec::new();

    let output = std::process::Command::new("gh")
        .args([
            "issue",
            "list",
            "--repo",
            &format!("{}/{}", provider.owner(), provider.name()),
            "--state",
            "open",
            "--json",
            "number,title,updatedAt,labels",
            "--limit",
            "100",
        ])
        .output();

    let issues: Vec<Issue> = match output {
        Ok(out) if out.status.success() => serde_json::from_slice(&out.stdout).unwrap_or_default(),
        _ => return findings,
    };

    let unlabeled_count = issues.iter().filter(|i| i.labels.is_empty()).count();

    if unlabeled_count > 0 {
        findings.push(
            Finding::new(
                "ISSUE003",
                "issues",
                Severity::Info,
                format!("{} issue(s) without labels", unlabeled_count),
            )
            .with_description(
                "Issues without labels are harder to triage, filter, and prioritize. \
                 Labels help organize work and provide visibility into issue categories.",
            )
            .with_remediation(
                "Add relevant labels to open issues (e.g., bug, enhancement, documentation). \
                 Consider using GitHub's default label set or creating a custom labeling scheme.",
            ),
        );
    }

    findings
}

/// PR001: Check for PRs without reviewers assigned
fn check_pr_reviewers(provider: &GitHubProvider) -> Vec<Finding> {
    let mut findings = Vec::new();

    let prs = match list_open_prs(provider) {
        Some(prs) => prs,
        None => return findings,
    };

    let no_reviewer_count = prs
        .iter()
        .filter(|pr| {
            !pr.is_draft && pr.review_requests.total_count == 0 && pr.reviews.total_count == 0
        })
        .count();

    if no_reviewer_count > 0 {
        findings.push(
            Finding::new(
                "PR001",
                "issues",
                Severity::Warning,
                format!(
                    "{} pull request(s) without reviewers assigned",
                    no_reviewer_count
                ),
            )
            .with_description(
                "Pull requests without reviewers may bypass code review processes. \
                 Code review is essential for maintaining code quality and knowledge sharing.",
            )
            .with_remediation(
                "Assign reviewers to all open pull requests. Consider configuring CODEOWNERS \
                 to automatically request reviews from the appropriate teams.",
            ),
        );
    }

    findings
}

/// PR002: Check for abandoned draft PRs (> 14 days)
fn check_abandoned_drafts(provider: &GitHubProvider) -> Vec<Finding> {
    let mut findings = Vec::new();

    let prs = match list_open_prs(provider) {
        Some(prs) => prs,
        None => return findings,
    };

    let now = Utc::now();
    let mut abandoned_count = 0;

    for pr in &prs {
        if pr.is_draft {
            if let Ok(updated) = pr.updated_at.parse::<DateTime<Utc>>() {
                let days_since = (now - updated).num_days();
                if days_since > ABANDONED_DRAFT_DAYS {
                    abandoned_count += 1;
                }
            }
        }
    }

    if abandoned_count > 0 {
        findings.push(
            Finding::new(
                "PR002",
                "issues",
                Severity::Info,
                format!(
                    "{} abandoned draft pull request(s) (no activity for over {} days)",
                    abandoned_count, ABANDONED_DRAFT_DAYS
                ),
            )
            .with_description(
                "Draft pull requests with no recent activity may represent abandoned work. \
                 They clutter the PR list and can accumulate merge conflicts.",
            )
            .with_remediation(
                "Review abandoned drafts: continue work, close, or convert to issues for tracking.",
            ),
        );
    }

    findings
}

/// Helper: list open pull requests
fn list_open_prs(provider: &GitHubProvider) -> Option<Vec<PullRequest>> {
    let output = std::process::Command::new("gh")
        .args([
            "pr",
            "list",
            "--repo",
            &format!("{}/{}", provider.owner(), provider.name()),
            "--state",
            "open",
            "--json",
            "number,title,updatedAt,isDraft,reviewRequests,reviews",
            "--limit",
            "100",
        ])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    serde_json::from_slice(&output.stdout).ok()
}

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

    #[test]
    fn test_stale_issue_threshold() {
        assert_eq!(STALE_ISSUE_DAYS, 90);
    }

    #[test]
    fn test_stale_pr_threshold() {
        assert_eq!(STALE_PR_DAYS, 30);
    }

    #[test]
    fn test_abandoned_draft_threshold() {
        assert_eq!(ABANDONED_DRAFT_DAYS, 14);
    }
}