git.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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/compose-spec/compose-go/cli"
  23. "github.com/compose-spec/compose-go/loader"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/moby/buildkit/util/gitutil"
  27. )
  28. const GIT_REMOTE_ENABLED = "COMPOSE_EXPERIMENTAL_GIT_REMOTE"
  29. func gitRemoteLoaderEnabled() (bool, error) {
  30. if v := os.Getenv(GIT_REMOTE_ENABLED); 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 {
  40. return gitRemoteLoader{
  41. offline: offline,
  42. }
  43. }
  44. type gitRemoteLoader struct {
  45. offline bool
  46. }
  47. func (g gitRemoteLoader) Accept(path string) bool {
  48. _, err := gitutil.ParseGitRef(path)
  49. return err == nil
  50. }
  51. var commitSHA = regexp.MustCompile(`^[a-f0-9]{40}$`)
  52. func (g gitRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  53. enabled, err := gitRemoteLoaderEnabled()
  54. if err != nil {
  55. return "", err
  56. }
  57. if !enabled {
  58. return "", fmt.Errorf("experimental git remote resource is disabled. %q must be set", GIT_REMOTE_ENABLED)
  59. }
  60. ref, err := gitutil.ParseGitRef(path)
  61. if err != nil {
  62. return "", err
  63. }
  64. if ref.Commit == "" {
  65. ref.Commit = "HEAD" // default branch
  66. }
  67. if !commitSHA.MatchString(ref.Commit) {
  68. cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", ref.Remote, ref.Commit)
  69. cmd.Env = g.gitCommandEnv()
  70. out, err := cmd.Output()
  71. if err != nil {
  72. if cmd.ProcessState.ExitCode() == 2 {
  73. return "", fmt.Errorf("repository does not contain ref %s, output: %q: %w", path, string(out), err)
  74. }
  75. return "", err
  76. }
  77. if len(out) < 40 {
  78. return "", fmt.Errorf("unexpected git command output: %q", string(out))
  79. }
  80. sha := string(out[:40])
  81. if !commitSHA.MatchString(sha) {
  82. return "", fmt.Errorf("invalid commit sha %q", sha)
  83. }
  84. ref.Commit = sha
  85. }
  86. cache, err := cacheDir()
  87. if err != nil {
  88. return "", fmt.Errorf("initializing remote resource cache: %w", err)
  89. }
  90. local := filepath.Join(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{}