git.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package remote
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "regexp"
  21. "strconv"
  22. "github.com/adrg/xdg"
  23. "github.com/compose-spec/compose-go/cli"
  24. "github.com/compose-spec/compose-go/loader"
  25. "github.com/compose-spec/compose-go/types"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/moby/buildkit/util/gitutil"
  28. )
  29. func GitRemoteLoaderEnabled() (bool, error) {
  30. if v := os.Getenv("COMPOSE_EXPERIMENTAL_GIT_REMOTE"); v != "" {
  31. enabled, err := strconv.ParseBool(v)
  32. if err != nil {
  33. return false, fmt.Errorf("COMPOSE_EXPERIMENTAL_GIT_REMOTE environment variable expects boolean value: %w", err)
  34. }
  35. return enabled, err
  36. }
  37. return false, nil
  38. }
  39. func NewGitRemoteLoader(offline bool) (loader.ResourceLoader, error) {
  40. // xdg.CacheFile creates the parent directories for the target file path
  41. // and returns the fully qualified path, so use "git" as a filename and
  42. // then chop it off after, i.e. no ~/.cache/docker-compose/git file will
  43. // ever be created
  44. cache, err := xdg.CacheFile(filepath.Join("docker-compose", "git"))
  45. if err != nil {
  46. return nil, fmt.Errorf("initializing git cache: %w", err)
  47. }
  48. cache = filepath.Dir(cache)
  49. return gitRemoteLoader{
  50. cache: cache,
  51. offline: offline,
  52. }, err
  53. }
  54. type gitRemoteLoader struct {
  55. cache string
  56. offline bool
  57. }
  58. func (g gitRemoteLoader) Accept(path string) bool {
  59. _, err := gitutil.ParseGitRef(path)
  60. return err == nil
  61. }
  62. var commitSHA = regexp.MustCompile(`^[a-f0-9]{40}$`)
  63. func (g gitRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  64. ref, err := gitutil.ParseGitRef(path)
  65. if err != nil {
  66. return "", err
  67. }
  68. if ref.Commit == "" {
  69. ref.Commit = "HEAD" // default branch
  70. }
  71. if !commitSHA.MatchString(ref.Commit) {
  72. cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", ref.Remote, ref.Commit)
  73. cmd.Env = g.gitCommandEnv()
  74. out, err := cmd.Output()
  75. if err != nil {
  76. if cmd.ProcessState.ExitCode() == 2 {
  77. return "", fmt.Errorf("repository does not contain ref %s, output: %q: %w", path, string(out), err)
  78. }
  79. return "", err
  80. }
  81. if len(out) < 40 {
  82. return "", fmt.Errorf("unexpected git command output: %q", string(out))
  83. }
  84. sha := string(out[:40])
  85. if !commitSHA.MatchString(sha) {
  86. return "", fmt.Errorf("invalid commit sha %q", sha)
  87. }
  88. ref.Commit = sha
  89. }
  90. local := filepath.Join(g.cache, ref.Commit)
  91. if _, err := os.Stat(local); os.IsNotExist(err) {
  92. if g.offline {
  93. return "", nil
  94. }
  95. err = g.checkout(ctx, local, ref)
  96. if err != nil {
  97. return "", err
  98. }
  99. }
  100. if ref.SubDir != "" {
  101. local = filepath.Join(local, ref.SubDir)
  102. }
  103. stat, err := os.Stat(local)
  104. if err != nil {
  105. return "", err
  106. }
  107. if stat.IsDir() {
  108. local, err = findFile(cli.DefaultFileNames, local)
  109. }
  110. return local, err
  111. }
  112. func (g gitRemoteLoader) checkout(ctx context.Context, path string, ref *gitutil.GitRef) error {
  113. err := os.MkdirAll(path, 0o700)
  114. if err != nil {
  115. return err
  116. }
  117. err = exec.CommandContext(ctx, "git", "init", path).Run()
  118. if err != nil {
  119. return err
  120. }
  121. cmd := exec.CommandContext(ctx, "git", "remote", "add", "origin", ref.Remote)
  122. cmd.Dir = path
  123. err = cmd.Run()
  124. if err != nil {
  125. return err
  126. }
  127. cmd = exec.CommandContext(ctx, "git", "fetch", "--depth=1", "origin", ref.Commit)
  128. cmd.Env = g.gitCommandEnv()
  129. cmd.Dir = path
  130. err = cmd.Run()
  131. if err != nil {
  132. return err
  133. }
  134. cmd = exec.CommandContext(ctx, "git", "checkout", ref.Commit)
  135. cmd.Dir = path
  136. err = cmd.Run()
  137. if err != nil {
  138. return err
  139. }
  140. return nil
  141. }
  142. func (g gitRemoteLoader) gitCommandEnv() []string {
  143. env := types.NewMapping(os.Environ())
  144. if env["GIT_TERMINAL_PROMPT"] == "" {
  145. // Disable prompting for passwords by Git until user explicitly asks for it.
  146. env["GIT_TERMINAL_PROMPT"] = "0"
  147. }
  148. if env["GIT_SSH"] == "" && env["GIT_SSH_COMMAND"] == "" {
  149. // Disable any ssh connection pooling by Git and do not attempt to prompt the user.
  150. env["GIT_SSH_COMMAND"] = "ssh -o ControlMaster=no -o BatchMode=yes"
  151. }
  152. v := env.Values()
  153. return v
  154. }
  155. func findFile(names []string, pwd string) (string, error) {
  156. for _, n := range names {
  157. f := filepath.Join(pwd, n)
  158. if fi, err := os.Stat(f); err == nil && !fi.IsDir() {
  159. return f, nil
  160. }
  161. }
  162. return "", api.ErrNotFound
  163. }
  164. var _ loader.ResourceLoader = gitRemoteLoader{}