gitutils_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. for _, tc := range tests {
  85. tc := tc
  86. t.Run(tc.doc, func(t *testing.T) {
  87. repo, err := parseRemoteURL(tc.url)
  88. assert.NilError(t, err)
  89. assert.Check(t, is.DeepEqual(tc.expected, repo, cmp.AllowUnexported(gitRepo{})))
  90. })
  91. }
  92. }
  93. func TestCloneArgsSmartHttp(t *testing.T) {
  94. mux := http.NewServeMux()
  95. server := httptest.NewServer(mux)
  96. serverURL, _ := url.Parse(server.URL)
  97. serverURL.Path = "/repo.git"
  98. mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
  99. q := r.URL.Query().Get("service")
  100. w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
  101. })
  102. args := fetchArgs(serverURL.String(), "master")
  103. exp := []string{"fetch", "--depth", "1", "origin", "--", "master"}
  104. assert.Check(t, is.DeepEqual(exp, args))
  105. }
  106. func TestCloneArgsDumbHttp(t *testing.T) {
  107. mux := http.NewServeMux()
  108. server := httptest.NewServer(mux)
  109. serverURL, _ := url.Parse(server.URL)
  110. serverURL.Path = "/repo.git"
  111. mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
  112. w.Header().Set("Content-Type", "text/plain")
  113. })
  114. args := fetchArgs(serverURL.String(), "master")
  115. exp := []string{"fetch", "origin", "--", "master"}
  116. assert.Check(t, is.DeepEqual(exp, args))
  117. }
  118. func TestCloneArgsGit(t *testing.T) {
  119. args := fetchArgs("git://github.com/docker/docker", "master")
  120. exp := []string{"fetch", "--depth", "1", "origin", "--", "master"}
  121. assert.Check(t, is.DeepEqual(exp, args))
  122. }
  123. func gitGetConfig(name string) string {
  124. b, err := git([]string{"config", "--get", name}...)
  125. if err != nil {
  126. // since we are interested in empty or non empty string,
  127. // we can safely ignore the err here.
  128. return ""
  129. }
  130. return strings.TrimSpace(string(b))
  131. }
  132. func TestCheckoutGit(t *testing.T) {
  133. root, err := ioutil.TempDir("", "docker-build-git-checkout")
  134. assert.NilError(t, err)
  135. defer os.RemoveAll(root)
  136. autocrlf := gitGetConfig("core.autocrlf")
  137. if !(autocrlf == "true" || autocrlf == "false" ||
  138. autocrlf == "input" || autocrlf == "") {
  139. t.Logf("unknown core.autocrlf value: \"%s\"", autocrlf)
  140. }
  141. eol := "\n"
  142. if autocrlf == "true" {
  143. eol = "\r\n"
  144. }
  145. gitDir := filepath.Join(root, "repo")
  146. _, err = git("init", gitDir)
  147. assert.NilError(t, err)
  148. _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com")
  149. assert.NilError(t, err)
  150. _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test")
  151. assert.NilError(t, err)
  152. err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644)
  153. assert.NilError(t, err)
  154. subDir := filepath.Join(gitDir, "subdir")
  155. assert.NilError(t, os.Mkdir(subDir, 0755))
  156. err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644)
  157. assert.NilError(t, err)
  158. if runtime.GOOS != "windows" {
  159. if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
  160. t.Fatal(err)
  161. }
  162. if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
  163. t.Fatal(err)
  164. }
  165. }
  166. _, err = gitWithinDir(gitDir, "add", "-A")
  167. assert.NilError(t, err)
  168. _, err = gitWithinDir(gitDir, "commit", "-am", "First commit")
  169. assert.NilError(t, err)
  170. _, err = gitWithinDir(gitDir, "checkout", "-b", "test")
  171. assert.NilError(t, err)
  172. err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644)
  173. assert.NilError(t, err)
  174. err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644)
  175. assert.NilError(t, err)
  176. _, err = gitWithinDir(gitDir, "add", "-A")
  177. assert.NilError(t, err)
  178. _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit")
  179. assert.NilError(t, err)
  180. _, err = gitWithinDir(gitDir, "checkout", "master")
  181. assert.NilError(t, err)
  182. // set up submodule
  183. subrepoDir := filepath.Join(root, "subrepo")
  184. _, err = git("init", subrepoDir)
  185. assert.NilError(t, err)
  186. _, err = gitWithinDir(subrepoDir, "config", "user.email", "test@docker.com")
  187. assert.NilError(t, err)
  188. _, err = gitWithinDir(subrepoDir, "config", "user.name", "Docker test")
  189. assert.NilError(t, err)
  190. err = ioutil.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644)
  191. assert.NilError(t, err)
  192. _, err = gitWithinDir(subrepoDir, "add", "-A")
  193. assert.NilError(t, err)
  194. _, err = gitWithinDir(subrepoDir, "commit", "-am", "Subrepo initial")
  195. assert.NilError(t, err)
  196. cmd := exec.Command("git", "submodule", "add", subrepoDir, "sub") // this command doesn't work with --work-tree
  197. cmd.Dir = gitDir
  198. assert.NilError(t, cmd.Run())
  199. _, err = gitWithinDir(gitDir, "add", "-A")
  200. assert.NilError(t, err)
  201. _, err = gitWithinDir(gitDir, "commit", "-am", "With submodule")
  202. assert.NilError(t, err)
  203. type singleCase struct {
  204. frag string
  205. exp string
  206. fail bool
  207. submodule bool
  208. }
  209. cases := []singleCase{
  210. {"", "FROM scratch", false, true},
  211. {"master", "FROM scratch", false, true},
  212. {":subdir", "FROM scratch" + eol + "EXPOSE 5000", false, false},
  213. {":nosubdir", "", true, false}, // missing directory error
  214. {":Dockerfile", "", true, false}, // not a directory error
  215. {"master:nosubdir", "", true, false},
  216. {"master:subdir", "FROM scratch" + eol + "EXPOSE 5000", false, false},
  217. {"master:../subdir", "", true, false},
  218. {"test", "FROM scratch" + eol + "EXPOSE 3000", false, false},
  219. {"test:", "FROM scratch" + eol + "EXPOSE 3000", false, false},
  220. {"test:subdir", "FROM busybox" + eol + "EXPOSE 5000", false, false},
  221. }
  222. if runtime.GOOS != "windows" {
  223. // Windows GIT (2.7.1 x64) does not support parentlink/absolutelink. Sample output below
  224. // git --work-tree .\repo --git-dir .\repo\.git add -A
  225. // error: readlink("absolutelink"): Function not implemented
  226. // error: unable to index file absolutelink
  227. // fatal: adding files failed
  228. cases = append(cases, singleCase{frag: "master:absolutelink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
  229. cases = append(cases, singleCase{frag: "master:parentlink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
  230. }
  231. for _, c := range cases {
  232. ref, subdir := getRefAndSubdir(c.frag)
  233. r, err := cloneGitRepo(gitRepo{remote: gitDir, ref: ref, subdir: subdir})
  234. if c.fail {
  235. assert.Check(t, is.ErrorContains(err, ""))
  236. continue
  237. }
  238. assert.NilError(t, err)
  239. defer os.RemoveAll(r)
  240. if c.submodule {
  241. b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile"))
  242. assert.NilError(t, err)
  243. assert.Check(t, is.Equal("subcontents", string(b)))
  244. } else {
  245. _, err := os.Stat(filepath.Join(r, "sub/subfile"))
  246. assert.Assert(t, is.ErrorContains(err, ""))
  247. assert.Assert(t, os.IsNotExist(err))
  248. }
  249. b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
  250. assert.NilError(t, err)
  251. assert.Check(t, is.Equal(c.exp, string(b)))
  252. }
  253. }
  254. func TestValidGitTransport(t *testing.T) {
  255. gitUrls := []string{
  256. "git://github.com/docker/docker",
  257. "git@github.com:docker/docker.git",
  258. "git@bitbucket.org:atlassianlabs/atlassian-docker.git",
  259. "https://github.com/docker/docker.git",
  260. "http://github.com/docker/docker.git",
  261. "http://github.com/docker/docker.git#branch",
  262. "http://github.com/docker/docker.git#:dir",
  263. }
  264. incompleteGitUrls := []string{
  265. "github.com/docker/docker",
  266. }
  267. for _, url := range gitUrls {
  268. if !isGitTransport(url) {
  269. t.Fatalf("%q should be detected as valid Git prefix", url)
  270. }
  271. }
  272. for _, url := range incompleteGitUrls {
  273. if isGitTransport(url) {
  274. t.Fatalf("%q should not be detected as valid Git prefix", url)
  275. }
  276. }
  277. }
  278. func TestGitInvalidRef(t *testing.T) {
  279. gitUrls := []string{
  280. "git://github.com/moby/moby#--foo bar",
  281. "git@github.com/moby/moby#--upload-pack=sleep;:",
  282. "git@g.com:a/b.git#-B",
  283. "git@g.com:a/b.git#with space",
  284. }
  285. for _, url := range gitUrls {
  286. _, err := Clone(url)
  287. assert.Assert(t, err != nil)
  288. assert.Check(t, is.Contains(strings.ToLower(err.Error()), "invalid refspec"))
  289. }
  290. }