git.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. "bufio"
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "regexp"
  23. "strconv"
  24. "github.com/compose-spec/compose-go/v2/cli"
  25. "github.com/compose-spec/compose-go/v2/loader"
  26. "github.com/compose-spec/compose-go/v2/types"
  27. "github.com/docker/cli/cli/command"
  28. "github.com/docker/compose/v2/pkg/api"
  29. gitutil "github.com/moby/buildkit/frontend/dockerfile/dfgitutil"
  30. "github.com/sirupsen/logrus"
  31. )
  32. const GIT_REMOTE_ENABLED = "COMPOSE_EXPERIMENTAL_GIT_REMOTE"
  33. func gitRemoteLoaderEnabled() (bool, error) {
  34. if v := os.Getenv(GIT_REMOTE_ENABLED); v != "" {
  35. enabled, err := strconv.ParseBool(v)
  36. if err != nil {
  37. return false, fmt.Errorf("COMPOSE_EXPERIMENTAL_GIT_REMOTE environment variable expects boolean value: %w", err)
  38. }
  39. return enabled, err
  40. }
  41. return true, nil
  42. }
  43. func NewGitRemoteLoader(dockerCli command.Cli, offline bool) loader.ResourceLoader {
  44. return gitRemoteLoader{
  45. dockerCli: dockerCli,
  46. offline: offline,
  47. known: map[string]string{},
  48. }
  49. }
  50. type gitRemoteLoader struct {
  51. dockerCli command.Cli
  52. offline bool
  53. known map[string]string
  54. }
  55. func (g gitRemoteLoader) Accept(path string) bool {
  56. _, _, err := gitutil.ParseGitRef(path)
  57. return err == nil
  58. }
  59. var commitSHA = regexp.MustCompile(`^[a-f0-9]{40}$`)
  60. func (g gitRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  61. enabled, err := gitRemoteLoaderEnabled()
  62. if err != nil {
  63. return "", err
  64. }
  65. if !enabled {
  66. return "", fmt.Errorf("git remote resource is disabled by %q", GIT_REMOTE_ENABLED)
  67. }
  68. ref, _, err := gitutil.ParseGitRef(path)
  69. if err != nil {
  70. return "", err
  71. }
  72. local, ok := g.known[path]
  73. if !ok {
  74. if ref.Ref == "" {
  75. ref.Ref = "HEAD" // default branch
  76. }
  77. err = g.resolveGitRef(ctx, path, ref)
  78. if err != nil {
  79. return "", err
  80. }
  81. cache, err := cacheDir()
  82. if err != nil {
  83. return "", fmt.Errorf("initializing remote resource cache: %w", err)
  84. }
  85. local = filepath.Join(cache, ref.Ref)
  86. if _, err := os.Stat(local); os.IsNotExist(err) {
  87. if g.offline {
  88. return "", nil
  89. }
  90. err = g.checkout(ctx, local, ref)
  91. if err != nil {
  92. return "", err
  93. }
  94. }
  95. g.known[path] = local
  96. }
  97. if ref.SubDir != "" {
  98. local = filepath.Join(local, ref.SubDir)
  99. }
  100. stat, err := os.Stat(local)
  101. if err != nil {
  102. return "", err
  103. }
  104. if stat.IsDir() {
  105. local, err = findFile(cli.DefaultFileNames, local)
  106. }
  107. return local, err
  108. }
  109. func (g gitRemoteLoader) Dir(path string) string {
  110. return g.known[path]
  111. }
  112. func (g gitRemoteLoader) resolveGitRef(ctx context.Context, path string, ref *gitutil.GitRef) error {
  113. if !commitSHA.MatchString(ref.Ref) {
  114. cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", ref.Remote, ref.Ref)
  115. cmd.Env = g.gitCommandEnv()
  116. out, err := cmd.CombinedOutput()
  117. if err != nil {
  118. if cmd.ProcessState.ExitCode() == 2 {
  119. return fmt.Errorf("repository does not contain ref %s, output: %q: %w", path, string(out), err)
  120. }
  121. return fmt.Errorf("failed to access repository at %s:\n %s", ref.Remote, out)
  122. }
  123. if len(out) < 40 {
  124. return fmt.Errorf("unexpected git command output: %q", string(out))
  125. }
  126. sha := string(out[:40])
  127. if !commitSHA.MatchString(sha) {
  128. return fmt.Errorf("invalid commit sha %q", sha)
  129. }
  130. ref.Ref = sha
  131. }
  132. return nil
  133. }
  134. func (g gitRemoteLoader) checkout(ctx context.Context, path string, ref *gitutil.GitRef) error {
  135. err := os.MkdirAll(path, 0o700)
  136. if err != nil {
  137. return err
  138. }
  139. err = exec.CommandContext(ctx, "git", "init", path).Run()
  140. if err != nil {
  141. return err
  142. }
  143. cmd := exec.CommandContext(ctx, "git", "remote", "add", "origin", ref.Remote)
  144. cmd.Dir = path
  145. err = cmd.Run()
  146. if err != nil {
  147. return err
  148. }
  149. cmd = exec.CommandContext(ctx, "git", "fetch", "--depth=1", "origin", ref.Ref)
  150. cmd.Env = g.gitCommandEnv()
  151. cmd.Dir = path
  152. err = g.run(cmd)
  153. if err != nil {
  154. return err
  155. }
  156. cmd = exec.CommandContext(ctx, "git", "checkout", ref.Ref)
  157. cmd.Dir = path
  158. err = cmd.Run()
  159. if err != nil {
  160. return err
  161. }
  162. return nil
  163. }
  164. func (g gitRemoteLoader) run(cmd *exec.Cmd) error {
  165. if logrus.IsLevelEnabled(logrus.DebugLevel) {
  166. output, err := cmd.CombinedOutput()
  167. scanner := bufio.NewScanner(bytes.NewBuffer(output))
  168. for scanner.Scan() {
  169. line := scanner.Text()
  170. logrus.Debug(line)
  171. }
  172. return err
  173. }
  174. return cmd.Run()
  175. }
  176. func (g gitRemoteLoader) gitCommandEnv() []string {
  177. env := types.NewMapping(os.Environ())
  178. if env["GIT_TERMINAL_PROMPT"] == "" {
  179. // Disable prompting for passwords by Git until user explicitly asks for it.
  180. env["GIT_TERMINAL_PROMPT"] = "0"
  181. }
  182. if env["GIT_SSH"] == "" && env["GIT_SSH_COMMAND"] == "" {
  183. // Disable any ssh connection pooling by Git and do not attempt to prompt the user.
  184. env["GIT_SSH_COMMAND"] = "ssh -o ControlMaster=no -o BatchMode=yes"
  185. }
  186. v := env.Values()
  187. return v
  188. }
  189. func findFile(names []string, pwd string) (string, error) {
  190. for _, n := range names {
  191. f := filepath.Join(pwd, n)
  192. if fi, err := os.Stat(f); err == nil && !fi.IsDir() {
  193. return f, nil
  194. }
  195. }
  196. return "", api.ErrNotFound
  197. }
  198. var _ loader.ResourceLoader = gitRemoteLoader{}