gitutils.go 6.4 KB

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