omni-dev 0.24.0

A powerful Git commit message analysis and amendment toolkit
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
423
424
425
426
//! Branch analysis and work pattern detection.

use std::str::FromStr;
use std::sync::LazyLock;

use anyhow::Result;
use regex::Regex;

use crate::data::context::{BranchContext, WorkType};

/// Maximum branch name length considered characteristic of GitHub Flow (short, flat names).
const GITHUB_FLOW_MAX_BRANCH_LEN: usize = 50;

/// Branch naming pattern analyzer.
pub struct BranchAnalyzer;

impl BranchAnalyzer {
    /// Analyzes a branch name and extracts context information.
    pub fn analyze(branch_name: &str) -> Result<BranchContext> {
        let mut context = BranchContext::default();

        // Parse different branch naming conventions
        if let Some(captures) = STANDARD_BRANCH_PATTERN.captures(branch_name) {
            // Standard pattern: type/scope/description or type/description
            context.work_type = captures
                .name("type")
                .map(|m| WorkType::from_str(m.as_str()))
                .transpose()?
                .unwrap_or(WorkType::Unknown);

            context.scope = captures.name("scope").map(|m| m.as_str().to_string());

            context.description = captures
                .name("desc")
                .map(|m| m.as_str().replace(['-', '_'], " "))
                .unwrap_or_default();
        } else if let Some(captures) = TICKET_BRANCH_PATTERN.captures(branch_name) {
            // Ticket-based pattern: JIRA-123-description, issue-456-description
            context.ticket_id = captures.name("ticket").map(|m| m.as_str().to_string());
            context.description = captures
                .name("desc")
                .map(|m| m.as_str().replace(['-', '_'], " "))
                .unwrap_or_default();

            // Infer work type from description or ticket prefix
            context.work_type = infer_work_type_from_description(&context.description);
        } else if let Some(captures) = USER_BRANCH_PATTERN.captures(branch_name) {
            // User-based pattern: username/feature-description
            context.description = captures
                .name("desc")
                .map(|m| m.as_str().replace(['-', '_'], " "))
                .unwrap_or_default();

            context.work_type = infer_work_type_from_description(&context.description);
        } else {
            // Fallback: try to extract any meaningful information
            context.description = branch_name.replace(['-', '_'], " ");
            context.work_type = infer_work_type_from_description(&context.description);
        }

        // Extract ticket references from anywhere in the branch name
        context.ticket_id = context
            .ticket_id
            .or_else(|| extract_ticket_references(branch_name));

        // Determine if this is a feature branch
        context.is_feature_branch = matches!(
            context.work_type,
            WorkType::Feature | WorkType::Fix | WorkType::Refactor
        );

        // Clean up description
        context.description = clean_description(&context.description);

        Ok(context)
    }

    /// Analyzes multiple branch names to understand the branching strategy.
    pub fn analyze_branching_strategy(branches: &[String]) -> BranchingStrategy {
        let mut has_gitflow = false;
        let mut has_github_flow = false;
        let mut has_conventional = false;

        for branch in branches {
            if branch.starts_with("feature/")
                || branch.starts_with("release/")
                || branch.starts_with("hotfix/")
            {
                has_gitflow = true;
            }
            if branch.contains("feat/") || branch.contains("fix/") || branch.contains("docs/") {
                has_conventional = true;
            }
            if branch.len() < GITHUB_FLOW_MAX_BRANCH_LEN && !branch.contains('/') {
                has_github_flow = true;
            }
        }

        if has_gitflow {
            BranchingStrategy::GitFlow
        } else if has_conventional {
            BranchingStrategy::ConventionalCommits
        } else if has_github_flow {
            BranchingStrategy::GitHubFlow
        } else {
            BranchingStrategy::Unknown
        }
    }
}

/// Branching strategy patterns.
#[derive(Debug, Clone)]
pub enum BranchingStrategy {
    /// Git Flow branching model with feature/, release/, hotfix/ branches.
    GitFlow,
    /// GitHub Flow with simple feature branches and main branch.
    GitHubFlow,
    /// Conventional commits with type-based branch naming.
    ConventionalCommits,
    /// Unknown or mixed branching strategy.
    Unknown,
}

// Branch naming pattern regexes
#[allow(clippy::unwrap_used)] // Compile-time constant regex pattern
static STANDARD_BRANCH_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?P<type>feature|feat|fix|bugfix|docs?|refactor|chore|test|ci|build|perf|hotfix|release)/(?:(?P<scope>[^/]+)/)?(?P<desc>.+)$").unwrap()
});

#[allow(clippy::unwrap_used)] // Compile-time constant regex pattern
static TICKET_BRANCH_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?P<ticket>[A-Z]+-\d+|issue-\d+|#\d+)-(?P<desc>.+)$").unwrap());

#[allow(clippy::unwrap_used)] // Compile-time constant regex pattern
static USER_BRANCH_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9_-]+/(?P<desc>.+)$").unwrap());

#[allow(clippy::unwrap_used)] // Compile-time constant regex pattern
static TICKET_REFERENCE_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"([A-Z]+-\d+|#\d+|issue-\d+)").unwrap());

/// Extracts ticket references from a branch name.
fn extract_ticket_references(branch_name: &str) -> Option<String> {
    TICKET_REFERENCE_PATTERN
        .find(branch_name)
        .map(|m| m.as_str().to_string())
}

/// Infers the work type from description keywords.
fn infer_work_type_from_description(description: &str) -> WorkType {
    let desc_lower = description.to_lowercase();

    if desc_lower.contains("fix") || desc_lower.contains("bug") || desc_lower.contains("issue") {
        WorkType::Fix
    } else if desc_lower.contains("doc") || desc_lower.contains("readme") {
        WorkType::Docs
    } else if desc_lower.contains("test") {
        WorkType::Test
    } else if desc_lower.contains("refactor") || desc_lower.contains("cleanup") {
        WorkType::Refactor
    } else if desc_lower.contains("build") || desc_lower.contains("config") {
        WorkType::Build
    } else if desc_lower.contains("ci") || desc_lower.contains("workflow") {
        WorkType::Ci
    } else if desc_lower.contains("perf") || desc_lower.contains("performance") {
        WorkType::Perf
    } else if desc_lower.contains("chore") || desc_lower.contains("maintenance") {
        WorkType::Chore
    } else {
        // Default to feature for most other cases
        WorkType::Feature
    }
}

/// Cleans up and normalizes description text.
fn clean_description(description: &str) -> String {
    let mut cleaned = description.trim().to_string();

    // Remove common prefixes
    let prefixes = [
        "add ",
        "implement ",
        "create ",
        "update ",
        "fix ",
        "remove ",
    ];
    for prefix in &prefixes {
        if cleaned.to_lowercase().starts_with(prefix) {
            cleaned = cleaned[prefix.len()..].to_string();
            break;
        }
    }

    // Ensure proper capitalization
    if let Some(first_char) = cleaned.chars().next() {
        cleaned = first_char.to_uppercase().collect::<String>() + &cleaned[first_char.len_utf8()..];
    }

    cleaned
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::context::WorkType;

    // ── BranchAnalyzer::analyze ──────────────────────────────────────

    #[test]
    fn standard_branch_feat_with_scope() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("feat/auth/add-login")?;
        assert!(matches!(ctx.work_type, WorkType::Feature));
        assert_eq!(ctx.scope, Some("auth".to_string()));
        assert!(ctx.is_feature_branch);
        Ok(())
    }

    #[test]
    fn standard_branch_fix_no_scope() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("fix/crash-on-startup")?;
        assert!(matches!(ctx.work_type, WorkType::Fix));
        assert!(ctx.scope.is_none());
        assert!(ctx.is_feature_branch);
        Ok(())
    }

    #[test]
    fn standard_branch_refactor() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("refactor/cleanup-modules")?;
        assert!(matches!(ctx.work_type, WorkType::Refactor));
        assert!(ctx.is_feature_branch);
        Ok(())
    }

    #[test]
    fn standard_branch_docs() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("docs/update-readme")?;
        assert!(matches!(ctx.work_type, WorkType::Docs));
        assert!(!ctx.is_feature_branch); // Docs is not a feature branch
        Ok(())
    }

    #[test]
    fn ticket_branch_jira() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("PROJ-123-add-feature")?;
        assert_eq!(ctx.ticket_id, Some("PROJ-123".to_string()));
        Ok(())
    }

    #[test]
    fn ticket_branch_issue() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("issue-456-fix-bug")?;
        assert_eq!(ctx.ticket_id, Some("issue-456".to_string()));
        assert!(matches!(ctx.work_type, WorkType::Fix));
        Ok(())
    }

    #[test]
    fn user_branch() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("johndoe/add-dark-mode")?;
        assert!(matches!(ctx.work_type, WorkType::Feature));
        Ok(())
    }

    #[test]
    fn simple_branch_name() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("add-login-page")?;
        assert!(matches!(ctx.work_type, WorkType::Feature));
        Ok(())
    }

    #[test]
    fn main_branch() -> anyhow::Result<()> {
        let ctx = BranchAnalyzer::analyze("main")?;
        // "main" has no type keywords → defaults to Feature via infer_work_type_from_description
        // but is_feature_branch is set based on work_type
        assert!(matches!(ctx.work_type, WorkType::Feature));
        Ok(())
    }

    // ── analyze_branching_strategy ───────────────────────────────────

    #[test]
    fn gitflow_branches() {
        let branches: Vec<String> = vec![
            "feature/add-auth".to_string(),
            "release/1.0".to_string(),
            "main".to_string(),
        ];
        assert!(matches!(
            BranchAnalyzer::analyze_branching_strategy(&branches),
            BranchingStrategy::GitFlow
        ));
    }

    #[test]
    fn conventional_branches() {
        let branches: Vec<String> = vec!["feat/add-auth".to_string(), "fix/crash".to_string()];
        assert!(matches!(
            BranchAnalyzer::analyze_branching_strategy(&branches),
            BranchingStrategy::ConventionalCommits
        ));
    }

    #[test]
    fn github_flow_branches() {
        let branches: Vec<String> = vec!["short-name".to_string(), "another-branch".to_string()];
        assert!(matches!(
            BranchAnalyzer::analyze_branching_strategy(&branches),
            BranchingStrategy::GitHubFlow
        ));
    }

    #[test]
    fn empty_branches_unknown() {
        assert!(matches!(
            BranchAnalyzer::analyze_branching_strategy(&[]),
            BranchingStrategy::Unknown
        ));
    }

    // ── infer_work_type_from_description ─────────────────────────────

    #[test]
    fn infer_fix_keywords() {
        assert!(matches!(
            infer_work_type_from_description("fix login bug"),
            WorkType::Fix
        ));
        assert!(matches!(
            infer_work_type_from_description("resolve issue"),
            WorkType::Fix
        ));
    }

    #[test]
    fn infer_various_types() {
        assert!(matches!(
            infer_work_type_from_description("update docs"),
            WorkType::Docs
        ));
        assert!(matches!(
            infer_work_type_from_description("add test cases"),
            WorkType::Test
        ));
        assert!(matches!(
            infer_work_type_from_description("refactor modules"),
            WorkType::Refactor
        ));
        assert!(matches!(
            infer_work_type_from_description("ci pipeline"),
            WorkType::Ci
        ));
        assert!(matches!(
            infer_work_type_from_description("build config"),
            WorkType::Build
        ));
        assert!(matches!(
            infer_work_type_from_description("performance tuning"),
            WorkType::Perf
        ));
        assert!(matches!(
            infer_work_type_from_description("chore maintenance"),
            WorkType::Chore
        ));
    }

    #[test]
    fn infer_default_feature() {
        assert!(matches!(
            infer_work_type_from_description("add login page"),
            WorkType::Feature
        ));
    }

    // ── clean_description ────────────────────────────────────────────

    #[test]
    fn clean_removes_prefixes() {
        assert_eq!(clean_description("add login page"), "Login page");
        assert_eq!(clean_description("implement auth"), "Auth");
        assert_eq!(clean_description("fix crash"), "Crash");
    }

    #[test]
    fn clean_capitalizes() {
        assert_eq!(clean_description("some description"), "Some description");
    }

    #[test]
    fn clean_trims_whitespace() {
        assert_eq!(clean_description("  hello  "), "Hello");
    }

    // ── extract_ticket_references ────────────────────────────────────

    #[test]
    fn extract_jira_ticket() {
        assert_eq!(
            extract_ticket_references("PROJ-123-some-work"),
            Some("PROJ-123".to_string())
        );
    }

    #[test]
    fn extract_issue_reference() {
        assert_eq!(
            extract_ticket_references("issue-456-fix"),
            Some("issue-456".to_string())
        );
    }

    #[test]
    fn extract_hash_reference() {
        assert_eq!(
            extract_ticket_references("work-on-#789"),
            Some("#789".to_string())
        );
    }

    #[test]
    fn no_ticket_reference() {
        assert_eq!(extract_ticket_references("plain-branch-name"), None);
    }
}