gitutils_test.go 9.3 KB

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