-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
106 lines (91 loc) · 2.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
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
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"github.com/shurcooL/markdownfmt/markdown"
"golang.org/x/term"
)
var (
baseFlag = flag.String("base", "main", "base branch to compare against locally")
allFlag = flag.Bool("all", false, `display all branches, including stale (>= 8 weeks old) and trashed ("trash/" prefix)`)
)
func main() {
flag.Parse()
if len(flag.Args()) != 0 {
flag.Usage()
os.Exit(2)
}
err := run()
if err != nil {
log.Fatalln(err)
}
}
func run() error {
cwd, err := os.Getwd()
if err != nil {
return err
}
dir, err := gitRoot(cwd)
if err != nil {
return err
}
isTerminal := term.IsTerminal(int(os.Stdout.Fd())) && os.Getenv("TERM") != "dumb"
// Display local branches.
branches, staleBranches, err := branches(dir, *baseFlag)
if err != nil {
return err
}
formatted, err := markdown.Process("", []byte(branches), &markdown.Options{Terminal: isTerminal})
if err != nil {
return err
}
os.Stdout.Write(formatted)
// Update all remotes.
cmd := exec.Command("git", "remote", "update", "--prune")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintln(os.Stderr, "git remote update failed:", err)
os.Stderr.Write(out)
}
// Display remote branches.
branches, staleRemoteBranches, err := branchesRemote(dir, *baseFlag)
if err != nil {
return err
}
formatted, err = markdown.Process("", []byte(branches), &markdown.Options{Terminal: isTerminal})
if err != nil {
return err
}
fmt.Println()
os.Stdout.Write(formatted)
switch {
case staleBranches == staleRemoteBranches && staleBranches > 0:
fmt.Printf("\n(%v stale/trashed branches not shown.)\n", staleBranches)
case staleBranches != staleRemoteBranches && (staleBranches > 0 || staleRemoteBranches > 0):
fmt.Printf("\n(%v stale/trashed local, %v stale/trashed remote branches not shown.)\n", staleBranches, staleRemoteBranches)
}
return nil
}
// gitRoot inspects dir and its parents to determine if it's inside a git repository.
// On return, root is the path corresponding to the root of the repository.
func gitRoot(dir string) (root string, err error) {
dir = filepath.Clean(dir)
origDir := dir
for {
// Accept .git as a directory (common case) and a regular file (e.g., a git worktree).
if fi, err := os.Stat(filepath.Join(dir, ".git")); err == nil && (fi.IsDir() || fi.Mode().IsRegular()) {
return dir, nil
}
// Move to parent.
ndir := filepath.Dir(dir)
if len(ndir) >= len(dir) {
break
}
dir = ndir
}
return "", fmt.Errorf("directory %q is not using git", origDir)
}