forked from hashicorp/terraform
/
get_git.go
74 lines (62 loc) · 1.45 KB
/
get_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
package module
import (
"fmt"
"net/url"
"os"
"os/exec"
)
// GitGetter is a Getter implementation that will download a module from
// a git repository.
type GitGetter struct{}
func (g *GitGetter) Get(dst string, u *url.URL) error {
if _, err := exec.LookPath("git"); err != nil {
return fmt.Errorf("git must be available and on the PATH")
}
// Extract some query parameters we use
var ref string
q := u.Query()
if len(q) > 0 {
ref = q.Get("ref")
q.Del("ref")
// Copy the URL
var newU url.URL = *u
u = &newU
u.RawQuery = q.Encode()
}
// First: clone or update the repository
_, err := os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
err = g.update(dst, u)
} else {
err = g.clone(dst, u)
}
if err != nil {
return err
}
// Next: check out the proper tag/branch if it is specified, and checkout
if ref == "" {
return nil
}
return g.checkout(dst, ref)
}
func (g *GitGetter) checkout(dst string, ref string) error {
cmd := exec.Command("git", "checkout", ref)
cmd.Dir = dst
return getRunCommand(cmd)
}
func (g *GitGetter) clone(dst string, u *url.URL) error {
cmd := exec.Command("git", "clone", u.String(), dst)
return getRunCommand(cmd)
}
func (g *GitGetter) update(dst string, u *url.URL) error {
// We have to be on a branch to pull
if err := g.checkout(dst, "master"); err != nil {
return err
}
cmd := exec.Command("git", "pull", "--ff-only")
cmd.Dir = dst
return getRunCommand(cmd)
}