terraform/config/module/get_git.go

75 lines
1.5 KiB
Go
Raw Normal View History

2014-09-16 08:32:30 +02:00
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")
}
2014-09-16 18:55:51 +02:00
// Extract some query parameters we use
2014-09-16 19:02:11 +02:00
var ref string
2014-09-16 18:55:51 +02:00
q := u.Query()
if len(q) > 0 {
2014-09-16 19:02:11 +02:00
ref = q.Get("ref")
q.Del("ref")
// Copy the URL
var newU url.URL = *u
u = &newU
u.RawQuery = q.Encode()
}
2014-09-16 18:55:51 +02:00
// First: clone or update the repository
2014-09-16 08:32:30 +02:00
_, err := os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
2014-09-16 18:55:51 +02:00
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
2014-09-16 19:02:11 +02:00
if ref == "" {
2014-09-16 18:55:51 +02:00
return nil
2014-09-16 08:32:30 +02:00
}
2014-09-16 19:02:11 +02:00
return g.checkout(dst, ref)
2014-09-16 18:55:51 +02:00
}
func (g *GitGetter) checkout(dst string, ref string) error {
cmd := exec.Command("git", "checkout", ref)
cmd.Dir = dst
return getRunCommand(cmd)
2014-09-16 08:32:30 +02:00
}
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
}
2014-09-16 08:32:30 +02:00
cmd := exec.Command("git", "pull", "--ff-only")
cmd.Dir = dst
return getRunCommand(cmd)
}