git.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. "github.com/pkg/errors"
  29. )
  30. func GitRemoteLoaderEnabled() (bool, error) {
  31. if v := os.Getenv("COMPOSE_EXPERIMENTAL_GIT_REMOTE"); v != "" {
  32. enabled, err := strconv.ParseBool(v)
  33. if err != nil {
  34. return false, errors.Wrap(err, "COMPOSE_EXPERIMENTAL_GIT_REMOTE environment variable expects boolean value")
  35. }
  36. return enabled, err
  37. }
  38. return false, nil
  39. }
  40. func NewGitRemoteLoader(offline bool) (loader.ResourceLoader, error) {
  41. // xdg.CacheFile creates the parent directories for the target file path
  42. // and returns the fully qualified path, so use "git" as a filename and
  43. // then chop it off after, i.e. no ~/.cache/docker-compose/git file will
  44. // ever be created
  45. cache, err := xdg.CacheFile(filepath.Join("docker-compose", "git"))
  46. if err != nil {
  47. return nil, fmt.Errorf("initializing git cache: %w", err)
  48. }
  49. cache = filepath.Dir(cache)
  50. return gitRemoteLoader{
  51. cache: cache,
  52. offline: offline,
  53. }, err
  54. }
  55. type gitRemoteLoader struct {
  56. cache string
  57. offline bool
  58. }
  59. func (g gitRemoteLoader) Accept(path string) bool {
  60. _, err := gitutil.ParseGitRef(path)
  61. return err == nil
  62. }
  63. var commitSHA = regexp.MustCompile(`^[a-f0-9]{40}$`)
  64. func (g gitRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  65. ref, err := gitutil.ParseGitRef(path)
  66. if err != nil {
  67. return "", err
  68. }
  69. if ref.Commit == "" {
  70. ref.Commit = "HEAD" // default branch
  71. }
  72. if !commitSHA.MatchString(ref.Commit) {
  73. cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", ref.Remote, ref.Commit)
  74. cmd.Env = g.gitCommandEnv()
  75. out, err := cmd.Output()
  76. if err != nil {
  77. if cmd.ProcessState.ExitCode() == 2 {
  78. return "", errors.Wrapf(err, "repository does not contain ref %s, output: %q", path, string(out))
  79. }
  80. return "", err
  81. }
  82. if len(out) < 40 {
  83. return "", fmt.Errorf("unexpected git command output: %q", string(out))
  84. }
  85. sha := string(out[:40])
  86. if !commitSHA.MatchString(sha) {
  87. return "", fmt.Errorf("invalid commit sha %q", sha)
  88. }
  89. ref.Commit = sha
  90. }
  91. local := filepath.Join(g.cache, ref.Commit)
  92. if _, err := os.Stat(local); os.IsNotExist(err) {
  93. if g.offline {
  94. return "", nil
  95. }
  96. err = g.checkout(ctx, local, ref)
  97. if err != nil {
  98. return "", err
  99. }
  100. }
  101. if ref.SubDir != "" {
  102. local = filepath.Join(local, ref.SubDir)
  103. }
  104. stat, err := os.Stat(local)
  105. if err != nil {
  106. return "", err
  107. }
  108. if stat.IsDir() {
  109. local, err = findFile(cli.DefaultFileNames, local)
  110. }
  111. return local, err
  112. }
  113. func (g gitRemoteLoader) checkout(ctx context.Context, path string, ref *gitutil.GitRef) error {
  114. err := os.MkdirAll(path, 0o700)
  115. if err != nil {
  116. return err
  117. }
  118. err = exec.CommandContext(ctx, "git", "init", path).Run()
  119. if err != nil {
  120. return err
  121. }
  122. cmd := exec.CommandContext(ctx, "git", "remote", "add", "origin", ref.Remote)
  123. cmd.Dir = path
  124. err = cmd.Run()
  125. if err != nil {
  126. return err
  127. }
  128. cmd = exec.CommandContext(ctx, "git", "fetch", "--depth=1", "origin", ref.Commit)
  129. cmd.Env = g.gitCommandEnv()
  130. cmd.Dir = path
  131. err = cmd.Run()
  132. if err != nil {
  133. return err
  134. }
  135. cmd = exec.CommandContext(ctx, "git", "checkout", ref.Commit)
  136. cmd.Dir = path
  137. err = cmd.Run()
  138. if err != nil {
  139. return err
  140. }
  141. return nil
  142. }
  143. func (g gitRemoteLoader) gitCommandEnv() []string {
  144. env := types.NewMapping(os.Environ())
  145. if env["GIT_TERMINAL_PROMPT"] == "" {
  146. // Disable prompting for passwords by Git until user explicitly asks for it.
  147. env["GIT_TERMINAL_PROMPT"] = "0"
  148. }
  149. if env["GIT_SSH"] == "" && env["GIT_SSH_COMMAND"] == "" {
  150. // Disable any ssh connection pooling by Git and do not attempt to prompt the user.
  151. env["GIT_SSH_COMMAND"] = "ssh -o ControlMaster=no -o BatchMode=yes"
  152. }
  153. v := env.Values()
  154. return v
  155. }
  156. func findFile(names []string, pwd string) (string, error) {
  157. for _, n := range names {
  158. f := filepath.Join(pwd, n)
  159. if fi, err := os.Stat(f); err == nil && !fi.IsDir() {
  160. return f, nil
  161. }
  162. }
  163. return "", api.ErrNotFound
  164. }
  165. var _ loader.ResourceLoader = gitRemoteLoader{}