fileutils_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. package fileutils // import "github.com/docker/docker/pkg/fileutils"
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "testing"
  10. "gotest.tools/v3/assert"
  11. is "gotest.tools/v3/assert/cmp"
  12. )
  13. // CopyFile with invalid src
  14. func TestCopyFileWithInvalidSrc(t *testing.T) {
  15. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test") // #nosec G303
  16. defer os.RemoveAll(tempFolder)
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest"))
  21. if err == nil {
  22. t.Fatal("Should have fail to copy an invalid src file")
  23. }
  24. if bytes != 0 {
  25. t.Fatal("Should have written 0 bytes")
  26. }
  27. }
  28. // CopyFile with invalid dest
  29. func TestCopyFileWithInvalidDest(t *testing.T) {
  30. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test")
  31. defer os.RemoveAll(tempFolder)
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. src := path.Join(tempFolder, "file")
  36. err = os.WriteFile(src, []byte("content"), 0740)
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path"))
  41. if err == nil {
  42. t.Fatal("Should have fail to copy an invalid src file")
  43. }
  44. if bytes != 0 {
  45. t.Fatal("Should have written 0 bytes")
  46. }
  47. }
  48. // CopyFile with same src and dest
  49. func TestCopyFileWithSameSrcAndDest(t *testing.T) {
  50. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test")
  51. defer os.RemoveAll(tempFolder)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. file := path.Join(tempFolder, "file")
  56. err = os.WriteFile(file, []byte("content"), 0740)
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. bytes, err := CopyFile(file, file)
  61. if err != nil {
  62. t.Fatal(err)
  63. }
  64. if bytes != 0 {
  65. t.Fatal("Should have written 0 bytes as it is the same file.")
  66. }
  67. }
  68. // CopyFile with same src and dest but path is different and not clean
  69. func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) {
  70. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test")
  71. defer os.RemoveAll(tempFolder)
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. testFolder := path.Join(tempFolder, "test")
  76. err = os.MkdirAll(testFolder, 0740)
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. file := path.Join(testFolder, "file")
  81. sameFile := testFolder + "/../test/file"
  82. err = os.WriteFile(file, []byte("content"), 0740)
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. bytes, err := CopyFile(file, sameFile)
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. if bytes != 0 {
  91. t.Fatal("Should have written 0 bytes as it is the same file.")
  92. }
  93. }
  94. func TestCopyFile(t *testing.T) {
  95. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test")
  96. defer os.RemoveAll(tempFolder)
  97. if err != nil {
  98. t.Fatal(err)
  99. }
  100. src := path.Join(tempFolder, "src")
  101. dest := path.Join(tempFolder, "dest")
  102. os.WriteFile(src, []byte("content"), 0777)
  103. os.WriteFile(dest, []byte("destContent"), 0777)
  104. bytes, err := CopyFile(src, dest)
  105. if err != nil {
  106. t.Fatal(err)
  107. }
  108. if bytes != 7 {
  109. t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes)
  110. }
  111. actual, err := os.ReadFile(dest)
  112. if err != nil {
  113. t.Fatal(err)
  114. }
  115. if string(actual) != "content" {
  116. t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content")
  117. }
  118. }
  119. // Reading a symlink to a directory must return the directory
  120. func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {
  121. // TODO Windows: Port this test
  122. if runtime.GOOS == "windows" {
  123. t.Skip("Needs porting to Windows")
  124. }
  125. var err error
  126. if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil {
  127. t.Errorf("failed to create directory: %s", err)
  128. }
  129. if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil {
  130. t.Errorf("failed to create symlink: %s", err)
  131. }
  132. var path string
  133. if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil {
  134. t.Fatalf("failed to read symlink to directory: %s", err)
  135. }
  136. if path != "/tmp/testReadSymlinkToExistingDirectory" {
  137. t.Fatalf("symlink returned unexpected directory: %s", path)
  138. }
  139. if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil {
  140. t.Errorf("failed to remove temporary directory: %s", err)
  141. }
  142. if err = os.Remove("/tmp/dirLinkTest"); err != nil {
  143. t.Errorf("failed to remove symlink: %s", err)
  144. }
  145. }
  146. // Reading a non-existing symlink must fail
  147. func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {
  148. var path string
  149. var err error
  150. if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil {
  151. t.Fatalf("error expected for non-existing symlink")
  152. }
  153. if path != "" {
  154. t.Fatalf("expected empty path, but '%s' was returned", path)
  155. }
  156. }
  157. // Reading a symlink to a file must fail
  158. func TestReadSymlinkedDirectoryToFile(t *testing.T) {
  159. // TODO Windows: Port this test
  160. if runtime.GOOS == "windows" {
  161. t.Skip("Needs porting to Windows")
  162. }
  163. var err error
  164. var file *os.File
  165. // #nosec G303
  166. if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil {
  167. t.Fatalf("failed to create file: %s", err)
  168. }
  169. file.Close()
  170. if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil {
  171. t.Errorf("failed to create symlink: %s", err)
  172. }
  173. var path string
  174. if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil {
  175. t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed")
  176. }
  177. if path != "" {
  178. t.Fatalf("path should've been empty: %s", path)
  179. }
  180. if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil {
  181. t.Errorf("failed to remove file: %s", err)
  182. }
  183. if err = os.Remove("/tmp/fileLinkTest"); err != nil {
  184. t.Errorf("failed to remove symlink: %s", err)
  185. }
  186. }
  187. func TestWildcardMatches(t *testing.T) {
  188. match, _ := Matches("fileutils.go", []string{"*"})
  189. if !match {
  190. t.Errorf("failed to get a wildcard match, got %v", match)
  191. }
  192. }
  193. // A simple pattern match should return true.
  194. func TestPatternMatches(t *testing.T) {
  195. match, _ := Matches("fileutils.go", []string{"*.go"})
  196. if !match {
  197. t.Errorf("failed to get a match, got %v", match)
  198. }
  199. }
  200. // An exclusion followed by an inclusion should return true.
  201. func TestExclusionPatternMatchesPatternBefore(t *testing.T) {
  202. match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"})
  203. if !match {
  204. t.Errorf("failed to get true match on exclusion pattern, got %v", match)
  205. }
  206. }
  207. // A folder pattern followed by an exception should return false.
  208. func TestPatternMatchesFolderExclusions(t *testing.T) {
  209. match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"})
  210. if match {
  211. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  212. }
  213. }
  214. // A folder pattern followed by an exception should return false.
  215. func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) {
  216. match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"})
  217. if match {
  218. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  219. }
  220. }
  221. // A folder pattern followed by an exception should return false.
  222. func TestPatternMatchesFolderWildcardExclusions(t *testing.T) {
  223. match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"})
  224. if match {
  225. t.Errorf("failed to get a false match on exclusion pattern, got %v", match)
  226. }
  227. }
  228. // A pattern followed by an exclusion should return false.
  229. func TestExclusionPatternMatchesPatternAfter(t *testing.T) {
  230. match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"})
  231. if match {
  232. t.Errorf("failed to get false match on exclusion pattern, got %v", match)
  233. }
  234. }
  235. // A filename evaluating to . should return false.
  236. func TestExclusionPatternMatchesWholeDirectory(t *testing.T) {
  237. match, _ := Matches(".", []string{"*.go"})
  238. if match {
  239. t.Errorf("failed to get false match on ., got %v", match)
  240. }
  241. }
  242. // A single ! pattern should return an error.
  243. func TestSingleExclamationError(t *testing.T) {
  244. _, err := Matches("fileutils.go", []string{"!"})
  245. if err == nil {
  246. t.Errorf("failed to get an error for a single exclamation point, got %v", err)
  247. }
  248. }
  249. // Matches with no patterns
  250. func TestMatchesWithNoPatterns(t *testing.T) {
  251. matches, err := Matches("/any/path/there", []string{})
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. if matches {
  256. t.Fatalf("Should not have match anything")
  257. }
  258. }
  259. // Matches with malformed patterns
  260. func TestMatchesWithMalformedPatterns(t *testing.T) {
  261. matches, err := Matches("/any/path/there", []string{"["})
  262. if err == nil {
  263. t.Fatal("Should have failed because of a malformed syntax in the pattern")
  264. }
  265. if matches {
  266. t.Fatalf("Should not have match anything")
  267. }
  268. }
  269. type matchesTestCase struct {
  270. pattern string
  271. text string
  272. pass bool
  273. }
  274. type multiPatternTestCase struct {
  275. patterns []string
  276. text string
  277. pass bool
  278. }
  279. func TestMatches(t *testing.T) {
  280. tests := []matchesTestCase{
  281. {"**", "file", true},
  282. {"**", "file/", true},
  283. {"**/", "file", true}, // weird one
  284. {"**/", "file/", true},
  285. {"**", "/", true},
  286. {"**/", "/", true},
  287. {"**", "dir/file", true},
  288. {"**/", "dir/file", true},
  289. {"**", "dir/file/", true},
  290. {"**/", "dir/file/", true},
  291. {"**/**", "dir/file", true},
  292. {"**/**", "dir/file/", true},
  293. {"dir/**", "dir/file", true},
  294. {"dir/**", "dir/file/", true},
  295. {"dir/**", "dir/dir2/file", true},
  296. {"dir/**", "dir/dir2/file/", true},
  297. {"**/dir", "dir", true},
  298. {"**/dir", "dir/file", true},
  299. {"**/dir2/*", "dir/dir2/file", true},
  300. {"**/dir2/*", "dir/dir2/file/", true},
  301. {"**/dir2/**", "dir/dir2/dir3/file", true},
  302. {"**/dir2/**", "dir/dir2/dir3/file/", true},
  303. {"**file", "file", true},
  304. {"**file", "dir/file", true},
  305. {"**/file", "dir/file", true},
  306. {"**file", "dir/dir/file", true},
  307. {"**/file", "dir/dir/file", true},
  308. {"**/file*", "dir/dir/file", true},
  309. {"**/file*", "dir/dir/file.txt", true},
  310. {"**/file*txt", "dir/dir/file.txt", true},
  311. {"**/file*.txt", "dir/dir/file.txt", true},
  312. {"**/file*.txt*", "dir/dir/file.txt", true},
  313. {"**/**/*.txt", "dir/dir/file.txt", true},
  314. {"**/**/*.txt2", "dir/dir/file.txt", false},
  315. {"**/*.txt", "file.txt", true},
  316. {"**/**/*.txt", "file.txt", true},
  317. {"a**/*.txt", "a/file.txt", true},
  318. {"a**/*.txt", "a/dir/file.txt", true},
  319. {"a**/*.txt", "a/dir/dir/file.txt", true},
  320. {"a/*.txt", "a/dir/file.txt", false},
  321. {"a/*.txt", "a/file.txt", true},
  322. {"a/*.txt**", "a/file.txt", true},
  323. {"a[b-d]e", "ae", false},
  324. {"a[b-d]e", "ace", true},
  325. {"a[b-d]e", "aae", false},
  326. {"a[^b-d]e", "aze", true},
  327. {".*", ".foo", true},
  328. {".*", "foo", false},
  329. {"abc.def", "abcdef", false},
  330. {"abc.def", "abc.def", true},
  331. {"abc.def", "abcZdef", false},
  332. {"abc?def", "abcZdef", true},
  333. {"abc?def", "abcdef", false},
  334. {"a\\\\", "a\\", true},
  335. {"**/foo/bar", "foo/bar", true},
  336. {"**/foo/bar", "dir/foo/bar", true},
  337. {"**/foo/bar", "dir/dir2/foo/bar", true},
  338. {"abc/**", "abc", false},
  339. {"abc/**", "abc/def", true},
  340. {"abc/**", "abc/def/ghi", true},
  341. {"**/.foo", ".foo", true},
  342. {"**/.foo", "bar.foo", false},
  343. {"a(b)c/def", "a(b)c/def", true},
  344. {"a(b)c/def", "a(b)c/xyz", false},
  345. {"a.|)$(}+{bc", "a.|)$(}+{bc", true},
  346. {"dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl", "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl", true},
  347. {"dist/*.whl", "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl", true},
  348. }
  349. multiPatternTests := []multiPatternTestCase{
  350. {[]string{"**", "!util/docker/web"}, "util/docker/web/foo", false},
  351. {[]string{"**", "!util/docker/web", "util/docker/web/foo"}, "util/docker/web/foo", true},
  352. {[]string{"**", "!dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl"}, "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl", false},
  353. {[]string{"**", "!dist/*.whl"}, "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl", false},
  354. }
  355. if runtime.GOOS != "windows" {
  356. tests = append(tests, []matchesTestCase{
  357. {"a\\*b", "a*b", true},
  358. }...)
  359. }
  360. t.Run("MatchesOrParentMatches", func(t *testing.T) {
  361. for _, test := range tests {
  362. desc := fmt.Sprintf("pattern=%q text=%q", test.pattern, test.text)
  363. pm, err := NewPatternMatcher([]string{test.pattern})
  364. assert.NilError(t, err, desc)
  365. res, _ := pm.MatchesOrParentMatches(test.text)
  366. assert.Check(t, is.Equal(test.pass, res), desc)
  367. }
  368. for _, test := range multiPatternTests {
  369. desc := fmt.Sprintf("patterns=%q text=%q", test.patterns, test.text)
  370. pm, err := NewPatternMatcher(test.patterns)
  371. assert.NilError(t, err, desc)
  372. res, _ := pm.MatchesOrParentMatches(test.text)
  373. assert.Check(t, is.Equal(test.pass, res), desc)
  374. }
  375. })
  376. t.Run("MatchesUsingParentResult", func(t *testing.T) {
  377. for _, test := range tests {
  378. desc := fmt.Sprintf("pattern=%q text=%q", test.pattern, test.text)
  379. pm, err := NewPatternMatcher([]string{test.pattern})
  380. assert.NilError(t, err, desc)
  381. parentPath := filepath.Dir(filepath.FromSlash(test.text))
  382. parentPathDirs := strings.Split(parentPath, string(os.PathSeparator))
  383. parentMatched := false
  384. if parentPath != "." {
  385. for i := range parentPathDirs {
  386. parentMatched, _ = pm.MatchesUsingParentResult(strings.Join(parentPathDirs[:i+1], "/"), parentMatched)
  387. }
  388. }
  389. res, _ := pm.MatchesUsingParentResult(test.text, parentMatched)
  390. assert.Check(t, is.Equal(test.pass, res), desc)
  391. }
  392. })
  393. t.Run("MatchesUsingParentResults", func(t *testing.T) {
  394. check := func(pm *PatternMatcher, text string, pass bool, desc string) {
  395. parentPath := filepath.Dir(filepath.FromSlash(text))
  396. parentPathDirs := strings.Split(parentPath, string(os.PathSeparator))
  397. parentMatchInfo := MatchInfo{}
  398. if parentPath != "." {
  399. for i := range parentPathDirs {
  400. _, parentMatchInfo, _ = pm.MatchesUsingParentResults(strings.Join(parentPathDirs[:i+1], "/"), parentMatchInfo)
  401. }
  402. }
  403. res, _, _ := pm.MatchesUsingParentResults(text, parentMatchInfo)
  404. assert.Check(t, is.Equal(pass, res), desc)
  405. }
  406. for _, test := range tests {
  407. desc := fmt.Sprintf("pattern=%q text=%q", test.pattern, test.text)
  408. pm, err := NewPatternMatcher([]string{test.pattern})
  409. assert.NilError(t, err, desc)
  410. check(pm, test.text, test.pass, desc)
  411. }
  412. for _, test := range multiPatternTests {
  413. desc := fmt.Sprintf("pattern=%q text=%q", test.patterns, test.text)
  414. pm, err := NewPatternMatcher(test.patterns)
  415. assert.NilError(t, err, desc)
  416. check(pm, test.text, test.pass, desc)
  417. }
  418. })
  419. t.Run("MatchesUsingParentResultsNoContext", func(t *testing.T) {
  420. check := func(pm *PatternMatcher, text string, pass bool, desc string) {
  421. res, _, _ := pm.MatchesUsingParentResults(text, MatchInfo{})
  422. assert.Check(t, is.Equal(pass, res), desc)
  423. }
  424. for _, test := range tests {
  425. desc := fmt.Sprintf("pattern=%q text=%q", test.pattern, test.text)
  426. pm, err := NewPatternMatcher([]string{test.pattern})
  427. assert.NilError(t, err, desc)
  428. check(pm, test.text, test.pass, desc)
  429. }
  430. for _, test := range multiPatternTests {
  431. desc := fmt.Sprintf("pattern=%q text=%q", test.patterns, test.text)
  432. pm, err := NewPatternMatcher(test.patterns)
  433. assert.NilError(t, err, desc)
  434. check(pm, test.text, test.pass, desc)
  435. }
  436. })
  437. }
  438. func TestCleanPatterns(t *testing.T) {
  439. patterns := []string{"docs", "config"}
  440. pm, err := NewPatternMatcher(patterns)
  441. if err != nil {
  442. t.Fatalf("invalid pattern %v", patterns)
  443. }
  444. cleaned := pm.Patterns()
  445. if len(cleaned) != 2 {
  446. t.Errorf("expected 2 element slice, got %v", len(cleaned))
  447. }
  448. }
  449. func TestCleanPatternsStripEmptyPatterns(t *testing.T) {
  450. patterns := []string{"docs", "config", ""}
  451. pm, err := NewPatternMatcher(patterns)
  452. if err != nil {
  453. t.Fatalf("invalid pattern %v", patterns)
  454. }
  455. cleaned := pm.Patterns()
  456. if len(cleaned) != 2 {
  457. t.Errorf("expected 2 element slice, got %v", len(cleaned))
  458. }
  459. }
  460. func TestCleanPatternsExceptionFlag(t *testing.T) {
  461. patterns := []string{"docs", "!docs/README.md"}
  462. pm, err := NewPatternMatcher(patterns)
  463. if err != nil {
  464. t.Fatalf("invalid pattern %v", patterns)
  465. }
  466. if !pm.Exclusions() {
  467. t.Errorf("expected exceptions to be true, got %v", pm.Exclusions())
  468. }
  469. }
  470. func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) {
  471. patterns := []string{"docs", " !docs/README.md"}
  472. pm, err := NewPatternMatcher(patterns)
  473. if err != nil {
  474. t.Fatalf("invalid pattern %v", patterns)
  475. }
  476. if !pm.Exclusions() {
  477. t.Errorf("expected exceptions to be true, got %v", pm.Exclusions())
  478. }
  479. }
  480. func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) {
  481. patterns := []string{"docs", "!docs/README.md "}
  482. pm, err := NewPatternMatcher(patterns)
  483. if err != nil {
  484. t.Fatalf("invalid pattern %v", patterns)
  485. }
  486. if !pm.Exclusions() {
  487. t.Errorf("expected exceptions to be true, got %v", pm.Exclusions())
  488. }
  489. }
  490. func TestCleanPatternsErrorSingleException(t *testing.T) {
  491. patterns := []string{"!"}
  492. _, err := NewPatternMatcher(patterns)
  493. if err == nil {
  494. t.Errorf("expected error on single exclamation point, got %v", err)
  495. }
  496. }
  497. func TestCreateIfNotExistsDir(t *testing.T) {
  498. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test")
  499. if err != nil {
  500. t.Fatal(err)
  501. }
  502. defer os.RemoveAll(tempFolder)
  503. folderToCreate := filepath.Join(tempFolder, "tocreate")
  504. if err := CreateIfNotExists(folderToCreate, true); err != nil {
  505. t.Fatal(err)
  506. }
  507. fileinfo, err := os.Stat(folderToCreate)
  508. if err != nil {
  509. t.Fatalf("Should have create a folder, got %v", err)
  510. }
  511. if !fileinfo.IsDir() {
  512. t.Fatalf("Should have been a dir, seems it's not")
  513. }
  514. }
  515. func TestCreateIfNotExistsFile(t *testing.T) {
  516. tempFolder, err := os.MkdirTemp("", "docker-fileutils-test")
  517. if err != nil {
  518. t.Fatal(err)
  519. }
  520. defer os.RemoveAll(tempFolder)
  521. fileToCreate := filepath.Join(tempFolder, "file/to/create")
  522. if err := CreateIfNotExists(fileToCreate, false); err != nil {
  523. t.Fatal(err)
  524. }
  525. fileinfo, err := os.Stat(fileToCreate)
  526. if err != nil {
  527. t.Fatalf("Should have create a file, got %v", err)
  528. }
  529. if fileinfo.IsDir() {
  530. t.Fatalf("Should have been a file, seems it's not")
  531. }
  532. }
  533. // These matchTests are stolen from go's filepath Match tests.
  534. type matchTest struct {
  535. pattern, s string
  536. match bool
  537. err error
  538. }
  539. var matchTests = []matchTest{
  540. {"abc", "abc", true, nil},
  541. {"*", "abc", true, nil},
  542. {"*c", "abc", true, nil},
  543. {"a*", "a", true, nil},
  544. {"a*", "abc", true, nil},
  545. {"a*", "ab/c", true, nil},
  546. {"a*/b", "abc/b", true, nil},
  547. {"a*/b", "a/c/b", false, nil},
  548. {"a*b*c*d*e*/f", "axbxcxdxe/f", true, nil},
  549. {"a*b*c*d*e*/f", "axbxcxdxexxx/f", true, nil},
  550. {"a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, nil},
  551. {"a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, nil},
  552. {"a*b?c*x", "abxbbxdbxebxczzx", true, nil},
  553. {"a*b?c*x", "abxbbxdbxebxczzy", false, nil},
  554. {"ab[c]", "abc", true, nil},
  555. {"ab[b-d]", "abc", true, nil},
  556. {"ab[e-g]", "abc", false, nil},
  557. {"ab[^c]", "abc", false, nil},
  558. {"ab[^b-d]", "abc", false, nil},
  559. {"ab[^e-g]", "abc", true, nil},
  560. {"a\\*b", "a*b", true, nil},
  561. {"a\\*b", "ab", false, nil},
  562. {"a?b", "a☺b", true, nil},
  563. {"a[^a]b", "a☺b", true, nil},
  564. {"a???b", "a☺b", false, nil},
  565. {"a[^a][^a][^a]b", "a☺b", false, nil},
  566. {"[a-ζ]*", "α", true, nil},
  567. {"*[a-ζ]", "A", false, nil},
  568. {"a?b", "a/b", false, nil},
  569. {"a*b", "a/b", false, nil},
  570. {"[\\]a]", "]", true, nil},
  571. {"[\\-]", "-", true, nil},
  572. {"[x\\-]", "x", true, nil},
  573. {"[x\\-]", "-", true, nil},
  574. {"[x\\-]", "z", false, nil},
  575. {"[\\-x]", "x", true, nil},
  576. {"[\\-x]", "-", true, nil},
  577. {"[\\-x]", "a", false, nil},
  578. {"[]a]", "]", false, filepath.ErrBadPattern},
  579. {"[-]", "-", false, filepath.ErrBadPattern},
  580. {"[x-]", "x", false, filepath.ErrBadPattern},
  581. {"[x-]", "-", false, filepath.ErrBadPattern},
  582. {"[x-]", "z", false, filepath.ErrBadPattern},
  583. {"[-x]", "x", false, filepath.ErrBadPattern},
  584. {"[-x]", "-", false, filepath.ErrBadPattern},
  585. {"[-x]", "a", false, filepath.ErrBadPattern},
  586. {"\\", "a", false, filepath.ErrBadPattern},
  587. {"[a-b-c]", "a", false, filepath.ErrBadPattern},
  588. {"[", "a", false, filepath.ErrBadPattern},
  589. {"[^", "a", false, filepath.ErrBadPattern},
  590. {"[^bc", "a", false, filepath.ErrBadPattern},
  591. {"a[", "a", false, filepath.ErrBadPattern}, // was nil but IMO its wrong
  592. {"a[", "ab", false, filepath.ErrBadPattern},
  593. {"*x", "xxx", true, nil},
  594. }
  595. func errp(e error) string {
  596. if e == nil {
  597. return "<nil>"
  598. }
  599. return e.Error()
  600. }
  601. // TestMatch test's our version of filepath.Match, called regexpMatch.
  602. func TestMatch(t *testing.T) {
  603. for _, tt := range matchTests {
  604. pattern := tt.pattern
  605. s := tt.s
  606. if runtime.GOOS == "windows" {
  607. if strings.Contains(pattern, "\\") {
  608. // no escape allowed on windows.
  609. continue
  610. }
  611. pattern = filepath.Clean(pattern)
  612. s = filepath.Clean(s)
  613. }
  614. ok, err := Matches(s, []string{pattern})
  615. if ok != tt.match || err != tt.err {
  616. t.Fatalf("Match(%#q, %#q) = %v, %q want %v, %q", pattern, s, ok, errp(err), tt.match, errp(tt.err))
  617. }
  618. }
  619. }