This repository has been archived by the owner on Mar 8, 2023. It is now read-only.
/
git.go
100 lines (76 loc) 路 1.64 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
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
package git
import (
"encoding/hex"
"fmt"
"os"
"regexp"
"github.com/mitchellh/mapstructure"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"github.com/pagarme/deployer/pipeline"
"github.com/pagarme/deployer/scm"
)
type Options struct {
Repository string `mapstructure:"repository"`
Ref string `mapstructure:"ref"`
}
type Git struct {
Options *Options
}
type Context struct {
Repo *git.Repository
Commit plumbing.Hash
}
func init() {
scm.Register("git", func(config map[string]interface{}) (scm.Scm, error) {
options := &Options{}
if err := mapstructure.Decode(config, options); err != nil {
return nil, err
}
return &Git{Options: options}, nil
})
}
func (g *Git) Fetch(ctx pipeline.Context, workdir, refName string) error {
var hash plumbing.Hash
repo, err := git.PlainClone(workdir, false, &git.CloneOptions{
RemoteName: "origin",
URL: g.Options.Repository,
Progress: os.Stdout,
})
if err != nil {
return err
}
isSha, err := regexp.MatchString("\\b[0-9a-fA-F]{5,40}\\b", refName)
if err != nil {
return err
}
ref, err := repo.Reference(plumbing.ReferenceName("refs/remotes/origin/"+refName), true)
if err != nil {
return err
}
if ref != nil {
hash = ref.Hash()
} else if isSha {
hash = plumbing.NewHash(refName)
} else {
return fmt.Errorf("invalid ref")
}
wt, err := repo.Worktree()
if err != nil {
return err
}
err = wt.Checkout(&git.CheckoutOptions{
Hash: hash,
})
if err != nil {
return err
}
ctx["Scm"] = &Context{
Repo: repo,
Commit: hash,
}
return nil
}
func (c *Context) CommitHash() string {
return hex.EncodeToString(c.Commit[:])
}