github.com/arvindram03/terraform@v0.3.7-0.20150212015210-408f838db36d/config/module/get_git.go (about)

     1  package module
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"os"
     7  	"os/exec"
     8  )
     9  
    10  // GitGetter is a Getter implementation that will download a module from
    11  // a git repository.
    12  type GitGetter struct{}
    13  
    14  func (g *GitGetter) Get(dst string, u *url.URL) error {
    15  	if _, err := exec.LookPath("git"); err != nil {
    16  		return fmt.Errorf("git must be available and on the PATH")
    17  	}
    18  
    19  	// Extract some query parameters we use
    20  	var ref string
    21  	q := u.Query()
    22  	if len(q) > 0 {
    23  		ref = q.Get("ref")
    24  		q.Del("ref")
    25  
    26  		// Copy the URL
    27  		var newU url.URL = *u
    28  		u = &newU
    29  		u.RawQuery = q.Encode()
    30  	}
    31  
    32  	// First: clone or update the repository
    33  	_, err := os.Stat(dst)
    34  	if err != nil && !os.IsNotExist(err) {
    35  		return err
    36  	}
    37  	if err == nil {
    38  		err = g.update(dst, u)
    39  	} else {
    40  		err = g.clone(dst, u)
    41  	}
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	// Next: check out the proper tag/branch if it is specified, and checkout
    47  	if ref == "" {
    48  		return nil
    49  	}
    50  
    51  	return g.checkout(dst, ref)
    52  }
    53  
    54  func (g *GitGetter) checkout(dst string, ref string) error {
    55  	cmd := exec.Command("git", "checkout", ref)
    56  	cmd.Dir = dst
    57  	return getRunCommand(cmd)
    58  }
    59  
    60  func (g *GitGetter) clone(dst string, u *url.URL) error {
    61  	cmd := exec.Command("git", "clone", u.String(), dst)
    62  	return getRunCommand(cmd)
    63  }
    64  
    65  func (g *GitGetter) update(dst string, u *url.URL) error {
    66  	// We have to be on a branch to pull
    67  	if err := g.checkout(dst, "master"); err != nil {
    68  		return err
    69  	}
    70  
    71  	cmd := exec.Command("git", "pull", "--ff-only")
    72  	cmd.Dir = dst
    73  	return getRunCommand(cmd)
    74  }