-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (62 loc) · 1.52 KB
/
main.go
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
// Copyright (c) Seth Hoenig
// SPDX-License-Identifier: MPL-2.0
// Command keep-branches is used to prune your local git repository
// of unwanted feature branches, etc.
package main
// Usage: keep-branches <branch, ...>
// Will remove any branch that is not main, the current branch, or
// listed in the command line arguments.
import (
"fmt"
"os"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/hashicorp/go-set/v3"
)
func main() {
help(os.Args)
keep := set.From(os.Args[1:])
keep.Insert("main")
lockdown(".git") // lockout filesystem
r, err := git.PlainOpen(".")
check(err)
head, err := r.Head()
check(err)
keep.Insert(branch(head))
it, err := r.Branches()
check(err)
err = it.ForEach(func(ref *plumbing.Reference) error {
label := branch(ref)
if !keep.Contains(label) {
fmt.Println(format(label))
del := hash(head, label)
return r.Storer.RemoveReference(del.Name())
}
return nil
})
check(err)
}
func check(err error) {
if err != nil {
fmt.Println("[failure]", err)
os.Exit(1)
}
}
func branch(r *plumbing.Reference) string {
name := string(r.Name())
return strings.TrimPrefix(name, "refs/heads/")
}
func hash(head *plumbing.Reference, branch string) *plumbing.Reference {
name := plumbing.ReferenceName("refs/heads/" + branch)
return plumbing.NewHashReference(name, head.Hash())
}
func help(args []string) {
if len(args) == 2 {
switch args[1] {
case "-h", "-help", "--help":
fmt.Println("keep-branches <branches>")
os.Exit(0)
}
}
}