1
mod branches;
2
mod hook;
3
mod input;
4
mod remote;
5
mod repo;
6

            
7
use hook::GitHook;
8

            
9
/// Delete all local branches that are not in remote branches.
10
pub fn run(no_confirm: bool, install_hook: bool) {
11
    let repo = match repo::open() {
12
        Ok(repo) => repo,
13
        Err(e) => {
14
            eprintln!("Failed to open repository: {}", e);
15
            return;
16
        }
17
    };
18

            
19
    // Install the hook script if requested.
20
    if install_hook {
21
        println!("Installing git-snip hook script.");
22
        let hook = GitHook::default();
23
        if let Err(e) = hook.install(repo.path()) {
24
            eprintln!("Failed to install hook: {}", e);
25
        }
26
    }
27

            
28
    let branches_to_delete = branches::list_to_delete(&repo);
29
    if branches_to_delete.is_empty() {
30
        println!("No local branches to delete.");
31
        return;
32
    }
33

            
34
    if !no_confirm {
35
        println!("Local branches to delete:");
36
        for b in &branches_to_delete {
37
            println!("- {}", b);
38
        }
39

            
40
        let user_input = input::prompt_stdin("Delete these branches? (y/n): ");
41
        if (user_input != "y") && (user_input != "yes") {
42
            println!("Aborting.");
43
            return;
44
        }
45
    }
46

            
47
    for b in branches_to_delete {
48
        branches::delete(&repo, &b).unwrap();
49
    }
50
}
51

            
52
#[cfg(test)]
53
pub mod test_utilities {
54
    use git2::{Repository, RepositoryInitOptions};
55
    use tempfile::TempDir;
56

            
57
    /// Create a mock Git repository with initial commit in a temporary
58
    /// directory for testing.
59
20
    pub fn create_mock_repo() -> (TempDir, Repository) {
60
20
        let tempdir = TempDir::new().unwrap();
61
20
        let mut opts = RepositoryInitOptions::new();
62
20
        opts.initial_head("main");
63
20
        let repo = Repository::init_opts(tempdir.path(), &opts).unwrap();
64
20

            
65
20
        // Create initial commit
66
20
        {
67
20
            let mut config = repo.config().unwrap();
68
20
            config.set_str("user.name", "name").unwrap();
69
20
            config.set_str("user.email", "email").unwrap();
70
20
            let mut index = repo.index().unwrap();
71
20
            let id = index.write_tree().unwrap();
72
20

            
73
20
            let tree = repo.find_tree(id).unwrap();
74
20
            let sig = repo.signature().unwrap();
75
20
            repo.commit(Some("HEAD"), &sig, &sig, "initial\n\nbody", &tree, &[])
76
20
                .unwrap();
77
20
        }
78
20
        (tempdir, repo)
79
20
    }
80
}