gitutils_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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, err := os.MkdirTemp("", "docker-build-git-checkout")
  159. assert.NilError(t, err)
  160. defer os.RemoveAll(root)
  161. autocrlf := gitGetConfig("core.autocrlf")
  162. if !(autocrlf == "true" || autocrlf == "false" ||
  163. autocrlf == "input" || autocrlf == "") {
  164. t.Logf("unknown core.autocrlf value: \"%s\"", autocrlf)
  165. }
  166. eol := "\n"
  167. if autocrlf == "true" {
  168. eol = "\r\n"
  169. }
  170. gitDir := filepath.Join(root, "repo")
  171. _, err = git("init", gitDir)
  172. assert.NilError(t, err)
  173. _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com")
  174. assert.NilError(t, err)
  175. _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test")
  176. assert.NilError(t, err)
  177. err = os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644)
  178. assert.NilError(t, err)
  179. subDir := filepath.Join(gitDir, "subdir")
  180. assert.NilError(t, os.Mkdir(subDir, 0755))
  181. err = os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644)
  182. assert.NilError(t, err)
  183. if runtime.GOOS != "windows" {
  184. if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
  185. t.Fatal(err)
  186. }
  187. if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
  188. t.Fatal(err)
  189. }
  190. }
  191. _, err = gitWithinDir(gitDir, "add", "-A")
  192. assert.NilError(t, err)
  193. _, err = gitWithinDir(gitDir, "commit", "-am", "First commit")
  194. assert.NilError(t, err)
  195. _, err = gitWithinDir(gitDir, "checkout", "-b", "test")
  196. assert.NilError(t, err)
  197. err = os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644)
  198. assert.NilError(t, err)
  199. err = os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644)
  200. assert.NilError(t, err)
  201. _, err = gitWithinDir(gitDir, "add", "-A")
  202. assert.NilError(t, err)
  203. _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit")
  204. assert.NilError(t, err)
  205. _, err = gitWithinDir(gitDir, "checkout", "master")
  206. assert.NilError(t, err)
  207. // set up submodule
  208. subrepoDir := filepath.Join(root, "subrepo")
  209. _, err = git("init", subrepoDir)
  210. assert.NilError(t, err)
  211. _, err = gitWithinDir(subrepoDir, "config", "user.email", "test@docker.com")
  212. assert.NilError(t, err)
  213. _, err = gitWithinDir(subrepoDir, "config", "user.name", "Docker test")
  214. assert.NilError(t, err)
  215. err = os.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644)
  216. assert.NilError(t, err)
  217. _, err = gitWithinDir(subrepoDir, "add", "-A")
  218. assert.NilError(t, err)
  219. _, err = gitWithinDir(subrepoDir, "commit", "-am", "Subrepo initial")
  220. assert.NilError(t, err)
  221. cmd := exec.Command("git", "submodule", "add", subrepoDir, "sub") // this command doesn't work with --work-tree
  222. cmd.Dir = gitDir
  223. assert.NilError(t, cmd.Run())
  224. _, err = gitWithinDir(gitDir, "add", "-A")
  225. assert.NilError(t, err)
  226. _, err = gitWithinDir(gitDir, "commit", "-am", "With submodule")
  227. assert.NilError(t, err)
  228. type singleCase struct {
  229. frag string
  230. exp string
  231. fail bool
  232. submodule bool
  233. }
  234. cases := []singleCase{
  235. {"", "FROM scratch", false, true},
  236. {"master", "FROM scratch", false, true},
  237. {":subdir", "FROM scratch" + eol + "EXPOSE 5000", false, false},
  238. {":nosubdir", "", true, false}, // missing directory error
  239. {":Dockerfile", "", true, false}, // not a directory error
  240. {"master:nosubdir", "", true, false},
  241. {"master:subdir", "FROM scratch" + eol + "EXPOSE 5000", false, false},
  242. {"master:../subdir", "", true, false},
  243. {"test", "FROM scratch" + eol + "EXPOSE 3000", false, false},
  244. {"test:", "FROM scratch" + eol + "EXPOSE 3000", false, false},
  245. {"test:subdir", "FROM busybox" + eol + "EXPOSE 5000", false, false},
  246. }
  247. if runtime.GOOS != "windows" {
  248. // Windows GIT (2.7.1 x64) does not support parentlink/absolutelink. Sample output below
  249. // git --work-tree .\repo --git-dir .\repo\.git add -A
  250. // error: readlink("absolutelink"): Function not implemented
  251. // error: unable to index file absolutelink
  252. // fatal: adding files failed
  253. cases = append(cases, singleCase{frag: "master:absolutelink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
  254. cases = append(cases, singleCase{frag: "master:parentlink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
  255. }
  256. for _, c := range cases {
  257. ref, subdir := getRefAndSubdir(c.frag)
  258. r, err := cloneGitRepo(gitRepo{remote: gitDir, ref: ref, subdir: subdir})
  259. if c.fail {
  260. assert.Check(t, is.ErrorContains(err, ""))
  261. continue
  262. }
  263. assert.NilError(t, err)
  264. defer os.RemoveAll(r)
  265. if c.submodule {
  266. b, err := os.ReadFile(filepath.Join(r, "sub/subfile"))
  267. assert.NilError(t, err)
  268. assert.Check(t, is.Equal("subcontents", string(b)))
  269. } else {
  270. _, err := os.Stat(filepath.Join(r, "sub/subfile"))
  271. assert.Assert(t, is.ErrorContains(err, ""))
  272. assert.Assert(t, os.IsNotExist(err))
  273. }
  274. b, err := os.ReadFile(filepath.Join(r, "Dockerfile"))
  275. assert.NilError(t, err)
  276. assert.Check(t, is.Equal(c.exp, string(b)))
  277. }
  278. }
  279. func TestValidGitTransport(t *testing.T) {
  280. gitUrls := []string{
  281. "git://github.com/docker/docker",
  282. "git@github.com:docker/docker.git",
  283. "git@bitbucket.org:atlassianlabs/atlassian-docker.git",
  284. "https://github.com/docker/docker.git",
  285. "http://github.com/docker/docker.git",
  286. "http://github.com/docker/docker.git#branch",
  287. "http://github.com/docker/docker.git#:dir",
  288. }
  289. incompleteGitUrls := []string{
  290. "github.com/docker/docker",
  291. }
  292. for _, url := range gitUrls {
  293. if !isGitTransport(url) {
  294. t.Fatalf("%q should be detected as valid Git prefix", url)
  295. }
  296. }
  297. for _, url := range incompleteGitUrls {
  298. if isGitTransport(url) {
  299. t.Fatalf("%q should not be detected as valid Git prefix", url)
  300. }
  301. }
  302. }
  303. func TestGitInvalidRef(t *testing.T) {
  304. gitUrls := []string{
  305. "git://github.com/moby/moby#--foo bar",
  306. "git@github.com/moby/moby#--upload-pack=sleep;:",
  307. "git@g.com:a/b.git#-B",
  308. "git@g.com:a/b.git#with space",
  309. }
  310. for _, url := range gitUrls {
  311. _, err := Clone(url)
  312. assert.Assert(t, err != nil)
  313. assert.Check(t, is.Contains(strings.ToLower(err.Error()), "invalid refspec"))
  314. }
  315. }