This repository has been archived by the owner on Apr 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
73 lines (63 loc) · 1.88 KB
/
git.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
package sprbox
import (
"errors"
"fmt"
"os/exec"
"strings"
)
// Repository represent a git repository
type Repository struct {
Path string
BranchName, Commit, Build, Tag string
Error error
}
// NewRepository return a new Repository instance for the given path
func NewRepository(path string) *Repository {
repo := &Repository{Path: path}
repo.UpdateInfo()
return repo
}
// UpdateInfo grab git info and set 'Error' var eventually.
func (r *Repository) UpdateInfo() {
r.BranchName = r.git("rev-parse", "--abbrev-ref", "HEAD")
r.Commit = r.git("rev-parse", "--short", "HEAD")
r.Build = r.git("rev-list", "--all", "--count")
r.Tag = r.git("describe", "--abbrev=0", "--tags", "--always")
}
// Git is the bash git command.
func (r *Repository) git(params ...string) string {
cmd := exec.Command("git", params...)
if len(r.Path) > 0 {
cmd.Dir = r.Path
}
output, err := cmd.Output()
if err != nil {
gitErrString := err.Error()
if exitError, ok := err.(*exec.ExitError); ok {
gitErrString = string(exitError.Stderr)
}
gitErrString = strings.TrimPrefix(gitErrString, "fatal: ")
gitErrString = strings.TrimSuffix(gitErrString, "\n")
gitErrString = strings.TrimSuffix(gitErrString, ": .git")
r.Error = errors.New(gitErrString)
return gitErrString
}
out := strings.TrimSuffix(string(output), "\n")
return out
}
// Info return Git repository info.
func (r *Repository) Info() string {
return fmt.Sprintf("Git Branch: %s\nGit Commit: %s\nGit Tag: %s\nGit Build: %s\n", r.BranchName, r.Commit, r.Tag, r.Build)
}
// PrintInfo print git data in console.
func (r *Repository) PrintInfo() {
if r == nil {
return
}
gitLog := kvLogger{ValuePainter: magenta}
gitLog.Println("Git Branch:", r.BranchName)
gitLog.Println("Git Commit:", r.Commit)
gitLog.Println("Git Tag:", r.Tag)
gitLog.Println("Git Build:", r.Build)
fmt.Println("")
}