gitutils_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package git // import "github.com/docker/docker/builder/remotecontext/git"
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/url"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "testing"
  13. "github.com/google/go-cmp/cmp"
  14. "gotest.tools/v3/assert"
  15. is "gotest.tools/v3/assert/cmp"
  16. )
  17. func TestParseRemoteURL(t *testing.T) {
  18. tests := []struct {
  19. doc string
  20. url string
  21. expected gitRepo
  22. }{
  23. {
  24. doc: "git scheme uppercase, no url-fragment",
  25. url: "GIT://github.com/user/repo.git",
  26. expected: gitRepo{
  27. remote: "git://github.com/user/repo.git",
  28. ref: "master",
  29. },
  30. },
  31. {
  32. doc: "git scheme, no url-fragment",
  33. url: "git://github.com/user/repo.git",
  34. expected: gitRepo{
  35. remote: "git://github.com/user/repo.git",
  36. ref: "master",
  37. },
  38. },
  39. {
  40. doc: "git scheme, with url-fragment",
  41. url: "git://github.com/user/repo.git#mybranch:mydir/mysubdir/",
  42. expected: gitRepo{
  43. remote: "git://github.com/user/repo.git",
  44. ref: "mybranch",
  45. subdir: "mydir/mysubdir/",
  46. },
  47. },
  48. {
  49. doc: "https scheme, no url-fragment",
  50. url: "https://github.com/user/repo.git",
  51. expected: gitRepo{
  52. remote: "https://github.com/user/repo.git",
  53. ref: "master",
  54. },
  55. },
  56. {
  57. doc: "https scheme, with url-fragment",
  58. url: "https://github.com/user/repo.git#mybranch:mydir/mysubdir/",
  59. expected: gitRepo{
  60. remote: "https://github.com/user/repo.git",
  61. ref: "mybranch",
  62. subdir: "mydir/mysubdir/",
  63. },
  64. },
  65. {
  66. doc: "git@, no url-fragment",
  67. url: "git@github.com:user/repo.git",
  68. expected: gitRepo{
  69. remote: "git@github.com:user/repo.git",
  70. ref: "master",
  71. },
  72. },
  73. {
  74. doc: "git@, with url-fragment",
  75. url: "git@github.com:user/repo.git#mybranch:mydir/mysubdir/",
  76. expected: gitRepo{
  77. remote: "git@github.com:user/repo.git",
  78. ref: "mybranch",
  79. subdir: "mydir/mysubdir/",
  80. },
  81. },
  82. {
  83. doc: "ssh, no url-fragment",
  84. url: "ssh://github.com/user/repo.git",
  85. expected: gitRepo{
  86. remote: "ssh://github.com/user/repo.git",
  87. ref: "master",
  88. },
  89. },
  90. {
  91. doc: "ssh, with url-fragment",
  92. url: "ssh://github.com/user/repo.git#mybranch:mydir/mysubdir/",
  93. expected: gitRepo{
  94. remote: "ssh://github.com/user/repo.git",
  95. ref: "mybranch",
  96. subdir: "mydir/mysubdir/",
  97. },
  98. },
  99. {
  100. doc: "ssh, with url-fragment and user",
  101. url: "ssh://foo%40barcorp.com@github.com/user/repo.git#mybranch:mydir/mysubdir/",
  102. expected: gitRepo{
  103. remote: "ssh://foo%40barcorp.com@github.com/user/repo.git",
  104. ref: "mybranch",
  105. subdir: "mydir/mysubdir/",
  106. },
  107. },
  108. }
  109. for _, tc := range tests {
  110. tc := tc
  111. t.Run(tc.doc, func(t *testing.T) {
  112. repo, err := parseRemoteURL(tc.url)
  113. assert.NilError(t, err)
  114. assert.Check(t, is.DeepEqual(tc.expected, repo, cmp.AllowUnexported(gitRepo{})))
  115. })
  116. }
  117. }
  118. func TestCloneArgsSmartHttp(t *testing.T) {
  119. mux := http.NewServeMux()
  120. server := httptest.NewServer(mux)
  121. serverURL, _ := url.Parse(server.URL)
  122. serverURL.Path = "/repo.git"
  123. mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
  124. q := r.URL.Query().Get("service")
  125. w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
  126. })
  127. args := fetchArgs(serverURL.String(), "master")
  128. exp := []string{"fetch", "--depth", "1", "origin", "--", "master"}
  129. assert.Check(t, is.DeepEqual(exp, args))
  130. }
  131. func TestCloneArgsDumbHttp(t *testing.T) {
  132. mux := http.NewServeMux()
  133. server := httptest.NewServer(mux)
  134. serverURL, _ := url.Parse(server.URL)
  135. serverURL.Path = "/repo.git"
  136. mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
  137. w.Header().Set("Content-Type", "text/plain")
  138. })
  139. args := fetchArgs(serverURL.String(), "master")
  140. exp := []string{"fetch", "origin", "--", "master"}
  141. assert.Check(t, is.DeepEqual(exp, args))
  142. }
  143. func TestCloneArgsGit(t *testing.T) {
  144. args := fetchArgs("git://github.com/docker/docker", "master")
  145. exp := []string{"fetch", "--depth", "1", "origin", "--", "master"}
  146. assert.Check(t, is.DeepEqual(exp, args))
  147. }
  148. func gitGetConfig(name string) string {
  149. b, err := git([]string{"config", "--get", name}...)
  150. if err != nil {
  151. // since we are interested in empty or non empty string,
  152. // we can safely ignore the err here.
  153. return ""
  154. }
  155. return strings.TrimSpace(string(b))
  156. }
  157. func TestCheckoutGit(t *testing.T) {
  158. root := t.TempDir()
  159. autocrlf := gitGetConfig("core.autocrlf")
  160. if !(autocrlf == "true" || autocrlf == "false" ||
  161. autocrlf == "input" || autocrlf == "") {
  162. t.Logf("unknown core.autocrlf value: \"%s\"", autocrlf)
  163. }
  164. eol := "\n"
  165. if autocrlf == "true" {
  166. eol = "\r\n"
  167. }
  168. must := func(out []byte, err error) {
  169. t.Helper()
  170. if len(out) > 0 {
  171. t.Logf("%s", out)
  172. }
  173. assert.NilError(t, err)
  174. }
  175. gitDir := filepath.Join(root, "repo")
  176. must(git("-c", "init.defaultBranch=master", "init", gitDir))
  177. must(gitWithinDir(gitDir, "config", "user.email", "test@docker.com"))
  178. must(gitWithinDir(gitDir, "config", "user.name", "Docker test"))
  179. assert.NilError(t, os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644))
  180. subDir := filepath.Join(gitDir, "subdir")
  181. assert.NilError(t, os.Mkdir(subDir, 0755))
  182. assert.NilError(t, os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644))
  183. if runtime.GOOS != "windows" {
  184. assert.NilError(t, os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")))
  185. assert.NilError(t, os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")))
  186. }
  187. must(gitWithinDir(gitDir, "add", "-A"))
  188. must(gitWithinDir(gitDir, "commit", "-am", "First commit"))
  189. must(gitWithinDir(gitDir, "checkout", "-b", "test"))
  190. assert.NilError(t, os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644))
  191. assert.NilError(t, os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644))
  192. must(gitWithinDir(gitDir, "add", "-A"))
  193. must(gitWithinDir(gitDir, "commit", "-am", "Branch commit"))
  194. must(gitWithinDir(gitDir, "checkout", "master"))
  195. // set up submodule
  196. subrepoDir := filepath.Join(root, "subrepo")
  197. must(git("-c", "init.defaultBranch=master", "init", subrepoDir))
  198. must(gitWithinDir(subrepoDir, "config", "user.email", "test@docker.com"))
  199. must(gitWithinDir(subrepoDir, "config", "user.name", "Docker test"))
  200. assert.NilError(t, os.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644))
  201. must(gitWithinDir(subrepoDir, "add", "-A"))
  202. must(gitWithinDir(subrepoDir, "commit", "-am", "Subrepo initial"))
  203. cmd := exec.Command("git", "submodule", "add", subrepoDir, "sub") // this command doesn't work with --work-tree
  204. cmd.Dir = gitDir
  205. must(cmd.CombinedOutput())
  206. must(gitWithinDir(gitDir, "add", "-A"))
  207. must(gitWithinDir(gitDir, "commit", "-am", "With submodule"))
  208. type singleCase struct {
  209. frag string
  210. exp string
  211. fail bool
  212. submodule bool
  213. }
  214. cases := []singleCase{
  215. {"", "FROM scratch", false, true},
  216. {"master", "FROM scratch", false, true},
  217. {":subdir", "FROM scratch" + eol + "EXPOSE 5000", false, false},
  218. {":nosubdir", "", true, false}, // missing directory error
  219. {":Dockerfile", "", true, false}, // not a directory error
  220. {"master:nosubdir", "", true, false},
  221. {"master:subdir", "FROM scratch" + eol + "EXPOSE 5000", false, false},
  222. {"master:../subdir", "", true, false},
  223. {"test", "FROM scratch" + eol + "EXPOSE 3000", false, false},
  224. {"test:", "FROM scratch" + eol + "EXPOSE 3000", false, false},
  225. {"test:subdir", "FROM busybox" + eol + "EXPOSE 5000", false, false},
  226. }
  227. if runtime.GOOS != "windows" {
  228. // Windows GIT (2.7.1 x64) does not support parentlink/absolutelink. Sample output below
  229. // git --work-tree .\repo --git-dir .\repo\.git add -A
  230. // error: readlink("absolutelink"): Function not implemented
  231. // error: unable to index file absolutelink
  232. // fatal: adding files failed
  233. cases = append(cases, singleCase{frag: "master:absolutelink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
  234. cases = append(cases, singleCase{frag: "master:parentlink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
  235. }
  236. for _, c := range cases {
  237. t.Run(c.frag, func(t *testing.T) {
  238. ref, subdir := getRefAndSubdir(c.frag)
  239. r, err := cloneGitRepo(gitRepo{remote: gitDir, ref: ref, subdir: subdir})
  240. if c.fail {
  241. assert.Check(t, is.ErrorContains(err, ""))
  242. return
  243. }
  244. assert.NilError(t, err)
  245. defer os.RemoveAll(r)
  246. if c.submodule {
  247. b, err := os.ReadFile(filepath.Join(r, "sub/subfile"))
  248. assert.NilError(t, err)
  249. assert.Check(t, is.Equal("subcontents", string(b)))
  250. } else {
  251. _, err := os.Stat(filepath.Join(r, "sub/subfile"))
  252. assert.Assert(t, is.ErrorContains(err, ""))
  253. assert.Assert(t, os.IsNotExist(err))
  254. }
  255. b, err := os.ReadFile(filepath.Join(r, "Dockerfile"))
  256. assert.NilError(t, err)
  257. assert.Check(t, is.Equal(c.exp, string(b)))
  258. })
  259. }
  260. }
  261. func TestValidGitTransport(t *testing.T) {
  262. gitUrls := []string{
  263. "git://github.com/docker/docker",
  264. "git@github.com:docker/docker.git",
  265. "git@bitbucket.org:atlassianlabs/atlassian-docker.git",
  266. "https://github.com/docker/docker.git",
  267. "http://github.com/docker/docker.git",
  268. "http://github.com/docker/docker.git#branch",
  269. "http://github.com/docker/docker.git#:dir",
  270. }
  271. incompleteGitUrls := []string{
  272. "github.com/docker/docker",
  273. }
  274. for _, url := range gitUrls {
  275. if !isGitTransport(url) {
  276. t.Fatalf("%q should be detected as valid Git prefix", url)
  277. }
  278. }
  279. for _, url := range incompleteGitUrls {
  280. if isGitTransport(url) {
  281. t.Fatalf("%q should not be detected as valid Git prefix", url)
  282. }
  283. }
  284. }
  285. func TestGitInvalidRef(t *testing.T) {
  286. gitUrls := []string{
  287. "git://github.com/moby/moby#--foo bar",
  288. "git@github.com/moby/moby#--upload-pack=sleep;:",
  289. "git@g.com:a/b.git#-B",
  290. "git@g.com:a/b.git#with space",
  291. }
  292. for _, url := range gitUrls {
  293. _, err := Clone(url)
  294. assert.Assert(t, err != nil)
  295. assert.Check(t, is.Contains(strings.ToLower(err.Error()), "invalid refspec"))
  296. }
  297. }