git.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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() (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. }, err
  53. }
  54. type gitRemoteLoader struct {
  55. cache string
  56. }
  57. func (g gitRemoteLoader) Accept(path string) bool {
  58. _, err := gitutil.ParseGitRef(path)
  59. return err == nil
  60. }
  61. var commitSHA = regexp.MustCompile(`^[a-f0-9]{40}$`)
  62. func (g gitRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  63. ref, err := gitutil.ParseGitRef(path)
  64. if err != nil {
  65. return "", err
  66. }
  67. if ref.Commit == "" {
  68. ref.Commit = "HEAD" // default branch
  69. }
  70. if !commitSHA.MatchString(ref.Commit) {
  71. cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", ref.Remote, ref.Commit)
  72. cmd.Env = g.gitCommandEnv()
  73. out, err := cmd.Output()
  74. if err != nil {
  75. if cmd.ProcessState.ExitCode() == 2 {
  76. return "", errors.Wrapf(err, "repository does not contain ref %s, output: %q", path, string(out))
  77. }
  78. return "", err
  79. }
  80. if len(out) < 40 {
  81. return "", fmt.Errorf("unexpected git command output: %q", string(out))
  82. }
  83. sha := string(out[:40])
  84. if !commitSHA.MatchString(sha) {
  85. return "", fmt.Errorf("invalid commit sha %q", sha)
  86. }
  87. ref.Commit = sha
  88. }
  89. local := filepath.Join(g.cache, ref.Commit)
  90. if _, err := os.Stat(local); os.IsNotExist(err) {
  91. err = g.checkout(ctx, local, ref)
  92. if err != nil {
  93. return "", err
  94. }
  95. }
  96. if ref.SubDir != "" {
  97. local = filepath.Join(local, ref.SubDir)
  98. }
  99. stat, err := os.Stat(local)
  100. if err != nil {
  101. return "", err
  102. }
  103. if stat.IsDir() {
  104. local, err = findFile(cli.DefaultFileNames, local)
  105. }
  106. return local, err
  107. }
  108. func (g gitRemoteLoader) checkout(ctx context.Context, path string, ref *gitutil.GitRef) error {
  109. err := os.MkdirAll(path, 0o700)
  110. if err != nil {
  111. return err
  112. }
  113. err = exec.CommandContext(ctx, "git", "init", path).Run()
  114. if err != nil {
  115. return err
  116. }
  117. cmd := exec.CommandContext(ctx, "git", "remote", "add", "origin", ref.Remote)
  118. cmd.Dir = path
  119. err = cmd.Run()
  120. if err != nil {
  121. return err
  122. }
  123. cmd = exec.CommandContext(ctx, "git", "fetch", "--depth=1", "origin", ref.Commit)
  124. cmd.Env = g.gitCommandEnv()
  125. cmd.Dir = path
  126. err = cmd.Run()
  127. if err != nil {
  128. return err
  129. }
  130. cmd = exec.CommandContext(ctx, "git", "checkout", ref.Commit)
  131. cmd.Dir = path
  132. err = cmd.Run()
  133. if err != nil {
  134. return err
  135. }
  136. return nil
  137. }
  138. func (g gitRemoteLoader) gitCommandEnv() []string {
  139. env := types.NewMapping(os.Environ())
  140. if env["GIT_TERMINAL_PROMPT"] == "" {
  141. // Disable prompting for passwords by Git until user explicitly asks for it.
  142. env["GIT_TERMINAL_PROMPT"] = "0"
  143. }
  144. if env["GIT_SSH"] == "" && env["GIT_SSH_COMMAND"] == "" {
  145. // Disable any ssh connection pooling by Git and do not attempt to prompt the user.
  146. env["GIT_SSH_COMMAND"] = "ssh -o ControlMaster=no -o BatchMode=yes"
  147. }
  148. v := values(env)
  149. return v
  150. }
  151. func findFile(names []string, pwd string) (string, error) {
  152. for _, n := range names {
  153. f := filepath.Join(pwd, n)
  154. if fi, err := os.Stat(f); err == nil && !fi.IsDir() {
  155. return f, nil
  156. }
  157. }
  158. return "", api.ErrNotFound
  159. }
  160. var _ loader.ResourceLoader = gitRemoteLoader{}
  161. func values(m types.Mapping) []string {
  162. values := make([]string, 0, len(m))
  163. for k, v := range m {
  164. values = append(values, fmt.Sprintf("%s=%s", k, v))
  165. }
  166. return values
  167. }