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
//! Branch topology analysis

use anyhow::{Context, Result};
use chrono::{Local, TimeZone};
use git2::Repository;

use super::types::{
    BranchRecommendation, BranchRecommendations, BranchRelation, BranchStatus, BranchTopology,
    RecommendedAction, TopologyBranch, TopologyConfig,
};

const GIT_SHORT_HASH_LEN: usize = 7;

// Recommendation priorities
const PRIORITY_MERGED: u8 = 90;
const PRIORITY_LONG_STALE: u8 = 80;
const PRIORITY_FAR_BEHIND: u8 = 70;
const PRIORITY_LARGE_DIVERGENCE: u8 = 65;
const PRIORITY_MERGE_CANDIDATE: u8 = 60;
const PRIORITY_REVIEW: u8 = 50;
const PRIORITY_KEEP: u8 = 10;

// Merge candidate threshold
const MERGE_CANDIDATE_MAX_BEHIND: usize = 10;

/// Perform topology analysis
pub fn analyze_topology(config: &TopologyConfig) -> Result<BranchTopology> {
    let repo = Repository::discover(".").context("Gitリポジトリが見つかりません")?;
    analyze_topology_from_repo(&repo, config)
}

/// Perform topology analysis from a Repository
pub fn analyze_topology_from_repo(
    repo: &Repository,
    config: &TopologyConfig,
) -> Result<BranchTopology> {
    // 1. Detect main branch
    let main_branch = detect_main_branch(repo);
    let mut topology = BranchTopology::new(main_branch.clone());
    topology.config = config.clone();

    // 2. Get current branch
    let current_branch = repo
        .head()
        .ok()
        .and_then(|h| h.shorthand().map(|s| s.to_string()));

    // 3. Get all local branches
    let branches = repo.branches(Some(git2::BranchType::Local))?;

    for branch_result in branches {
        let (branch, _) = branch_result?;
        let name = match branch.name()? {
            Some(n) => n.to_string(),
            None => continue,
        };

        // Get HEAD commit of the branch
        let commit = match branch.get().peel_to_commit() {
            Ok(c) => c,
            Err(_) => continue,
        };

        let head_hash = commit.id().to_string()[..GIT_SHORT_HASH_LEN].to_string();
        let last_activity = Local
            .timestamp_opt(commit.time().seconds(), 0)
            .single()
            .unwrap_or_else(Local::now);

        // Create branch information
        let mut topo_branch = TopologyBranch::new(name.clone(), head_hash, last_activity);

        // Determine status
        let status = if current_branch.as_ref() == Some(&name) {
            BranchStatus::Active
        } else if topo_branch.is_stale(config.stale_threshold_days) {
            BranchStatus::Stale
        } else {
            BranchStatus::Normal
        };
        topo_branch = topo_branch.with_status(status);

        // Analyze relation with main branch
        if name != main_branch {
            if let Some(relation) = analyze_branch_relation(repo, &main_branch, &name) {
                // Update status if merged
                if relation.is_merged && status != BranchStatus::Active {
                    topo_branch = topo_branch.with_status(BranchStatus::Merged);
                }
                topo_branch = topo_branch.with_relation(relation);
            }
        }

        topology.add_branch(topo_branch);
    }

    // Sort branches (active first, then main, then by last activity)
    topology.branches.sort_by(|a, b| {
        // Active branch gets highest priority
        if a.status == BranchStatus::Active {
            return std::cmp::Ordering::Less;
        }
        if b.status == BranchStatus::Active {
            return std::cmp::Ordering::Greater;
        }

        // Main branch gets next priority
        if a.name == topology.main_branch {
            return std::cmp::Ordering::Less;
        }
        if b.name == topology.main_branch {
            return std::cmp::Ordering::Greater;
        }

        // Stale branches go to the end
        if a.status == BranchStatus::Stale && b.status != BranchStatus::Stale {
            return std::cmp::Ordering::Greater;
        }
        if b.status == BranchStatus::Stale && a.status != BranchStatus::Stale {
            return std::cmp::Ordering::Less;
        }

        // Sort by last activity descending (most recent first)
        b.last_activity.cmp(&a.last_activity)
    });

    // Limit display count
    if topology.branches.len() > config.max_branches {
        topology.branches.truncate(config.max_branches);
    }

    // Calculate health for all branches
    topology.calculate_all_health();

    Ok(topology)
}

/// Detect main branch (main or master)
fn detect_main_branch(repo: &Repository) -> String {
    // Prefer main
    if repo.find_branch("main", git2::BranchType::Local).is_ok() {
        return "main".to_string();
    }

    // Fall back to master
    if repo.find_branch("master", git2::BranchType::Local).is_ok() {
        return "master".to_string();
    }

    // Default to "main" if neither exists
    "main".to_string()
}

/// Analyze relation between branches
fn analyze_branch_relation(
    repo: &Repository,
    base_name: &str,
    branch_name: &str,
) -> Option<BranchRelation> {
    // Resolve both branches
    let base_ref = format!("refs/heads/{}", base_name);
    let branch_ref = format!("refs/heads/{}", branch_name);

    let base_oid = repo.revparse_single(&base_ref).ok()?.id();
    let branch_oid = repo.revparse_single(&branch_ref).ok()?.id();

    // Calculate merge base
    let merge_base = repo.merge_base(base_oid, branch_oid).ok()?;
    let merge_base_hash = merge_base.to_string()[..GIT_SHORT_HASH_LEN].to_string();

    let mut relation = BranchRelation::new(base_name.to_string(), branch_name.to_string());
    relation.merge_base = merge_base_hash;

    // Calculate ahead/behind
    let (ahead, behind) = repo.graph_ahead_behind(branch_oid, base_oid).ok()?;
    relation.ahead_count = ahead;
    relation.behind_count = behind;

    // Determine if merged
    // branch_oid is contained in base (ahead == 0) and merge base equals branch HEAD
    relation.is_merged = ahead == 0 && merge_base == branch_oid;

    Some(relation)
}

/// Analyze recommended actions for branches
///
/// Calculate recommended actions for each branch from topology analysis results
pub fn analyze_branch_recommendations(topology: &BranchTopology) -> BranchRecommendations {
    let mut recommendations = BranchRecommendations::new();
    recommendations.total_branches = topology.branches.len();
    let now = Local::now();

    for branch in &topology.branches {
        // Exclude main branch and active branch
        if branch.name == topology.main_branch || branch.status == BranchStatus::Active {
            continue;
        }

        let days_inactive = now.signed_duration_since(branch.last_activity).num_days();

        // Get ahead/behind counts
        let (ahead, behind) = branch
            .relation
            .as_ref()
            .map(|r| (r.ahead_count, r.behind_count))
            .unwrap_or((0, 0));

        // Determine recommended action
        let (action, reason, priority) =
            determine_recommendation(branch, days_inactive, ahead, behind, &topology.config);

        let rec = BranchRecommendation::new(branch.name.clone(), action, reason, priority)
            .with_counts(ahead, behind)
            .with_days_inactive(days_inactive);

        recommendations.add(rec);
    }

    // Sort by priority
    recommendations.sort_by_priority();
    recommendations
}

/// Determine recommended action for a branch
fn determine_recommendation(
    branch: &TopologyBranch,
    days_inactive: i64,
    ahead: usize,
    behind: usize,
    config: &TopologyConfig,
) -> (RecommendedAction, String, u8) {
    // 1. Merged -> Delete
    if branch.status == BranchStatus::Merged {
        return (
            RecommendedAction::Delete,
            "Branch has been merged".to_string(),
            PRIORITY_MERGED,
        );
    }

    // 2. 60+ days inactive (long-term stale) -> Delete
    if days_inactive >= config.long_lived_threshold_days {
        return (
            RecommendedAction::Delete,
            format!("No activity for {} days", days_inactive),
            PRIORITY_LONG_STALE,
        );
    }

    // 3. Significantly behind base -> Rebase
    if behind >= config.far_behind_threshold {
        return (
            RecommendedAction::Rebase,
            format!("{} commits behind main", behind),
            PRIORITY_FAR_BEHIND,
        );
    }

    // 4. ahead > 0, merge candidate -> Merge
    if ahead > 0 && behind < MERGE_CANDIDATE_MAX_BEHIND {
        return (
            RecommendedAction::Merge,
            format!("{} commits ahead, ready to merge", ahead),
            PRIORITY_MERGE_CANDIDATE,
        );
    }

    // 5. Long-lived (30+ days) but active -> Review
    if days_inactive >= config.stale_threshold_days
        && days_inactive < config.long_lived_threshold_days
    {
        return (
            RecommendedAction::Review,
            format!("Branch is {} days old, needs attention", days_inactive),
            PRIORITY_REVIEW,
        );
    }

    // 6. Both ahead and behind are high (large divergence) -> Rebase
    if ahead >= config.divergence_threshold && behind >= config.divergence_threshold {
        return (
            RecommendedAction::Rebase,
            format!("Large divergence: {} ahead, {} behind", ahead, behind),
            PRIORITY_LARGE_DIVERGENCE,
        );
    }

    // Default: Keep
    (
        RecommendedAction::Keep,
        "Branch is in good condition".to_string(),
        PRIORITY_KEEP,
    )
}

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

    fn init_test_repo() -> (TempDir, Repository) {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let repo = Repository::init(temp_dir.path()).expect("Failed to init repo");

        // Create initial commit
        let sig = git2::Signature::now("Test Author", "test@example.com").unwrap();
        let tree_id = {
            let mut index = repo.index().unwrap();
            let test_file = temp_dir.path().join("test.txt");
            fs::write(&test_file, "test content").unwrap();
            index.add_path(Path::new("test.txt")).unwrap();
            index.write().unwrap();
            index.write_tree().unwrap()
        };
        {
            let tree = repo.find_tree(tree_id).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
                .unwrap();
        }

        (temp_dir, repo)
    }

    #[test]
    fn test_detect_main_branch_prefers_main() {
        let (_temp_dir, repo) = init_test_repo();

        // Create main branch
        let head = repo.head().unwrap().peel_to_commit().unwrap();
        repo.branch("main", &head, false).unwrap();

        let main = detect_main_branch(&repo);
        assert_eq!(main, "main");
    }

    #[test]
    fn test_detect_main_branch_falls_back_to_master() {
        let (_temp_dir, repo) = init_test_repo();
        // When initial branch is master
        let main = detect_main_branch(&repo);
        // master or main (depends on git config)
        assert!(main == "master" || main == "main");
    }

    #[test]
    fn test_analyze_topology_from_repo_returns_topology() {
        let (_temp_dir, repo) = init_test_repo();
        let config = TopologyConfig::default();
        let topology = analyze_topology_from_repo(&repo, &config).unwrap();

        assert!(!topology.branches.is_empty());
    }

    #[test]
    fn test_analyze_topology_from_repo_includes_current_branch() {
        let (_temp_dir, repo) = init_test_repo();
        let config = TopologyConfig::default();
        let topology = analyze_topology_from_repo(&repo, &config).unwrap();

        // Active branch exists
        assert!(topology.active_branch().is_some());
    }

    #[test]
    fn test_analyze_topology_with_feature_branch() {
        let (temp_dir, repo) = init_test_repo();

        // Create feature branch and commit
        let head = repo.head().unwrap().peel_to_commit().unwrap();
        repo.branch("feature", &head, false).unwrap();

        // Checkout feature branch
        let obj = repo.revparse_single("refs/heads/feature").unwrap();
        repo.checkout_tree(&obj, None).unwrap();
        repo.set_head("refs/heads/feature").unwrap();

        // Add a new commit
        let sig = git2::Signature::now("Test Author", "test@example.com").unwrap();
        let test_file = temp_dir.path().join("feature.txt");
        fs::write(&test_file, "feature content").unwrap();
        let mut index = repo.index().unwrap();
        index.add_path(Path::new("feature.txt")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        let parent = repo.head().unwrap().peel_to_commit().unwrap();
        repo.commit(
            Some("HEAD"),
            &sig,
            &sig,
            "Feature commit",
            &tree,
            &[&parent],
        )
        .unwrap();

        let config = TopologyConfig::default();
        let topology = analyze_topology_from_repo(&repo, &config).unwrap();

        // Feature branch is active
        let active = topology.active_branch().unwrap();
        assert_eq!(active.name, "feature");
    }
}