gitutils.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package git
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "net/url"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strings"
  10. "github.com/docker/docker/pkg/symlink"
  11. "github.com/docker/docker/pkg/urlutil"
  12. "github.com/pkg/errors"
  13. )
  14. type gitRepo struct {
  15. remote string
  16. ref string
  17. subdir string
  18. }
  19. // Clone clones a repository into a newly created directory which
  20. // will be under "docker-build-git"
  21. func Clone(remoteURL string) (string, error) {
  22. repo, err := parseRemoteURL(remoteURL)
  23. if err != nil {
  24. return "", err
  25. }
  26. fetch := fetchArgs(repo.remote, repo.ref)
  27. root, err := ioutil.TempDir("", "docker-build-git")
  28. if err != nil {
  29. return "", err
  30. }
  31. if out, err := gitWithinDir(root, "init"); err != nil {
  32. return "", errors.Wrapf(err, "failed to init repo at %s: %s", root, out)
  33. }
  34. // Add origin remote for compatibility with previous implementation that
  35. // used "git clone" and also to make sure local refs are created for branches
  36. if out, err := gitWithinDir(root, "remote", "add", "origin", repo.remote); err != nil {
  37. return "", errors.Wrapf(err, "failed add origin repo at %s: %s", repo.remote, out)
  38. }
  39. if output, err := gitWithinDir(root, fetch...); err != nil {
  40. return "", errors.Wrapf(err, "error fetching: %s", output)
  41. }
  42. return checkoutGit(root, repo.ref, repo.subdir)
  43. }
  44. func parseRemoteURL(remoteURL string) (gitRepo, error) {
  45. repo := gitRepo{}
  46. if !isGitTransport(remoteURL) {
  47. remoteURL = "https://" + remoteURL
  48. }
  49. var fragment string
  50. if strings.HasPrefix(remoteURL, "git@") {
  51. // git@.. is not an URL, so cannot be parsed as URL
  52. parts := strings.SplitN(remoteURL, "#", 2)
  53. repo.remote = parts[0]
  54. if len(parts) == 2 {
  55. fragment = parts[1]
  56. }
  57. repo.ref, repo.subdir = getRefAndSubdir(fragment)
  58. } else {
  59. u, err := url.Parse(remoteURL)
  60. if err != nil {
  61. return repo, err
  62. }
  63. repo.ref, repo.subdir = getRefAndSubdir(u.Fragment)
  64. u.Fragment = ""
  65. repo.remote = u.String()
  66. }
  67. return repo, nil
  68. }
  69. func getRefAndSubdir(fragment string) (ref string, subdir string) {
  70. refAndDir := strings.SplitN(fragment, ":", 2)
  71. ref = "master"
  72. if len(refAndDir[0]) != 0 {
  73. ref = refAndDir[0]
  74. }
  75. if len(refAndDir) > 1 && len(refAndDir[1]) != 0 {
  76. subdir = refAndDir[1]
  77. }
  78. return
  79. }
  80. func fetchArgs(remoteURL string, ref string) []string {
  81. args := []string{"fetch", "--recurse-submodules=yes"}
  82. if supportsShallowClone(remoteURL) {
  83. args = append(args, "--depth", "1")
  84. }
  85. return append(args, "origin", ref)
  86. }
  87. // Check if a given git URL supports a shallow git clone,
  88. // i.e. it is a non-HTTP server or a smart HTTP server.
  89. func supportsShallowClone(remoteURL string) bool {
  90. if urlutil.IsURL(remoteURL) {
  91. // Check if the HTTP server is smart
  92. // Smart servers must correctly respond to a query for the git-upload-pack service
  93. serviceURL := remoteURL + "/info/refs?service=git-upload-pack"
  94. // Try a HEAD request and fallback to a Get request on error
  95. res, err := http.Head(serviceURL)
  96. if err != nil || res.StatusCode != http.StatusOK {
  97. res, err = http.Get(serviceURL)
  98. if err == nil {
  99. res.Body.Close()
  100. }
  101. if err != nil || res.StatusCode != http.StatusOK {
  102. // request failed
  103. return false
  104. }
  105. }
  106. if res.Header.Get("Content-Type") != "application/x-git-upload-pack-advertisement" {
  107. // Fallback, not a smart server
  108. return false
  109. }
  110. return true
  111. }
  112. // Non-HTTP protocols always support shallow clones
  113. return true
  114. }
  115. func checkoutGit(root, ref, subdir string) (string, error) {
  116. // Try checking out by ref name first. This will work on branches and sets
  117. // .git/HEAD to the current branch name
  118. if output, err := gitWithinDir(root, "checkout", ref); err != nil {
  119. // If checking out by branch name fails check out the last fetched ref
  120. if _, err2 := gitWithinDir(root, "checkout", "FETCH_HEAD"); err2 != nil {
  121. return "", errors.Wrapf(err, "error checking out %s: %s", ref, output)
  122. }
  123. }
  124. if subdir != "" {
  125. newCtx, err := symlink.FollowSymlinkInScope(filepath.Join(root, subdir), root)
  126. if err != nil {
  127. return "", errors.Wrapf(err, "error setting git context, %q not within git root", subdir)
  128. }
  129. fi, err := os.Stat(newCtx)
  130. if err != nil {
  131. return "", err
  132. }
  133. if !fi.IsDir() {
  134. return "", errors.Errorf("error setting git context, not a directory: %s", newCtx)
  135. }
  136. root = newCtx
  137. }
  138. return root, nil
  139. }
  140. func gitWithinDir(dir string, args ...string) ([]byte, error) {
  141. a := []string{"--work-tree", dir, "--git-dir", filepath.Join(dir, ".git")}
  142. return git(append(a, args...)...)
  143. }
  144. func git(args ...string) ([]byte, error) {
  145. return exec.Command("git", args...).CombinedOutput()
  146. }
  147. // isGitTransport returns true if the provided str is a git transport by inspecting
  148. // the prefix of the string for known protocols used in git.
  149. func isGitTransport(str string) bool {
  150. return urlutil.IsURL(str) || strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@")
  151. }