git.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package utils
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "os/exec"
  7. "strings"
  8. "github.com/docker/docker/pkg/urlutil"
  9. )
  10. func GitClone(remoteURL string) (string, error) {
  11. if !urlutil.IsGitTransport(remoteURL) {
  12. remoteURL = "https://" + remoteURL
  13. }
  14. root, err := ioutil.TempDir("", "docker-build-git")
  15. if err != nil {
  16. return "", err
  17. }
  18. clone := cloneArgs(remoteURL, root)
  19. if output, err := exec.Command("git", clone...).CombinedOutput(); err != nil {
  20. return "", fmt.Errorf("Error trying to use git: %s (%s)", err, output)
  21. }
  22. return root, nil
  23. }
  24. func cloneArgs(remoteURL, root string) []string {
  25. args := []string{"clone", "--recursive"}
  26. shallow := true
  27. if strings.HasPrefix(remoteURL, "http") {
  28. res, err := http.Head(fmt.Sprintf("%s/info/refs?service=git-upload-pack", remoteURL))
  29. if err != nil || res.Header.Get("Content-Type") != "application/x-git-upload-pack-advertisement" {
  30. shallow = false
  31. }
  32. }
  33. if shallow {
  34. args = append(args, "--depth", "1")
  35. }
  36. return append(args, remoteURL, root)
  37. }