git.go 5.0 KB

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