gitutils_test.go 10 KB

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