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
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Data structure definitions for topology view

use chrono::{DateTime, Local};

/// Branch status
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BranchStatus {
    /// Current branch (HEAD)
    Active,
    /// Normal branch
    Normal,
    /// Has uncommitted changes (WIP) - reserved for future working tree detection
    #[allow(dead_code)]
    Wip,
    /// Stale (no commits for 30+ days)
    Stale,
    /// Merged
    Merged,
}

impl BranchStatus {
    /// Get display string for the status
    pub fn label(&self) -> &'static str {
        match self {
            Self::Active => "HEAD",
            Self::Normal => "",
            Self::Wip => "WIP",
            Self::Stale => "stale",
            Self::Merged => "merged",
        }
    }

    /// Get color index for the status
    pub fn color_index(&self) -> usize {
        match self {
            Self::Active => 0, // Green
            Self::Normal => 1, // Blue
            Self::Wip => 2,    // Yellow
            Self::Stale => 3,  // Gray
            Self::Merged => 4, // Magenta
        }
    }
}

/// Branch relation information
#[derive(Debug, Clone)]
pub struct BranchRelation {
    /// Base branch name
    pub base: String,
    /// Target branch name
    pub branch: String,
    /// Merge base commit hash
    pub merge_base: String,
    /// Number of commits ahead of base
    pub ahead_count: usize,
    /// Number of commits behind base
    pub behind_count: usize,
    /// Whether the branch is merged
    pub is_merged: bool,
}

impl BranchRelation {
    /// Create a new branch relation
    pub fn new(base: String, branch: String) -> Self {
        Self {
            base,
            branch,
            merge_base: String::new(),
            ahead_count: 0,
            behind_count: 0,
            is_merged: false,
        }
    }

    /// Get status summary
    pub fn summary(&self) -> String {
        if self.is_merged {
            "merged".to_string()
        } else if self.ahead_count == 0 && self.behind_count == 0 {
            "up to date".to_string()
        } else {
            let mut parts = Vec::new();
            if self.ahead_count > 0 {
                parts.push(format!("{} ahead", self.ahead_count));
            }
            if self.behind_count > 0 {
                parts.push(format!("{} behind", self.behind_count));
            }
            parts.join(", ")
        }
    }
}

/// Branch health warning types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HealthWarning {
    /// Stale (no commits for 30+ days)
    Stale,
    /// Long-lived (60+ days old)
    LongLived,
    /// Significantly behind main (50+ commits)
    FarBehind,
    /// Large divergence (both ahead and behind are high)
    LargeDivergence,
}

impl HealthWarning {
    /// Get warning description
    pub fn description(&self) -> &'static str {
        match self {
            Self::Stale => "No activity for 30+ days",
            Self::LongLived => "Branch exists for 60+ days",
            Self::FarBehind => "50+ commits behind main",
            Self::LargeDivergence => "Large divergence from main",
        }
    }

    /// Get warning icon
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Stale => "",
            Self::LongLived => "",
            Self::FarBehind => "",
            Self::LargeDivergence => "",
        }
    }
}

/// Branch health assessment
#[derive(Debug, Clone, Default)]
pub struct BranchHealth {
    /// List of health warnings
    pub warnings: Vec<HealthWarning>,
}

impl BranchHealth {
    /// Create a new health assessment
    pub fn new() -> Self {
        Self {
            warnings: Vec::new(),
        }
    }

    /// Add a warning
    pub fn add_warning(&mut self, warning: HealthWarning) {
        if !self.warnings.contains(&warning) {
            self.warnings.push(warning);
        }
    }

    /// Whether the branch is healthy (no warnings)
    pub fn is_healthy(&self) -> bool {
        self.warnings.is_empty()
    }

    /// Get warning count
    pub fn warning_count(&self) -> usize {
        self.warnings.len()
    }

    /// Get concatenated warning icons
    pub fn warning_icons(&self) -> String {
        self.warnings
            .iter()
            .map(|w| w.icon())
            .collect::<Vec<_>>()
            .join("")
    }
}

/// Branch information for topology view
#[derive(Debug, Clone)]
pub struct TopologyBranch {
    /// Branch name
    pub name: String,
    /// HEAD commit hash
    pub head_hash: String,
    /// Branch status
    pub status: BranchStatus,
    /// Last activity timestamp
    pub last_activity: DateTime<Local>,
    /// Relation with the base branch
    pub relation: Option<BranchRelation>,
    /// Number of commits on the branch
    pub commit_count: usize,
    /// Health assessment
    pub health: BranchHealth,
}

impl TopologyBranch {
    /// Create a new topology branch
    pub fn new(name: String, head_hash: String, last_activity: DateTime<Local>) -> Self {
        Self {
            name,
            head_hash,
            status: BranchStatus::Normal,
            last_activity,
            relation: None,
            commit_count: 0,
            health: BranchHealth::new(),
        }
    }

    /// Set the status
    pub fn with_status(mut self, status: BranchStatus) -> Self {
        self.status = status;
        self
    }

    /// Set the relation information
    pub fn with_relation(mut self, relation: BranchRelation) -> Self {
        self.relation = Some(relation);
        self
    }

    /// Set the commit count
    pub fn with_commit_count(mut self, count: usize) -> Self {
        self.commit_count = count;
        self
    }

    /// Check if stale (last activity older than specified days)
    pub fn is_stale(&self, threshold_days: i64) -> bool {
        let now = Local::now();
        let diff = now.signed_duration_since(self.last_activity);
        diff.num_days() >= threshold_days
    }

    /// Whether the branch is ahead of base
    pub fn is_ahead(&self) -> bool {
        self.relation.as_ref().is_some_and(|r| r.ahead_count > 0)
    }

    /// Whether the branch is behind base
    pub fn is_behind(&self) -> bool {
        self.relation.as_ref().is_some_and(|r| r.behind_count > 0)
    }

    /// Calculate and update health
    pub fn calculate_health(&mut self, config: &TopologyConfig) {
        self.health = BranchHealth::new();

        // Stale warning (default 30 days)
        if self.is_stale(config.stale_threshold_days) {
            self.health.add_warning(HealthWarning::Stale);
        }

        // LongLived warning (60+ days)
        let now = Local::now();
        let age_days = now.signed_duration_since(self.last_activity).num_days();
        if age_days >= config.long_lived_threshold_days {
            self.health.add_warning(HealthWarning::LongLived);
        }

        // FarBehind warning (50+ commits behind)
        if let Some(ref relation) = self.relation {
            if relation.behind_count >= config.far_behind_threshold {
                self.health.add_warning(HealthWarning::FarBehind);
            }

            // LargeDivergence warning (both ahead and behind are high)
            if relation.ahead_count >= config.divergence_threshold
                && relation.behind_count >= config.divergence_threshold
            {
                self.health.add_warning(HealthWarning::LargeDivergence);
            }
        }
    }
}

/// Topology configuration
#[derive(Debug, Clone)]
pub struct TopologyConfig {
    /// Days threshold to consider stale
    pub stale_threshold_days: i64,
    /// Days threshold to consider long-lived
    pub long_lived_threshold_days: i64,
    /// Commit count threshold to consider far behind
    pub far_behind_threshold: usize,
    /// Commit count threshold for large divergence (both ahead/behind)
    pub divergence_threshold: usize,
    /// Maximum number of branches to display
    pub max_branches: usize,
}

impl Default for TopologyConfig {
    fn default() -> Self {
        Self {
            stale_threshold_days: 30,
            long_lived_threshold_days: 60,
            far_behind_threshold: 50,
            divergence_threshold: 20,
            max_branches: 50,
        }
    }
}

/// Overall branch topology
#[derive(Debug, Clone)]
pub struct BranchTopology {
    /// Main branch name
    pub main_branch: String,
    /// List of branches
    pub branches: Vec<TopologyBranch>,
    /// Maximum column count (for layout)
    pub max_column: usize,
    /// Configuration
    pub config: TopologyConfig,
}

impl BranchTopology {
    /// Create a new topology
    pub fn new(main_branch: String) -> Self {
        Self {
            main_branch,
            branches: Vec::new(),
            max_column: 0,
            config: TopologyConfig::default(),
        }
    }

    /// Add a branch
    pub fn add_branch(&mut self, branch: TopologyBranch) {
        self.branches.push(branch);
    }

    /// Get branch count
    pub fn branch_count(&self) -> usize {
        self.branches.len()
    }

    /// Get the active branch
    pub fn active_branch(&self) -> Option<&TopologyBranch> {
        self.branches
            .iter()
            .find(|b| b.status == BranchStatus::Active)
    }

    /// Get the number of stale branches
    pub fn stale_count(&self) -> usize {
        self.branches
            .iter()
            .filter(|b| b.status == BranchStatus::Stale)
            .count()
    }

    /// Get the number of merged branches
    pub fn merged_count(&self) -> usize {
        self.branches
            .iter()
            .filter(|b| b.status == BranchStatus::Merged)
            .count()
    }

    /// Calculate health for all branches
    pub fn calculate_all_health(&mut self) {
        let config = self.config.clone();
        for branch in &mut self.branches {
            // Skip health check for main branch and merged branches
            if branch.name != self.main_branch && branch.status != BranchStatus::Merged {
                branch.calculate_health(&config);
            }
        }
    }

    /// Get the number of unhealthy branches
    pub fn unhealthy_count(&self) -> usize {
        self.branches
            .iter()
            .filter(|b| !b.health.is_healthy())
            .count()
    }

    /// Get the number of branches with a specific warning
    pub fn warning_count(&self, warning: HealthWarning) -> usize {
        self.branches
            .iter()
            .filter(|b| b.health.warnings.contains(&warning))
            .count()
    }
}

// =============================================================================
// Branch recommended actions
// =============================================================================

/// Types of recommended actions
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecommendedAction {
    /// Delete recommended (merged or 60+ days inactive)
    Delete,
    /// Rebase recommended (significantly behind base branch)
    Rebase,
    /// Merge recommended (ahead > 0, merge candidate)
    Merge,
    /// Review recommended (long-lived but active)
    Review,
    /// Keep (no action needed)
    Keep,
}

impl RecommendedAction {
    /// Get display string for the action
    pub fn label(&self) -> &'static str {
        match self {
            Self::Delete => "Delete",
            Self::Rebase => "Rebase",
            Self::Merge => "Merge",
            Self::Review => "Review",
            Self::Keep => "Keep",
        }
    }

    /// Get icon for the action
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Delete => "🗑",
            Self::Rebase => "",
            Self::Merge => "",
            Self::Review => "👁",
            Self::Keep => "",
        }
    }

    /// Get color for the action
    pub fn color(&self) -> &'static str {
        match self {
            Self::Delete => "red",
            Self::Rebase => "yellow",
            Self::Merge => "green",
            Self::Review => "cyan",
            Self::Keep => "white",
        }
    }

    /// Get description
    pub fn description(&self) -> &'static str {
        match self {
            Self::Delete => "Branch is merged or inactive for 60+ days",
            Self::Rebase => "Branch is significantly behind the base branch",
            Self::Merge => "Branch has changes ready to merge",
            Self::Review => "Long-lived branch needs attention",
            Self::Keep => "Branch is in good condition",
        }
    }
}

/// Recommended action per branch
#[derive(Debug, Clone)]
pub struct BranchRecommendation {
    /// Branch name
    pub branch_name: String,
    /// Recommended action
    pub action: RecommendedAction,
    /// Reason for recommendation
    pub reason: String,
    /// Priority (higher is more urgent)
    pub priority: u8,
    /// ahead/behind counts (when applicable)
    pub ahead: usize,
    pub behind: usize,
    /// Days since last activity
    pub days_inactive: i64,
}

impl BranchRecommendation {
    /// Create a new recommendation
    pub fn new(
        branch_name: String,
        action: RecommendedAction,
        reason: impl Into<String>,
        priority: u8,
    ) -> Self {
        Self {
            branch_name,
            action,
            reason: reason.into(),
            priority,
            ahead: 0,
            behind: 0,
            days_inactive: 0,
        }
    }

    /// Set ahead/behind counts
    pub fn with_counts(mut self, ahead: usize, behind: usize) -> Self {
        self.ahead = ahead;
        self.behind = behind;
        self
    }

    /// Set days of inactivity
    pub fn with_days_inactive(mut self, days: i64) -> Self {
        self.days_inactive = days;
        self
    }
}

/// Branch recommendation analysis result
#[derive(Debug, Clone, Default)]
pub struct BranchRecommendations {
    /// List of recommendations (sorted by priority)
    pub recommendations: Vec<BranchRecommendation>,
    /// Number of branches recommended for deletion
    pub delete_count: usize,
    /// Number of branches recommended for rebase
    pub rebase_count: usize,
    /// Number of branches recommended for merge
    pub merge_count: usize,
    /// Number of branches recommended for review
    pub review_count: usize,
    /// Total number of branches analyzed
    pub total_branches: usize,
}

impl BranchRecommendations {
    /// Create a new recommendation result
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a recommendation
    pub fn add(&mut self, recommendation: BranchRecommendation) {
        match recommendation.action {
            RecommendedAction::Delete => self.delete_count += 1,
            RecommendedAction::Rebase => self.rebase_count += 1,
            RecommendedAction::Merge => self.merge_count += 1,
            RecommendedAction::Review => self.review_count += 1,
            RecommendedAction::Keep => {}
        }
        self.recommendations.push(recommendation);
    }

    /// Sort by priority
    pub fn sort_by_priority(&mut self) {
        self.recommendations
            .sort_by(|a, b| b.priority.cmp(&a.priority));
    }

    /// Get recommendations for a specific action
    pub fn by_action(&self, action: RecommendedAction) -> Vec<&BranchRecommendation> {
        self.recommendations
            .iter()
            .filter(|r| r.action == action)
            .collect()
    }

    /// Get list of branch names recommended for deletion
    pub fn deletable_branches(&self) -> Vec<&str> {
        self.recommendations
            .iter()
            .filter(|r| r.action == RecommendedAction::Delete)
            .map(|r| r.branch_name.as_str())
            .collect()
    }

    /// Get recommendation by branch name
    pub fn get_recommendation(&self, branch_name: &str) -> Option<&BranchRecommendation> {
        self.recommendations
            .iter()
            .find(|r| r.branch_name == branch_name)
    }
}

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

    fn create_test_branch(name: &str) -> TopologyBranch {
        TopologyBranch::new(name.to_string(), "abc1234".to_string(), Local::now())
    }

    #[test]
    fn test_branch_status_label() {
        assert_eq!(BranchStatus::Active.label(), "HEAD");
        assert_eq!(BranchStatus::Normal.label(), "");
        assert_eq!(BranchStatus::Stale.label(), "stale");
        assert_eq!(BranchStatus::Merged.label(), "merged");
    }

    #[test]
    fn test_branch_relation_summary_merged() {
        let mut relation = BranchRelation::new("main".to_string(), "feature".to_string());
        relation.is_merged = true;
        assert_eq!(relation.summary(), "merged");
    }

    #[test]
    fn test_branch_relation_summary_up_to_date() {
        let relation = BranchRelation::new("main".to_string(), "feature".to_string());
        assert_eq!(relation.summary(), "up to date");
    }

    #[test]
    fn test_branch_relation_summary_ahead() {
        let mut relation = BranchRelation::new("main".to_string(), "feature".to_string());
        relation.ahead_count = 3;
        assert_eq!(relation.summary(), "3 ahead");
    }

    #[test]
    fn test_branch_relation_summary_behind() {
        let mut relation = BranchRelation::new("main".to_string(), "feature".to_string());
        relation.behind_count = 2;
        assert_eq!(relation.summary(), "2 behind");
    }

    #[test]
    fn test_branch_relation_summary_ahead_and_behind() {
        let mut relation = BranchRelation::new("main".to_string(), "feature".to_string());
        relation.ahead_count = 3;
        relation.behind_count = 2;
        assert_eq!(relation.summary(), "3 ahead, 2 behind");
    }

    #[test]
    fn test_topology_branch_new() {
        let branch = create_test_branch("feature");
        assert_eq!(branch.name, "feature");
        assert_eq!(branch.status, BranchStatus::Normal);
    }

    #[test]
    fn test_topology_branch_with_status() {
        let branch = create_test_branch("feature").with_status(BranchStatus::Active);
        assert_eq!(branch.status, BranchStatus::Active);
    }

    #[test]
    fn test_topology_branch_is_ahead() {
        let mut relation = BranchRelation::new("main".to_string(), "feature".to_string());
        relation.ahead_count = 3;
        let branch = create_test_branch("feature").with_relation(relation);
        assert!(branch.is_ahead());
    }

    #[test]
    fn test_topology_branch_is_behind() {
        let mut relation = BranchRelation::new("main".to_string(), "feature".to_string());
        relation.behind_count = 2;
        let branch = create_test_branch("feature").with_relation(relation);
        assert!(branch.is_behind());
    }

    #[test]
    fn test_branch_topology_new() {
        let topology = BranchTopology::new("main".to_string());
        assert_eq!(topology.main_branch, "main");
        assert_eq!(topology.branch_count(), 0);
    }

    #[test]
    fn test_branch_topology_add_branch() {
        let mut topology = BranchTopology::new("main".to_string());
        topology.add_branch(create_test_branch("feature"));
        assert_eq!(topology.branch_count(), 1);
    }

    #[test]
    fn test_branch_topology_active_branch() {
        let mut topology = BranchTopology::new("main".to_string());
        topology.add_branch(create_test_branch("feature"));
        topology.add_branch(create_test_branch("main").with_status(BranchStatus::Active));

        let active = topology.active_branch();
        assert!(active.is_some());
        assert_eq!(active.unwrap().name, "main");
    }

    #[test]
    fn test_branch_topology_stale_count() {
        let mut topology = BranchTopology::new("main".to_string());
        topology.add_branch(create_test_branch("feature1"));
        topology.add_branch(create_test_branch("feature2").with_status(BranchStatus::Stale));
        topology.add_branch(create_test_branch("feature3").with_status(BranchStatus::Stale));

        assert_eq!(topology.stale_count(), 2);
    }

    #[test]
    fn test_branch_topology_merged_count() {
        let mut topology = BranchTopology::new("main".to_string());
        topology.add_branch(create_test_branch("feature1"));
        topology.add_branch(create_test_branch("feature2").with_status(BranchStatus::Merged));

        assert_eq!(topology.merged_count(), 1);
    }
}