archive_test.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. package archive
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/stretchr/testify/assert"
  16. "github.com/stretchr/testify/require"
  17. )
  18. var tmp string
  19. func init() {
  20. tmp = "/tmp/"
  21. if runtime.GOOS == "windows" {
  22. tmp = os.Getenv("TEMP") + `\`
  23. }
  24. }
  25. func TestIsArchiveNilHeader(t *testing.T) {
  26. out := IsArchive(nil)
  27. if out {
  28. t.Fatalf("isArchive should return false as nil is not a valid archive header")
  29. }
  30. }
  31. func TestIsArchiveInvalidHeader(t *testing.T) {
  32. header := []byte{0x00, 0x01, 0x02}
  33. out := IsArchive(header)
  34. if out {
  35. t.Fatalf("isArchive should return false as %s is not a valid archive header", header)
  36. }
  37. }
  38. func TestIsArchiveBzip2(t *testing.T) {
  39. header := []byte{0x42, 0x5A, 0x68}
  40. out := IsArchive(header)
  41. if !out {
  42. t.Fatalf("isArchive should return true as %s is a bz2 header", header)
  43. }
  44. }
  45. func TestIsArchive7zip(t *testing.T) {
  46. header := []byte{0x50, 0x4b, 0x03, 0x04}
  47. out := IsArchive(header)
  48. if out {
  49. t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header)
  50. }
  51. }
  52. func TestIsArchivePathDir(t *testing.T) {
  53. cmd := exec.Command("sh", "-c", "mkdir -p /tmp/archivedir")
  54. output, err := cmd.CombinedOutput()
  55. if err != nil {
  56. t.Fatalf("Fail to create an archive file for test : %s.", output)
  57. }
  58. if IsArchivePath(tmp + "archivedir") {
  59. t.Fatalf("Incorrectly recognised directory as an archive")
  60. }
  61. }
  62. func TestIsArchivePathInvalidFile(t *testing.T) {
  63. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1024 count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz")
  64. output, err := cmd.CombinedOutput()
  65. if err != nil {
  66. t.Fatalf("Fail to create an archive file for test : %s.", output)
  67. }
  68. if IsArchivePath(tmp + "archive") {
  69. t.Fatalf("Incorrectly recognised invalid tar path as archive")
  70. }
  71. if IsArchivePath(tmp + "archive.gz") {
  72. t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
  73. }
  74. }
  75. func TestIsArchivePathTar(t *testing.T) {
  76. var whichTar string
  77. if runtime.GOOS == "solaris" {
  78. whichTar = "gtar"
  79. } else {
  80. whichTar = "tar"
  81. }
  82. cmdStr := fmt.Sprintf("touch /tmp/archivedata && %s -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz", whichTar)
  83. cmd := exec.Command("sh", "-c", cmdStr)
  84. output, err := cmd.CombinedOutput()
  85. if err != nil {
  86. t.Fatalf("Fail to create an archive file for test : %s.", output)
  87. }
  88. if !IsArchivePath(tmp + "/archive") {
  89. t.Fatalf("Did not recognise valid tar path as archive")
  90. }
  91. if !IsArchivePath(tmp + "archive.gz") {
  92. t.Fatalf("Did not recognise valid compressed tar path as archive")
  93. }
  94. }
  95. func testDecompressStream(t *testing.T, ext, compressCommand string) {
  96. cmd := exec.Command("sh", "-c",
  97. fmt.Sprintf("touch /tmp/archive && %s /tmp/archive", compressCommand))
  98. output, err := cmd.CombinedOutput()
  99. if err != nil {
  100. t.Fatalf("Failed to create an archive file for test : %s.", output)
  101. }
  102. filename := "archive." + ext
  103. archive, err := os.Open(tmp + filename)
  104. if err != nil {
  105. t.Fatalf("Failed to open file %s: %v", filename, err)
  106. }
  107. defer archive.Close()
  108. r, err := DecompressStream(archive)
  109. if err != nil {
  110. t.Fatalf("Failed to decompress %s: %v", filename, err)
  111. }
  112. if _, err = ioutil.ReadAll(r); err != nil {
  113. t.Fatalf("Failed to read the decompressed stream: %v ", err)
  114. }
  115. if err = r.Close(); err != nil {
  116. t.Fatalf("Failed to close the decompressed stream: %v ", err)
  117. }
  118. }
  119. func TestDecompressStreamGzip(t *testing.T) {
  120. testDecompressStream(t, "gz", "gzip -f")
  121. }
  122. func TestDecompressStreamBzip2(t *testing.T) {
  123. testDecompressStream(t, "bz2", "bzip2 -f")
  124. }
  125. func TestDecompressStreamXz(t *testing.T) {
  126. if runtime.GOOS == "windows" {
  127. t.Skip("Xz not present in msys2")
  128. }
  129. testDecompressStream(t, "xz", "xz -f")
  130. }
  131. func TestCompressStreamXzUnsupported(t *testing.T) {
  132. dest, err := os.Create(tmp + "dest")
  133. if err != nil {
  134. t.Fatalf("Fail to create the destination file")
  135. }
  136. defer dest.Close()
  137. _, err = CompressStream(dest, Xz)
  138. if err == nil {
  139. t.Fatalf("Should fail as xz is unsupported for compression format.")
  140. }
  141. }
  142. func TestCompressStreamBzip2Unsupported(t *testing.T) {
  143. dest, err := os.Create(tmp + "dest")
  144. if err != nil {
  145. t.Fatalf("Fail to create the destination file")
  146. }
  147. defer dest.Close()
  148. _, err = CompressStream(dest, Xz)
  149. if err == nil {
  150. t.Fatalf("Should fail as xz is unsupported for compression format.")
  151. }
  152. }
  153. func TestCompressStreamInvalid(t *testing.T) {
  154. dest, err := os.Create(tmp + "dest")
  155. if err != nil {
  156. t.Fatalf("Fail to create the destination file")
  157. }
  158. defer dest.Close()
  159. _, err = CompressStream(dest, -1)
  160. if err == nil {
  161. t.Fatalf("Should fail as xz is unsupported for compression format.")
  162. }
  163. }
  164. func TestExtensionInvalid(t *testing.T) {
  165. compression := Compression(-1)
  166. output := compression.Extension()
  167. if output != "" {
  168. t.Fatalf("The extension of an invalid compression should be an empty string.")
  169. }
  170. }
  171. func TestExtensionUncompressed(t *testing.T) {
  172. compression := Uncompressed
  173. output := compression.Extension()
  174. if output != "tar" {
  175. t.Fatalf("The extension of an uncompressed archive should be 'tar'.")
  176. }
  177. }
  178. func TestExtensionBzip2(t *testing.T) {
  179. compression := Bzip2
  180. output := compression.Extension()
  181. if output != "tar.bz2" {
  182. t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'")
  183. }
  184. }
  185. func TestExtensionGzip(t *testing.T) {
  186. compression := Gzip
  187. output := compression.Extension()
  188. if output != "tar.gz" {
  189. t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
  190. }
  191. }
  192. func TestExtensionXz(t *testing.T) {
  193. compression := Xz
  194. output := compression.Extension()
  195. if output != "tar.xz" {
  196. t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
  197. }
  198. }
  199. func TestCmdStreamLargeStderr(t *testing.T) {
  200. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
  201. out, _, err := cmdStream(cmd, nil)
  202. if err != nil {
  203. t.Fatalf("Failed to start command: %s", err)
  204. }
  205. errCh := make(chan error)
  206. go func() {
  207. _, err := io.Copy(ioutil.Discard, out)
  208. errCh <- err
  209. }()
  210. select {
  211. case err := <-errCh:
  212. if err != nil {
  213. t.Fatalf("Command should not have failed (err=%.100s...)", err)
  214. }
  215. case <-time.After(5 * time.Second):
  216. t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
  217. }
  218. }
  219. func TestCmdStreamBad(t *testing.T) {
  220. // TODO Windows: Figure out why this is failing in CI but not locally
  221. if runtime.GOOS == "windows" {
  222. t.Skip("Failing on Windows CI machines")
  223. }
  224. badCmd := exec.Command("sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
  225. out, _, err := cmdStream(badCmd, nil)
  226. if err != nil {
  227. t.Fatalf("Failed to start command: %s", err)
  228. }
  229. if output, err := ioutil.ReadAll(out); err == nil {
  230. t.Fatalf("Command should have failed")
  231. } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
  232. t.Fatalf("Wrong error value (%s)", err)
  233. } else if s := string(output); s != "hello\n" {
  234. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  235. }
  236. }
  237. func TestCmdStreamGood(t *testing.T) {
  238. cmd := exec.Command("sh", "-c", "echo hello; exit 0")
  239. out, _, err := cmdStream(cmd, nil)
  240. if err != nil {
  241. t.Fatal(err)
  242. }
  243. if output, err := ioutil.ReadAll(out); err != nil {
  244. t.Fatalf("Command should not have failed (err=%s)", err)
  245. } else if s := string(output); s != "hello\n" {
  246. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  247. }
  248. }
  249. func TestUntarPathWithInvalidDest(t *testing.T) {
  250. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  251. if err != nil {
  252. t.Fatal(err)
  253. }
  254. defer os.RemoveAll(tempFolder)
  255. invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
  256. // Create a src file
  257. srcFile := filepath.Join(tempFolder, "src")
  258. tarFile := filepath.Join(tempFolder, "src.tar")
  259. os.Create(srcFile)
  260. os.Create(invalidDestFolder) // being a file (not dir) should cause an error
  261. // Translate back to Unix semantics as next exec.Command is run under sh
  262. srcFileU := srcFile
  263. tarFileU := tarFile
  264. if runtime.GOOS == "windows" {
  265. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  266. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  267. }
  268. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  269. _, err = cmd.CombinedOutput()
  270. if err != nil {
  271. t.Fatal(err)
  272. }
  273. err = UntarPath(tarFile, invalidDestFolder)
  274. if err == nil {
  275. t.Fatalf("UntarPath with invalid destination path should throw an error.")
  276. }
  277. }
  278. func TestUntarPathWithInvalidSrc(t *testing.T) {
  279. dest, err := ioutil.TempDir("", "docker-archive-test")
  280. if err != nil {
  281. t.Fatalf("Fail to create the destination file")
  282. }
  283. defer os.RemoveAll(dest)
  284. err = UntarPath("/invalid/path", dest)
  285. if err == nil {
  286. t.Fatalf("UntarPath with invalid src path should throw an error.")
  287. }
  288. }
  289. func TestUntarPath(t *testing.T) {
  290. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  291. if err != nil {
  292. t.Fatal(err)
  293. }
  294. defer os.RemoveAll(tmpFolder)
  295. srcFile := filepath.Join(tmpFolder, "src")
  296. tarFile := filepath.Join(tmpFolder, "src.tar")
  297. os.Create(filepath.Join(tmpFolder, "src"))
  298. destFolder := filepath.Join(tmpFolder, "dest")
  299. err = os.MkdirAll(destFolder, 0740)
  300. if err != nil {
  301. t.Fatalf("Fail to create the destination file")
  302. }
  303. // Translate back to Unix semantics as next exec.Command is run under sh
  304. srcFileU := srcFile
  305. tarFileU := tarFile
  306. if runtime.GOOS == "windows" {
  307. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  308. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  309. }
  310. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  311. _, err = cmd.CombinedOutput()
  312. if err != nil {
  313. t.Fatal(err)
  314. }
  315. err = UntarPath(tarFile, destFolder)
  316. if err != nil {
  317. t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
  318. }
  319. expectedFile := filepath.Join(destFolder, srcFileU)
  320. _, err = os.Stat(expectedFile)
  321. if err != nil {
  322. t.Fatalf("Destination folder should contain the source file but did not.")
  323. }
  324. }
  325. // Do the same test as above but with the destination as file, it should fail
  326. func TestUntarPathWithDestinationFile(t *testing.T) {
  327. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  328. if err != nil {
  329. t.Fatal(err)
  330. }
  331. defer os.RemoveAll(tmpFolder)
  332. srcFile := filepath.Join(tmpFolder, "src")
  333. tarFile := filepath.Join(tmpFolder, "src.tar")
  334. os.Create(filepath.Join(tmpFolder, "src"))
  335. // Translate back to Unix semantics as next exec.Command is run under sh
  336. srcFileU := srcFile
  337. tarFileU := tarFile
  338. if runtime.GOOS == "windows" {
  339. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  340. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  341. }
  342. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  343. _, err = cmd.CombinedOutput()
  344. if err != nil {
  345. t.Fatal(err)
  346. }
  347. destFile := filepath.Join(tmpFolder, "dest")
  348. _, err = os.Create(destFile)
  349. if err != nil {
  350. t.Fatalf("Fail to create the destination file")
  351. }
  352. err = UntarPath(tarFile, destFile)
  353. if err == nil {
  354. t.Fatalf("UntarPath should throw an error if the destination if a file")
  355. }
  356. }
  357. // Do the same test as above but with the destination folder already exists
  358. // and the destination file is a directory
  359. // It's working, see https://github.com/docker/docker/issues/10040
  360. func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
  361. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  362. if err != nil {
  363. t.Fatal(err)
  364. }
  365. defer os.RemoveAll(tmpFolder)
  366. srcFile := filepath.Join(tmpFolder, "src")
  367. tarFile := filepath.Join(tmpFolder, "src.tar")
  368. os.Create(srcFile)
  369. // Translate back to Unix semantics as next exec.Command is run under sh
  370. srcFileU := srcFile
  371. tarFileU := tarFile
  372. if runtime.GOOS == "windows" {
  373. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  374. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  375. }
  376. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  377. _, err = cmd.CombinedOutput()
  378. if err != nil {
  379. t.Fatal(err)
  380. }
  381. destFolder := filepath.Join(tmpFolder, "dest")
  382. err = os.MkdirAll(destFolder, 0740)
  383. if err != nil {
  384. t.Fatalf("Fail to create the destination folder")
  385. }
  386. // Let's create a folder that will has the same path as the extracted file (from tar)
  387. destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
  388. err = os.MkdirAll(destSrcFileAsFolder, 0740)
  389. if err != nil {
  390. t.Fatal(err)
  391. }
  392. err = UntarPath(tarFile, destFolder)
  393. if err != nil {
  394. t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
  395. }
  396. }
  397. func TestCopyWithTarInvalidSrc(t *testing.T) {
  398. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  399. if err != nil {
  400. t.Fatal(nil)
  401. }
  402. destFolder := filepath.Join(tempFolder, "dest")
  403. invalidSrc := filepath.Join(tempFolder, "doesnotexists")
  404. err = os.MkdirAll(destFolder, 0740)
  405. if err != nil {
  406. t.Fatal(err)
  407. }
  408. err = CopyWithTar(invalidSrc, destFolder)
  409. if err == nil {
  410. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  411. }
  412. }
  413. func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
  414. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  415. if err != nil {
  416. t.Fatal(nil)
  417. }
  418. srcFolder := filepath.Join(tempFolder, "src")
  419. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  420. err = os.MkdirAll(srcFolder, 0740)
  421. if err != nil {
  422. t.Fatal(err)
  423. }
  424. err = CopyWithTar(srcFolder, inexistentDestFolder)
  425. if err != nil {
  426. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  427. }
  428. _, err = os.Stat(inexistentDestFolder)
  429. if err != nil {
  430. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  431. }
  432. }
  433. // Test CopyWithTar with a file as src
  434. func TestCopyWithTarSrcFile(t *testing.T) {
  435. folder, err := ioutil.TempDir("", "docker-archive-test")
  436. if err != nil {
  437. t.Fatal(err)
  438. }
  439. defer os.RemoveAll(folder)
  440. dest := filepath.Join(folder, "dest")
  441. srcFolder := filepath.Join(folder, "src")
  442. src := filepath.Join(folder, filepath.Join("src", "src"))
  443. err = os.MkdirAll(srcFolder, 0740)
  444. if err != nil {
  445. t.Fatal(err)
  446. }
  447. err = os.MkdirAll(dest, 0740)
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. ioutil.WriteFile(src, []byte("content"), 0777)
  452. err = CopyWithTar(src, dest)
  453. if err != nil {
  454. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  455. }
  456. _, err = os.Stat(dest)
  457. // FIXME Check the content
  458. if err != nil {
  459. t.Fatalf("Destination file should be the same as the source.")
  460. }
  461. }
  462. // Test CopyWithTar with a folder as src
  463. func TestCopyWithTarSrcFolder(t *testing.T) {
  464. folder, err := ioutil.TempDir("", "docker-archive-test")
  465. if err != nil {
  466. t.Fatal(err)
  467. }
  468. defer os.RemoveAll(folder)
  469. dest := filepath.Join(folder, "dest")
  470. src := filepath.Join(folder, filepath.Join("src", "folder"))
  471. err = os.MkdirAll(src, 0740)
  472. if err != nil {
  473. t.Fatal(err)
  474. }
  475. err = os.MkdirAll(dest, 0740)
  476. if err != nil {
  477. t.Fatal(err)
  478. }
  479. ioutil.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777)
  480. err = CopyWithTar(src, dest)
  481. if err != nil {
  482. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  483. }
  484. _, err = os.Stat(dest)
  485. // FIXME Check the content (the file inside)
  486. if err != nil {
  487. t.Fatalf("Destination folder should contain the source file but did not.")
  488. }
  489. }
  490. func TestCopyFileWithTarInvalidSrc(t *testing.T) {
  491. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  492. if err != nil {
  493. t.Fatal(err)
  494. }
  495. defer os.RemoveAll(tempFolder)
  496. destFolder := filepath.Join(tempFolder, "dest")
  497. err = os.MkdirAll(destFolder, 0740)
  498. if err != nil {
  499. t.Fatal(err)
  500. }
  501. invalidFile := filepath.Join(tempFolder, "doesnotexists")
  502. err = CopyFileWithTar(invalidFile, destFolder)
  503. if err == nil {
  504. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  505. }
  506. }
  507. func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
  508. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  509. if err != nil {
  510. t.Fatal(nil)
  511. }
  512. defer os.RemoveAll(tempFolder)
  513. srcFile := filepath.Join(tempFolder, "src")
  514. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  515. _, err = os.Create(srcFile)
  516. if err != nil {
  517. t.Fatal(err)
  518. }
  519. err = CopyFileWithTar(srcFile, inexistentDestFolder)
  520. if err != nil {
  521. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  522. }
  523. _, err = os.Stat(inexistentDestFolder)
  524. if err != nil {
  525. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  526. }
  527. // FIXME Test the src file and content
  528. }
  529. func TestCopyFileWithTarSrcFolder(t *testing.T) {
  530. folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test")
  531. if err != nil {
  532. t.Fatal(err)
  533. }
  534. defer os.RemoveAll(folder)
  535. dest := filepath.Join(folder, "dest")
  536. src := filepath.Join(folder, "srcfolder")
  537. err = os.MkdirAll(src, 0740)
  538. if err != nil {
  539. t.Fatal(err)
  540. }
  541. err = os.MkdirAll(dest, 0740)
  542. if err != nil {
  543. t.Fatal(err)
  544. }
  545. err = CopyFileWithTar(src, dest)
  546. if err == nil {
  547. t.Fatalf("CopyFileWithTar should throw an error with a folder.")
  548. }
  549. }
  550. func TestCopyFileWithTarSrcFile(t *testing.T) {
  551. folder, err := ioutil.TempDir("", "docker-archive-test")
  552. if err != nil {
  553. t.Fatal(err)
  554. }
  555. defer os.RemoveAll(folder)
  556. dest := filepath.Join(folder, "dest")
  557. srcFolder := filepath.Join(folder, "src")
  558. src := filepath.Join(folder, filepath.Join("src", "src"))
  559. err = os.MkdirAll(srcFolder, 0740)
  560. if err != nil {
  561. t.Fatal(err)
  562. }
  563. err = os.MkdirAll(dest, 0740)
  564. if err != nil {
  565. t.Fatal(err)
  566. }
  567. ioutil.WriteFile(src, []byte("content"), 0777)
  568. err = CopyWithTar(src, dest+"/")
  569. if err != nil {
  570. t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
  571. }
  572. _, err = os.Stat(dest)
  573. if err != nil {
  574. t.Fatalf("Destination folder should contain the source file but did not.")
  575. }
  576. }
  577. func TestTarFiles(t *testing.T) {
  578. // TODO Windows: Figure out how to port this test.
  579. if runtime.GOOS == "windows" {
  580. t.Skip("Failing on Windows")
  581. }
  582. // try without hardlinks
  583. if err := checkNoChanges(1000, false); err != nil {
  584. t.Fatal(err)
  585. }
  586. // try with hardlinks
  587. if err := checkNoChanges(1000, true); err != nil {
  588. t.Fatal(err)
  589. }
  590. }
  591. func checkNoChanges(fileNum int, hardlinks bool) error {
  592. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  593. if err != nil {
  594. return err
  595. }
  596. defer os.RemoveAll(srcDir)
  597. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  598. if err != nil {
  599. return err
  600. }
  601. defer os.RemoveAll(destDir)
  602. _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
  603. if err != nil {
  604. return err
  605. }
  606. err = TarUntar(srcDir, destDir)
  607. if err != nil {
  608. return err
  609. }
  610. changes, err := ChangesDirs(destDir, srcDir)
  611. if err != nil {
  612. return err
  613. }
  614. if len(changes) > 0 {
  615. return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
  616. }
  617. return nil
  618. }
  619. func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
  620. archive, err := TarWithOptions(origin, options)
  621. if err != nil {
  622. t.Fatal(err)
  623. }
  624. defer archive.Close()
  625. buf := make([]byte, 10)
  626. if _, err := archive.Read(buf); err != nil {
  627. return nil, err
  628. }
  629. wrap := io.MultiReader(bytes.NewReader(buf), archive)
  630. detectedCompression := DetectCompression(buf)
  631. compression := options.Compression
  632. if detectedCompression.Extension() != compression.Extension() {
  633. return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
  634. }
  635. tmp, err := ioutil.TempDir("", "docker-test-untar")
  636. if err != nil {
  637. return nil, err
  638. }
  639. defer os.RemoveAll(tmp)
  640. if err := Untar(wrap, tmp, nil); err != nil {
  641. return nil, err
  642. }
  643. if _, err := os.Stat(tmp); err != nil {
  644. return nil, err
  645. }
  646. return ChangesDirs(origin, tmp)
  647. }
  648. func TestTarUntar(t *testing.T) {
  649. // TODO Windows: Figure out how to fix this test.
  650. if runtime.GOOS == "windows" {
  651. t.Skip("Failing on Windows")
  652. }
  653. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  654. if err != nil {
  655. t.Fatal(err)
  656. }
  657. defer os.RemoveAll(origin)
  658. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  659. t.Fatal(err)
  660. }
  661. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  662. t.Fatal(err)
  663. }
  664. if err := ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
  665. t.Fatal(err)
  666. }
  667. for _, c := range []Compression{
  668. Uncompressed,
  669. Gzip,
  670. } {
  671. changes, err := tarUntar(t, origin, &TarOptions{
  672. Compression: c,
  673. ExcludePatterns: []string{"3"},
  674. })
  675. if err != nil {
  676. t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
  677. }
  678. if len(changes) != 1 || changes[0].Path != "/3" {
  679. t.Fatalf("Unexpected differences after tarUntar: %v", changes)
  680. }
  681. }
  682. }
  683. func TestTarWithOptions(t *testing.T) {
  684. // TODO Windows: Figure out how to fix this test.
  685. if runtime.GOOS == "windows" {
  686. t.Skip("Failing on Windows")
  687. }
  688. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  689. if err != nil {
  690. t.Fatal(err)
  691. }
  692. if _, err := ioutil.TempDir(origin, "folder"); err != nil {
  693. t.Fatal(err)
  694. }
  695. defer os.RemoveAll(origin)
  696. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  697. t.Fatal(err)
  698. }
  699. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  700. t.Fatal(err)
  701. }
  702. cases := []struct {
  703. opts *TarOptions
  704. numChanges int
  705. }{
  706. {&TarOptions{IncludeFiles: []string{"1"}}, 2},
  707. {&TarOptions{ExcludePatterns: []string{"2"}}, 1},
  708. {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
  709. {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
  710. {&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
  711. }
  712. for _, testCase := range cases {
  713. changes, err := tarUntar(t, origin, testCase.opts)
  714. if err != nil {
  715. t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
  716. }
  717. if len(changes) != testCase.numChanges {
  718. t.Errorf("Expected %d changes, got %d for %+v:",
  719. testCase.numChanges, len(changes), testCase.opts)
  720. }
  721. }
  722. }
  723. // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
  724. // use PAX Global Extended Headers.
  725. // Failing prevents the archives from being uncompressed during ADD
  726. func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
  727. hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
  728. tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
  729. if err != nil {
  730. t.Fatal(err)
  731. }
  732. defer os.RemoveAll(tmpDir)
  733. err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil, false)
  734. if err != nil {
  735. t.Fatal(err)
  736. }
  737. }
  738. // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
  739. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
  740. func TestUntarUstarGnuConflict(t *testing.T) {
  741. f, err := os.Open("testdata/broken.tar")
  742. if err != nil {
  743. t.Fatal(err)
  744. }
  745. defer f.Close()
  746. found := false
  747. tr := tar.NewReader(f)
  748. // Iterate through the files in the archive.
  749. for {
  750. hdr, err := tr.Next()
  751. if err == io.EOF {
  752. // end of tar archive
  753. break
  754. }
  755. if err != nil {
  756. t.Fatal(err)
  757. }
  758. if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
  759. found = true
  760. break
  761. }
  762. }
  763. if !found {
  764. t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
  765. }
  766. }
  767. func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
  768. fileData := []byte("fooo")
  769. for n := 0; n < numberOfFiles; n++ {
  770. fileName := fmt.Sprintf("file-%d", n)
  771. if err := ioutil.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil {
  772. return 0, err
  773. }
  774. if makeLinks {
  775. if err := os.Link(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil {
  776. return 0, err
  777. }
  778. }
  779. }
  780. totalSize := numberOfFiles * len(fileData)
  781. return totalSize, nil
  782. }
  783. func BenchmarkTarUntar(b *testing.B) {
  784. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  785. if err != nil {
  786. b.Fatal(err)
  787. }
  788. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  789. if err != nil {
  790. b.Fatal(err)
  791. }
  792. target := filepath.Join(tempDir, "dest")
  793. n, err := prepareUntarSourceDirectory(100, origin, false)
  794. if err != nil {
  795. b.Fatal(err)
  796. }
  797. defer os.RemoveAll(origin)
  798. defer os.RemoveAll(tempDir)
  799. b.ResetTimer()
  800. b.SetBytes(int64(n))
  801. for n := 0; n < b.N; n++ {
  802. err := TarUntar(origin, target)
  803. if err != nil {
  804. b.Fatal(err)
  805. }
  806. os.RemoveAll(target)
  807. }
  808. }
  809. func BenchmarkTarUntarWithLinks(b *testing.B) {
  810. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  811. if err != nil {
  812. b.Fatal(err)
  813. }
  814. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  815. if err != nil {
  816. b.Fatal(err)
  817. }
  818. target := filepath.Join(tempDir, "dest")
  819. n, err := prepareUntarSourceDirectory(100, origin, true)
  820. if err != nil {
  821. b.Fatal(err)
  822. }
  823. defer os.RemoveAll(origin)
  824. defer os.RemoveAll(tempDir)
  825. b.ResetTimer()
  826. b.SetBytes(int64(n))
  827. for n := 0; n < b.N; n++ {
  828. err := TarUntar(origin, target)
  829. if err != nil {
  830. b.Fatal(err)
  831. }
  832. os.RemoveAll(target)
  833. }
  834. }
  835. func TestUntarInvalidFilenames(t *testing.T) {
  836. // TODO Windows: Figure out how to fix this test.
  837. if runtime.GOOS == "windows" {
  838. t.Skip("Passes but hits breakoutError: platform and architecture is not supported")
  839. }
  840. for i, headers := range [][]*tar.Header{
  841. {
  842. {
  843. Name: "../victim/dotdot",
  844. Typeflag: tar.TypeReg,
  845. Mode: 0644,
  846. },
  847. },
  848. {
  849. {
  850. // Note the leading slash
  851. Name: "/../victim/slash-dotdot",
  852. Typeflag: tar.TypeReg,
  853. Mode: 0644,
  854. },
  855. },
  856. } {
  857. if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
  858. t.Fatalf("i=%d. %v", i, err)
  859. }
  860. }
  861. }
  862. func TestUntarHardlinkToSymlink(t *testing.T) {
  863. // TODO Windows. There may be a way of running this, but turning off for now
  864. if runtime.GOOS == "windows" {
  865. t.Skip("hardlinks on Windows")
  866. }
  867. for i, headers := range [][]*tar.Header{
  868. {
  869. {
  870. Name: "symlink1",
  871. Typeflag: tar.TypeSymlink,
  872. Linkname: "regfile",
  873. Mode: 0644,
  874. },
  875. {
  876. Name: "symlink2",
  877. Typeflag: tar.TypeLink,
  878. Linkname: "symlink1",
  879. Mode: 0644,
  880. },
  881. {
  882. Name: "regfile",
  883. Typeflag: tar.TypeReg,
  884. Mode: 0644,
  885. },
  886. },
  887. } {
  888. if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil {
  889. t.Fatalf("i=%d. %v", i, err)
  890. }
  891. }
  892. }
  893. func TestUntarInvalidHardlink(t *testing.T) {
  894. // TODO Windows. There may be a way of running this, but turning off for now
  895. if runtime.GOOS == "windows" {
  896. t.Skip("hardlinks on Windows")
  897. }
  898. for i, headers := range [][]*tar.Header{
  899. { // try reading victim/hello (../)
  900. {
  901. Name: "dotdot",
  902. Typeflag: tar.TypeLink,
  903. Linkname: "../victim/hello",
  904. Mode: 0644,
  905. },
  906. },
  907. { // try reading victim/hello (/../)
  908. {
  909. Name: "slash-dotdot",
  910. Typeflag: tar.TypeLink,
  911. // Note the leading slash
  912. Linkname: "/../victim/hello",
  913. Mode: 0644,
  914. },
  915. },
  916. { // try writing victim/file
  917. {
  918. Name: "loophole-victim",
  919. Typeflag: tar.TypeLink,
  920. Linkname: "../victim",
  921. Mode: 0755,
  922. },
  923. {
  924. Name: "loophole-victim/file",
  925. Typeflag: tar.TypeReg,
  926. Mode: 0644,
  927. },
  928. },
  929. { // try reading victim/hello (hardlink, symlink)
  930. {
  931. Name: "loophole-victim",
  932. Typeflag: tar.TypeLink,
  933. Linkname: "../victim",
  934. Mode: 0755,
  935. },
  936. {
  937. Name: "symlink",
  938. Typeflag: tar.TypeSymlink,
  939. Linkname: "loophole-victim/hello",
  940. Mode: 0644,
  941. },
  942. },
  943. { // Try reading victim/hello (hardlink, hardlink)
  944. {
  945. Name: "loophole-victim",
  946. Typeflag: tar.TypeLink,
  947. Linkname: "../victim",
  948. Mode: 0755,
  949. },
  950. {
  951. Name: "hardlink",
  952. Typeflag: tar.TypeLink,
  953. Linkname: "loophole-victim/hello",
  954. Mode: 0644,
  955. },
  956. },
  957. { // Try removing victim directory (hardlink)
  958. {
  959. Name: "loophole-victim",
  960. Typeflag: tar.TypeLink,
  961. Linkname: "../victim",
  962. Mode: 0755,
  963. },
  964. {
  965. Name: "loophole-victim",
  966. Typeflag: tar.TypeReg,
  967. Mode: 0644,
  968. },
  969. },
  970. } {
  971. if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
  972. t.Fatalf("i=%d. %v", i, err)
  973. }
  974. }
  975. }
  976. func TestUntarInvalidSymlink(t *testing.T) {
  977. // TODO Windows. There may be a way of running this, but turning off for now
  978. if runtime.GOOS == "windows" {
  979. t.Skip("hardlinks on Windows")
  980. }
  981. for i, headers := range [][]*tar.Header{
  982. { // try reading victim/hello (../)
  983. {
  984. Name: "dotdot",
  985. Typeflag: tar.TypeSymlink,
  986. Linkname: "../victim/hello",
  987. Mode: 0644,
  988. },
  989. },
  990. { // try reading victim/hello (/../)
  991. {
  992. Name: "slash-dotdot",
  993. Typeflag: tar.TypeSymlink,
  994. // Note the leading slash
  995. Linkname: "/../victim/hello",
  996. Mode: 0644,
  997. },
  998. },
  999. { // try writing victim/file
  1000. {
  1001. Name: "loophole-victim",
  1002. Typeflag: tar.TypeSymlink,
  1003. Linkname: "../victim",
  1004. Mode: 0755,
  1005. },
  1006. {
  1007. Name: "loophole-victim/file",
  1008. Typeflag: tar.TypeReg,
  1009. Mode: 0644,
  1010. },
  1011. },
  1012. { // try reading victim/hello (symlink, symlink)
  1013. {
  1014. Name: "loophole-victim",
  1015. Typeflag: tar.TypeSymlink,
  1016. Linkname: "../victim",
  1017. Mode: 0755,
  1018. },
  1019. {
  1020. Name: "symlink",
  1021. Typeflag: tar.TypeSymlink,
  1022. Linkname: "loophole-victim/hello",
  1023. Mode: 0644,
  1024. },
  1025. },
  1026. { // try reading victim/hello (symlink, hardlink)
  1027. {
  1028. Name: "loophole-victim",
  1029. Typeflag: tar.TypeSymlink,
  1030. Linkname: "../victim",
  1031. Mode: 0755,
  1032. },
  1033. {
  1034. Name: "hardlink",
  1035. Typeflag: tar.TypeLink,
  1036. Linkname: "loophole-victim/hello",
  1037. Mode: 0644,
  1038. },
  1039. },
  1040. { // try removing victim directory (symlink)
  1041. {
  1042. Name: "loophole-victim",
  1043. Typeflag: tar.TypeSymlink,
  1044. Linkname: "../victim",
  1045. Mode: 0755,
  1046. },
  1047. {
  1048. Name: "loophole-victim",
  1049. Typeflag: tar.TypeReg,
  1050. Mode: 0644,
  1051. },
  1052. },
  1053. { // try writing to victim/newdir/newfile with a symlink in the path
  1054. {
  1055. // this header needs to be before the next one, or else there is an error
  1056. Name: "dir/loophole",
  1057. Typeflag: tar.TypeSymlink,
  1058. Linkname: "../../victim",
  1059. Mode: 0755,
  1060. },
  1061. {
  1062. Name: "dir/loophole/newdir/newfile",
  1063. Typeflag: tar.TypeReg,
  1064. Mode: 0644,
  1065. },
  1066. },
  1067. } {
  1068. if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
  1069. t.Fatalf("i=%d. %v", i, err)
  1070. }
  1071. }
  1072. }
  1073. func TestTempArchiveCloseMultipleTimes(t *testing.T) {
  1074. reader := ioutil.NopCloser(strings.NewReader("hello"))
  1075. tempArchive, err := NewTempArchive(reader, "")
  1076. buf := make([]byte, 10)
  1077. n, err := tempArchive.Read(buf)
  1078. if n != 5 {
  1079. t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
  1080. }
  1081. for i := 0; i < 3; i++ {
  1082. if err = tempArchive.Close(); err != nil {
  1083. t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
  1084. }
  1085. }
  1086. }
  1087. func TestReplaceFileTarWrapper(t *testing.T) {
  1088. filesInArchive := 20
  1089. testcases := []struct {
  1090. doc string
  1091. filename string
  1092. modifier TarModifierFunc
  1093. expected string
  1094. fileCount int
  1095. }{
  1096. {
  1097. doc: "Modifier creates a new file",
  1098. filename: "newfile",
  1099. modifier: createModifier(t),
  1100. expected: "the new content",
  1101. fileCount: filesInArchive + 1,
  1102. },
  1103. {
  1104. doc: "Modifier replaces a file",
  1105. filename: "file-2",
  1106. modifier: createOrReplaceModifier,
  1107. expected: "the new content",
  1108. fileCount: filesInArchive,
  1109. },
  1110. {
  1111. doc: "Modifier replaces the last file",
  1112. filename: fmt.Sprintf("file-%d", filesInArchive-1),
  1113. modifier: createOrReplaceModifier,
  1114. expected: "the new content",
  1115. fileCount: filesInArchive,
  1116. },
  1117. {
  1118. doc: "Modifier appends to a file",
  1119. filename: "file-3",
  1120. modifier: appendModifier,
  1121. expected: "fooo\nnext line",
  1122. fileCount: filesInArchive,
  1123. },
  1124. }
  1125. for _, testcase := range testcases {
  1126. sourceArchive, cleanup := buildSourceArchive(t, filesInArchive)
  1127. defer cleanup()
  1128. resultArchive := ReplaceFileTarWrapper(
  1129. sourceArchive,
  1130. map[string]TarModifierFunc{testcase.filename: testcase.modifier})
  1131. actual := readFileFromArchive(t, resultArchive, testcase.filename, testcase.fileCount, testcase.doc)
  1132. assert.Equal(t, testcase.expected, actual, testcase.doc)
  1133. }
  1134. }
  1135. func buildSourceArchive(t *testing.T, numberOfFiles int) (io.ReadCloser, func()) {
  1136. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  1137. require.NoError(t, err)
  1138. _, err = prepareUntarSourceDirectory(numberOfFiles, srcDir, false)
  1139. require.NoError(t, err)
  1140. sourceArchive, err := TarWithOptions(srcDir, &TarOptions{})
  1141. require.NoError(t, err)
  1142. return sourceArchive, func() {
  1143. os.RemoveAll(srcDir)
  1144. sourceArchive.Close()
  1145. }
  1146. }
  1147. func createOrReplaceModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1148. return &tar.Header{
  1149. Mode: 0600,
  1150. Typeflag: tar.TypeReg,
  1151. }, []byte("the new content"), nil
  1152. }
  1153. func createModifier(t *testing.T) TarModifierFunc {
  1154. return func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1155. assert.Nil(t, content)
  1156. return createOrReplaceModifier(path, header, content)
  1157. }
  1158. }
  1159. func appendModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1160. buffer := bytes.Buffer{}
  1161. if content != nil {
  1162. if _, err := buffer.ReadFrom(content); err != nil {
  1163. return nil, nil, err
  1164. }
  1165. }
  1166. buffer.WriteString("\nnext line")
  1167. return &tar.Header{Mode: 0600, Typeflag: tar.TypeReg}, buffer.Bytes(), nil
  1168. }
  1169. func readFileFromArchive(t *testing.T, archive io.ReadCloser, name string, expectedCount int, doc string) string {
  1170. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  1171. require.NoError(t, err)
  1172. defer os.RemoveAll(destDir)
  1173. err = Untar(archive, destDir, nil)
  1174. require.NoError(t, err)
  1175. files, _ := ioutil.ReadDir(destDir)
  1176. assert.Len(t, files, expectedCount, doc)
  1177. content, err := ioutil.ReadFile(filepath.Join(destDir, name))
  1178. assert.NoError(t, err)
  1179. return string(content)
  1180. }