-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgitsrc.go
102 lines (77 loc) · 2.4 KB
/
gitsrc.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
// gitsrc satisfies the urfave/cli/altsrc.InputSourceContext interface
package gitsrc
import (
"errors"
"fmt"
"time"
git "github.com/go-git/go-git/v5"
cli "gopkg.in/urfave/cli.v1"
altsrc "gopkg.in/urfave/cli.v1/altsrc"
)
// ErrNotSupported is returned by all the functions that are not String().
var ErrNotSupported = errors.New("gitsrc: operation not supported")
// ErrNotFound is returned when the String(name) doesn't have a reference.
var ErrNotFound = errors.New("gitsrc: key not found")
// ErrNotBranch is returned when the git repo is not on a branch.
var ErrNotBranch = errors.New("gitsrc: ref is not a branch")
// FromCurrentDir tries to open $PWD as the git repo.
func FromCurrentDir(*cli.Context) (altsrc.InputSourceContext, error) { //nolint:nolintlint,ireturn
r, err := git.PlainOpenWithOptions(".", &git.PlainOpenOptions{DetectDotGit: true})
return &gitSource{r}, err
}
type gitSource struct {
*git.Repository
}
func (x *gitSource) String(name string) (string, error) {
// These names need to be aligned with the top-level GlobalFlags
switch name {
case "git-origin":
remote, err := x.Remote("origin")
if err != nil {
return "", fmt.Errorf("gitsrc: %w", err)
}
return remote.Config().URLs[0], nil
case "git-commit":
ref, err := x.Head()
if err != nil {
return "", fmt.Errorf("gitsrc: %w", err)
}
return ref.Hash().String(), nil
case "git-branch":
ref, err := x.Head()
if err != nil {
return "", fmt.Errorf("gitsrc: %w", err)
}
refName := ref.Name()
if refName.IsBranch() {
return refName.String(), nil
}
return "", ErrNotBranch
}
return "", ErrNotFound
}
// These are implemented to satisfy the altsrc.InputSourceContext interface
func (x *gitSource) Int(_ string) (int, error) {
return 0, ErrNotSupported
}
func (x *gitSource) Float64(_ string) (float64, error) {
return 0, ErrNotSupported
}
func (x *gitSource) Duration(_ string) (time.Duration, error) {
return 0, ErrNotSupported
}
func (x *gitSource) StringSlice(_ string) ([]string, error) {
return nil, ErrNotSupported
}
func (x *gitSource) IntSlice(_ string) ([]int, error) {
return nil, ErrNotSupported
}
func (x *gitSource) Generic(_ string) (cli.Generic, error) { //nolint:nolintlint,ireturn
return nil, ErrNotSupported
}
func (x *gitSource) Bool(_ string) (bool, error) {
return false, ErrNotSupported
}
func (x *gitSource) BoolT(_ string) (bool, error) {
return false, ErrNotSupported
}