gitutils.go 5.7 KB

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