gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
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
//! Commit suggestion engine
//!
//! Generate commit message suggestions from staged files

use crate::app::CommitType;
use crate::git::FileStatus;

/// Commit suggestion
#[derive(Debug, Clone)]
pub struct CommitSuggestion {
    /// Commit type
    pub commit_type: CommitType,
    /// Scope (optional)
    pub scope: Option<String>,
    /// Message body
    pub message: String,
    /// Confidence (0.0-1.0)
    pub confidence: f32,
}

impl CommitSuggestion {
    /// Generate a full commit message
    pub fn full_message(&self) -> String {
        match &self.scope {
            Some(scope) => format!("{}({}): {}", self.commit_type.name(), scope, self.message),
            None => format!("{}: {}", self.commit_type.name(), self.message),
        }
    }
}

/// Generate suggestions from staged files
///
/// Generate up to 3 suggestions, sorted by confidence
pub fn generate_suggestions(statuses: &[FileStatus]) -> Vec<CommitSuggestion> {
    if statuses.is_empty() {
        return Vec::new();
    }

    let paths: Vec<&str> = statuses.iter().map(|s| s.path.as_str()).collect();
    let status_refs: Vec<&FileStatus> = statuses.iter().collect();
    let mut suggestions = Vec::new();

    // 1. Infer type from file paths and diff stats
    let type_counts = count_inferred_types_with_stats(&paths, &status_refs);

    // Generate suggestions from the most common type
    let mut type_vec: Vec<_> = type_counts.into_iter().collect();
    type_vec.sort_by(|a, b| b.1.cmp(&a.1));

    for (commit_type, count) in type_vec.iter().take(3) {
        let confidence = *count as f32 / paths.len() as f32;
        if confidence < 0.2 {
            continue;
        }

        let scope = infer_scope_from_paths(&paths);
        let message = generate_message(*commit_type, scope.as_deref(), &paths);

        suggestions.push(CommitSuggestion {
            commit_type: *commit_type,
            scope,
            message,
            confidence,
        });
    }

    // 2. Add generic suggestion if none were generated
    if suggestions.is_empty() {
        let scope = infer_scope_from_paths(&paths);
        let message = generate_message(CommitType::Chore, scope.as_deref(), &paths);
        suggestions.push(CommitSuggestion {
            commit_type: CommitType::Chore,
            scope,
            message,
            confidence: 0.3,
        });
    }

    // Sort by confidence (with NaN handling)
    suggestions.sort_by(|a, b| {
        b.confidence
            .partial_cmp(&a.confidence)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    // Maximum 3 suggestions
    suggestions.truncate(3);

    suggestions
}

/// Infer commit type from file path
fn infer_type_from_path(path: &str) -> Option<CommitType> {
    let path_lower = path.to_lowercase();
    let file_name = path_lower.split('/').next_back().unwrap_or(&path_lower);

    // Test files
    if path_lower.contains("/tests/")
        || path_lower.starts_with("tests/")
        || file_name.contains("_test.")
        || file_name.contains(".test.")
        || file_name.ends_with("_test.rs")
        || file_name.ends_with("_test.go")
        || file_name.ends_with("_test.py")
        || file_name.ends_with(".spec.js")
        || file_name.ends_with(".spec.ts")
        || file_name.starts_with("test_")
    {
        return Some(CommitType::Test);
    }

    // Documentation
    if path_lower.starts_with("readme")
        || path_lower.ends_with(".md")
        || path_lower.contains("/docs/")
        || path_lower.starts_with("docs/")
        || path_lower.contains("license")
        || path_lower.contains("changelog")
    {
        return Some(CommitType::Docs);
    }

    // Config and dependency files (root-level config files only)
    if path_lower == "cargo.toml"
        || path_lower == "package.json"
        || path_lower == "go.mod"
        || path_lower == "requirements.txt"
        || path_lower == "pyproject.toml"
        || path_lower == "tsconfig.json"
        || path_lower == "jest.config.json"
        || path_lower == "eslint.config.json"
        || path_lower == ".eslintrc.json"
        || path_lower == ".prettierrc"
        || path_lower == ".prettierrc.json"
        || path_lower.ends_with(".lock")
        || path_lower.starts_with(".github/")
        || path_lower == ".gitignore"
        || path_lower == ".dockerignore"
        || path_lower == "dockerfile"
        || path_lower == "docker-compose.yml"
        || path_lower == "docker-compose.yaml"
        || path_lower == "makefile"
        || path_lower.ends_with(".yml")
        || path_lower.ends_with(".yaml")
    {
        return Some(CommitType::Chore);
    }

    // Style-related files
    if path_lower.ends_with(".css")
        || path_lower.ends_with(".scss")
        || path_lower.ends_with(".sass")
        || path_lower.ends_with(".less")
    {
        return Some(CommitType::Style);
    }

    None
}

/// Count occurrences of each inferred type with diff stat awareness
///
/// When statuses are provided, uses the add/modify/delete ratio to improve inference:
/// - All new files -> feat
/// - More deletions than additions -> refactor or fix
/// - All deletions -> refactor
fn count_inferred_types_with_stats(
    paths: &[&str],
    statuses: &[&FileStatus],
) -> std::collections::HashMap<CommitType, usize> {
    use crate::git::FileStatusKind;
    let mut counts = std::collections::HashMap::new();

    for path in paths {
        if let Some(commit_type) = infer_type_from_path(path) {
            *counts.entry(commit_type).or_insert(0) += 1;
        }
    }

    // If no explicit type found, infer from file operation patterns
    if counts.is_empty() && !statuses.is_empty() {
        let new_count = statuses
            .iter()
            .filter(|s| s.kind == FileStatusKind::StagedNew)
            .count();
        let deleted_count = statuses
            .iter()
            .filter(|s| s.kind == FileStatusKind::StagedDeleted)
            .count();
        let modified_count = statuses
            .iter()
            .filter(|s| s.kind == FileStatusKind::StagedModified)
            .count();
        let total = statuses.len();

        if new_count == total {
            // All files are new -> feat
            counts.insert(CommitType::Feat, total);
        } else if deleted_count == total {
            // All files are deleted -> refactor
            counts.insert(CommitType::Refactor, total);
        } else if deleted_count > new_count && deleted_count > modified_count {
            // More deletions than additions -> refactor
            counts.insert(CommitType::Refactor, total);
        } else if modified_count > 0 && new_count == 0 && deleted_count == 0 {
            // Only modifications, no new or deleted -> could be fix or refactor
            counts.insert(CommitType::Fix, modified_count);
            // Also suggest feat as alternative
            if modified_count > 1 {
                counts.insert(CommitType::Refactor, modified_count / 2);
            }
        } else if new_count > deleted_count {
            // More additions -> feat
            counts.insert(CommitType::Feat, total);
        } else {
            // Default to feat
            counts.insert(CommitType::Feat, total);
        }
    } else if counts.is_empty() {
        // No statuses provided, default to feat (original behavior)
        counts.insert(CommitType::Feat, paths.len());
    }

    counts
}

/// Infer scope from common directories
pub fn infer_scope_from_paths(paths: &[&str]) -> Option<String> {
    if paths.is_empty() {
        return None;
    }

    // Find common directory
    let first_parts: Vec<&str> = paths[0].split('/').collect();
    if first_parts.len() < 2 {
        return None;
    }

    // Use the directory directly under src/ as scope
    let scope_candidates: Vec<Option<&str>> = paths
        .iter()
        .map(|p| {
            let parts: Vec<&str> = p.split('/').collect();
            if parts.len() >= 2 && parts[0] == "src" {
                Some(parts[1])
            } else if parts.len() >= 2 {
                Some(parts[0])
            } else {
                None
            }
        })
        .collect();

    // Only return if all files share the same scope
    let first_scope = scope_candidates.first().and_then(|s| *s)?;
    if scope_candidates
        .iter()
        .all(|s| s.map(|x| x == first_scope).unwrap_or(false))
    {
        // Do not use file names as scope
        if !first_scope.contains('.') {
            return Some(first_scope.to_string());
        }
    }

    None
}

/// Auto-generate commit message
fn generate_message(commit_type: CommitType, scope: Option<&str>, paths: &[&str]) -> String {
    let file_count = paths.len();

    match commit_type {
        CommitType::Test => {
            if file_count == 1 {
                format!("add tests for {}", extract_module_name(paths[0]))
            } else {
                "add tests".to_string()
            }
        }
        CommitType::Docs => {
            if file_count == 1 && paths[0].to_lowercase().starts_with("readme") {
                "update README".to_string()
            } else if file_count == 1 {
                format!("update {}", extract_file_name(paths[0]))
            } else {
                "update documentation".to_string()
            }
        }
        CommitType::Chore => {
            if file_count == 1 {
                format!("update {}", extract_file_name(paths[0]))
            } else {
                "update configuration".to_string()
            }
        }
        CommitType::Style => "update styles".to_string(),
        CommitType::Feat => {
            if let Some(s) = scope {
                format!("add {} feature", s)
            } else if file_count == 1 {
                format!("add {}", extract_module_name(paths[0]))
            } else {
                "add new feature".to_string()
            }
        }
        CommitType::Fix => {
            if let Some(s) = scope {
                format!("fix {} issue", s)
            } else {
                "fix issue".to_string()
            }
        }
        CommitType::Refactor => {
            if let Some(s) = scope {
                format!("refactor {}", s)
            } else {
                "refactor code".to_string()
            }
        }
        CommitType::Perf => {
            if let Some(s) = scope {
                format!("improve {} performance", s)
            } else {
                "improve performance".to_string()
            }
        }
    }
}

/// Extract module name from path (strip extension)
fn extract_module_name(path: &str) -> String {
    let file_name = path.split('/').next_back().unwrap_or(path);
    file_name
        .strip_suffix(".rs")
        .or_else(|| file_name.strip_suffix(".go"))
        .or_else(|| file_name.strip_suffix(".py"))
        .or_else(|| file_name.strip_suffix(".js"))
        .or_else(|| file_name.strip_suffix(".ts"))
        .or_else(|| file_name.strip_suffix(".tsx"))
        .or_else(|| file_name.strip_suffix(".jsx"))
        .unwrap_or(file_name)
        .to_string()
}

/// Extract file name from path
fn extract_file_name(path: &str) -> String {
    path.split('/').next_back().unwrap_or(path).to_string()
}

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

    fn create_staged_status(path: &str) -> FileStatus {
        FileStatus {
            path: path.to_string(),
            kind: FileStatusKind::StagedNew,
        }
    }

    #[test]
    fn test_infer_type_from_test_file() {
        assert_eq!(
            infer_type_from_path("src/app_test.rs"),
            Some(CommitType::Test)
        );
        assert_eq!(
            infer_type_from_path("tests/integration_test.rs"),
            Some(CommitType::Test)
        );
        assert_eq!(
            infer_type_from_path("src/utils.spec.js"),
            Some(CommitType::Test)
        );
    }

    #[test]
    fn test_infer_type_from_readme() {
        assert_eq!(infer_type_from_path("README.md"), Some(CommitType::Docs));
        assert_eq!(infer_type_from_path("readme.txt"), Some(CommitType::Docs));
    }

    #[test]
    fn test_infer_type_from_docs() {
        assert_eq!(infer_type_from_path("docs/api.md"), Some(CommitType::Docs));
        assert_eq!(infer_type_from_path("CHANGELOG.md"), Some(CommitType::Docs));
    }

    #[test]
    fn test_infer_type_from_cargo_toml() {
        assert_eq!(infer_type_from_path("Cargo.toml"), Some(CommitType::Chore));
        // Also handles lowercase
        assert_eq!(infer_type_from_path("cargo.toml"), Some(CommitType::Chore));
    }

    #[test]
    fn test_infer_type_from_package_json() {
        assert_eq!(
            infer_type_from_path("package.json"),
            Some(CommitType::Chore)
        );
    }

    #[test]
    fn test_infer_type_from_regular_json_is_none() {
        // Regular .json files return None (defaults to feat)
        assert_eq!(infer_type_from_path("src/data.json"), None);
        assert_eq!(infer_type_from_path("config/settings.json"), None);
    }

    #[test]
    fn test_infer_type_from_regular_toml_is_none() {
        // Regular .toml files return None
        assert_eq!(infer_type_from_path("src/config.toml"), None);
    }

    #[test]
    fn test_infer_type_from_github_workflow() {
        assert_eq!(
            infer_type_from_path(".github/workflows/ci.yml"),
            Some(CommitType::Chore)
        );
    }

    #[test]
    fn test_infer_type_from_css() {
        assert_eq!(
            infer_type_from_path("styles/main.css"),
            Some(CommitType::Style)
        );
        assert_eq!(infer_type_from_path("app.scss"), Some(CommitType::Style));
    }

    #[test]
    fn test_infer_type_from_regular_source() {
        // Regular source files return None (handled by default logic)
        assert_eq!(infer_type_from_path("src/main.rs"), None);
        assert_eq!(infer_type_from_path("src/app.rs"), None);
    }

    #[test]
    fn test_infer_scope_from_src_auth() {
        let paths = vec!["src/auth/login.rs", "src/auth/logout.rs"];
        assert_eq!(infer_scope_from_paths(&paths), Some("auth".to_string()));
    }

    #[test]
    fn test_infer_scope_from_src_tui() {
        let paths = vec!["src/tui/ui.rs", "src/tui/render.rs"];
        assert_eq!(infer_scope_from_paths(&paths), Some("tui".to_string()));
    }

    #[test]
    fn test_infer_scope_mixed_paths() {
        let paths = vec!["src/auth/login.rs", "src/tui/ui.rs"];
        // Returns None for different scopes
        assert_eq!(infer_scope_from_paths(&paths), None);
    }

    #[test]
    fn test_infer_scope_single_file() {
        let paths = vec!["src/main.rs"];
        // Returns None for single file directly under src/ (main.rs is a file name)
        assert_eq!(infer_scope_from_paths(&paths), None);
    }

    #[test]
    fn test_generate_suggestions_empty() {
        let statuses: Vec<FileStatus> = vec![];
        let suggestions = generate_suggestions(&statuses);
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_generate_suggestions_test_files() {
        let statuses = vec![
            create_staged_status("src/app_test.rs"),
            create_staged_status("src/utils_test.rs"),
        ];
        let suggestions = generate_suggestions(&statuses);
        assert!(!suggestions.is_empty());
        assert_eq!(suggestions[0].commit_type, CommitType::Test);
    }

    #[test]
    fn test_generate_suggestions_readme() {
        let statuses = vec![create_staged_status("README.md")];
        let suggestions = generate_suggestions(&statuses);
        assert!(!suggestions.is_empty());
        assert_eq!(suggestions[0].commit_type, CommitType::Docs);
        assert!(suggestions[0].message.contains("README"));
    }

    #[test]
    fn test_generate_suggestions_cargo_toml() {
        let statuses = vec![create_staged_status("Cargo.toml")];
        let suggestions = generate_suggestions(&statuses);
        assert!(!suggestions.is_empty());
        assert_eq!(suggestions[0].commit_type, CommitType::Chore);
    }

    #[test]
    fn test_generate_suggestions_max_three() {
        // Maximum 3 suggestions even with many files
        let statuses = vec![
            create_staged_status("src/a.rs"),
            create_staged_status("src/b.rs"),
            create_staged_status("src/c.rs"),
            create_staged_status("src/d.rs"),
            create_staged_status("src/e.rs"),
        ];
        let suggestions = generate_suggestions(&statuses);
        assert!(suggestions.len() <= 3);
    }

    #[test]
    fn test_commit_suggestion_full_message_with_scope() {
        let suggestion = CommitSuggestion {
            commit_type: CommitType::Feat,
            scope: Some("auth".to_string()),
            message: "add login".to_string(),
            confidence: 0.8,
        };
        assert_eq!(suggestion.full_message(), "feat(auth): add login");
    }

    #[test]
    fn test_commit_suggestion_full_message_without_scope() {
        let suggestion = CommitSuggestion {
            commit_type: CommitType::Fix,
            scope: None,
            message: "fix bug".to_string(),
            confidence: 0.7,
        };
        assert_eq!(suggestion.full_message(), "fix: fix bug");
    }

    #[test]
    fn test_extract_module_name() {
        assert_eq!(extract_module_name("src/app.rs"), "app");
        assert_eq!(extract_module_name("main.go"), "main");
        assert_eq!(extract_module_name("utils.py"), "utils");
    }

    #[test]
    fn test_extract_file_name() {
        assert_eq!(extract_file_name("src/app.rs"), "app.rs");
        assert_eq!(extract_file_name("Cargo.toml"), "Cargo.toml");
    }
}