git.go 4.7 KB

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