ignore_test.go 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package ignore
  7. import (
  8. "bytes"
  9. "fmt"
  10. "io"
  11. "path/filepath"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/syncthing/syncthing/lib/build"
  16. "github.com/syncthing/syncthing/lib/fs"
  17. "github.com/syncthing/syncthing/lib/ignore/ignoreresult"
  18. "github.com/syncthing/syncthing/lib/osutil"
  19. "github.com/syncthing/syncthing/lib/rand"
  20. )
  21. var testFiles = map[string]string{
  22. ".stignore": `#include excludes
  23. bfile
  24. dir1/cfile
  25. **/efile
  26. /ffile
  27. lost+found
  28. `,
  29. "excludes": "dir2/dfile\n#include further-excludes\n",
  30. "further-excludes": "dir3\n",
  31. }
  32. func newTestFS() fs.Filesystem {
  33. testFS := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?content=true&nostfolder=true")
  34. // Add some data expected by the tests, previously existing on disk.
  35. testFS.Mkdir("dir3", 0o777)
  36. for name, content := range testFiles {
  37. fs.WriteFile(testFS, name, []byte(content), 0o666)
  38. }
  39. return testFS
  40. }
  41. func TestIgnore(t *testing.T) {
  42. testFs := newTestFS()
  43. pats := New(testFs, WithCache(true))
  44. err := pats.Load(".stignore")
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. tests := []struct {
  49. f string
  50. r bool
  51. }{
  52. {"afile", false},
  53. {"bfile", true},
  54. {"cfile", false},
  55. {"dfile", false},
  56. {"efile", true},
  57. {"ffile", true},
  58. {"dir1", false},
  59. {filepath.Join("dir1", "cfile"), true},
  60. {filepath.Join("dir1", "dfile"), false},
  61. {filepath.Join("dir1", "efile"), true},
  62. {filepath.Join("dir1", "ffile"), false},
  63. {"dir2", false},
  64. {filepath.Join("dir2", "cfile"), false},
  65. {filepath.Join("dir2", "dfile"), true},
  66. {filepath.Join("dir2", "efile"), true},
  67. {filepath.Join("dir2", "ffile"), false},
  68. {filepath.Join("dir3"), true},
  69. {filepath.Join("dir3", "afile"), true},
  70. {"lost+found", true},
  71. }
  72. for i, tc := range tests {
  73. if r := pats.Match(tc.f); r.IsIgnored() != tc.r {
  74. t.Errorf("Incorrect ignoreFile() #%d (%s); E: %v, A: %v", i, tc.f, tc.r, r)
  75. }
  76. }
  77. }
  78. func TestExcludes(t *testing.T) {
  79. testFs := newTestFS()
  80. stignore := `
  81. !iex2
  82. !ign1/ex
  83. ign1
  84. i*2
  85. !ign2
  86. `
  87. pats := New(testFs, WithCache(true))
  88. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  89. if err != nil {
  90. t.Fatal(err)
  91. }
  92. tests := []struct {
  93. f string
  94. r bool
  95. }{
  96. {"ign1", true},
  97. {"ign2", true},
  98. {"ibla2", true},
  99. {"iex2", false},
  100. {filepath.Join("ign1", "ign"), true},
  101. {filepath.Join("ign1", "ex"), false},
  102. {filepath.Join("ign1", "iex2"), false},
  103. {filepath.Join("iex2", "ign"), false},
  104. {filepath.Join("foo", "bar", "ign1"), true},
  105. {filepath.Join("foo", "bar", "ign2"), true},
  106. {filepath.Join("foo", "bar", "iex2"), false},
  107. }
  108. for _, tc := range tests {
  109. if r := pats.Match(tc.f); r.IsIgnored() != tc.r {
  110. t.Errorf("Incorrect match for %s: %v != %v", tc.f, r, tc.r)
  111. }
  112. }
  113. }
  114. func TestFlagOrder(t *testing.T) {
  115. testFs := newTestFS()
  116. stignore := `
  117. ## Ok cases
  118. (?i)(?d)!ign1
  119. (?d)(?i)!ign2
  120. (?i)!(?d)ign3
  121. (?d)!(?i)ign4
  122. !(?i)(?d)ign5
  123. !(?d)(?i)ign6
  124. ## Bad cases
  125. !!(?i)(?d)ign7
  126. (?i)(?i)(?d)ign8
  127. (?i)(?d)(?d)!ign9
  128. (?d)(?d)!ign10
  129. `
  130. pats := New(testFs, WithCache(true))
  131. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  132. if err != nil {
  133. t.Fatal(err)
  134. }
  135. for i := 1; i < 7; i++ {
  136. pat := fmt.Sprintf("ign%d", i)
  137. if r := pats.Match(pat); r.IsIgnored() || r.IsDeletable() {
  138. t.Errorf("incorrect %s", pat)
  139. }
  140. }
  141. for i := 7; i < 10; i++ {
  142. pat := fmt.Sprintf("ign%d", i)
  143. if r := pats.Match(pat); r.IsDeletable() {
  144. t.Errorf("incorrect %s", pat)
  145. }
  146. }
  147. if r := pats.Match("(?d)!ign10"); !r.IsIgnored() {
  148. t.Errorf("incorrect")
  149. }
  150. }
  151. func TestDeletables(t *testing.T) {
  152. testFs := newTestFS()
  153. stignore := `
  154. (?d)ign1
  155. (?d)(?i)ign2
  156. (?i)(?d)ign3
  157. !(?d)ign4
  158. !ign5
  159. !(?i)(?d)ign6
  160. ign7
  161. (?i)ign8
  162. `
  163. pats := New(testFs, WithCache(true))
  164. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  165. if err != nil {
  166. t.Fatal(err)
  167. }
  168. tests := []struct {
  169. f string
  170. i bool
  171. d bool
  172. }{
  173. {"ign1", true, true},
  174. {"ign2", true, true},
  175. {"ign3", true, true},
  176. {"ign4", false, false},
  177. {"ign5", false, false},
  178. {"ign6", false, false},
  179. {"ign7", true, false},
  180. {"ign8", true, false},
  181. }
  182. for _, tc := range tests {
  183. if r := pats.Match(tc.f); r.IsIgnored() != tc.i || r.IsDeletable() != tc.d {
  184. t.Errorf("Incorrect match for %s: %v != Result{%t, %t}", tc.f, r, tc.i, tc.d)
  185. }
  186. }
  187. }
  188. func TestBadPatterns(t *testing.T) {
  189. testFs := newTestFS()
  190. t.Skip("to fix: bad pattern not happening")
  191. badPatterns := []string{
  192. "[",
  193. "/[",
  194. "**/[",
  195. "#include nonexistent",
  196. "#include .stignore",
  197. }
  198. for _, pat := range badPatterns {
  199. err := New(testFs, WithCache(true)).Parse(bytes.NewBufferString(pat), ".stignore")
  200. if err == nil {
  201. t.Errorf("No error for pattern %q", pat)
  202. }
  203. if !IsParseError(err) {
  204. t.Error("Should have been a parse error:", err)
  205. }
  206. if strings.HasPrefix(pat, "#include") {
  207. if fs.IsNotExist(err) {
  208. t.Error("Includes should not toss a regular isNotExist error")
  209. }
  210. }
  211. }
  212. }
  213. func TestCaseSensitivity(t *testing.T) {
  214. testFs := newTestFS()
  215. ign := New(testFs, WithCache(true))
  216. err := ign.Parse(bytes.NewBufferString("test"), ".stignore")
  217. if err != nil {
  218. t.Error(err)
  219. }
  220. match := []string{"test"}
  221. dontMatch := []string{"foo"}
  222. if build.IsDarwin || build.IsWindows {
  223. match = append(match, "TEST", "Test", "tESt")
  224. } else {
  225. dontMatch = append(dontMatch, "TEST", "Test", "tESt")
  226. }
  227. for _, tc := range match {
  228. if !ign.Match(tc).IsIgnored() {
  229. t.Errorf("Incorrect match for %q: should be matched", tc)
  230. }
  231. }
  232. for _, tc := range dontMatch {
  233. if ign.Match(tc).IsIgnored() {
  234. t.Errorf("Incorrect match for %q: should not be matched", tc)
  235. }
  236. }
  237. }
  238. func TestCaching(t *testing.T) {
  239. fs := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?content=true")
  240. fd1, err := osutil.TempFile(fs, "", "")
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. fd2, err := osutil.TempFile(fs, "", "")
  245. if err != nil {
  246. t.Fatal(err)
  247. }
  248. defer fd1.Close()
  249. defer fd2.Close()
  250. defer fs.Remove(fd1.Name())
  251. defer fs.Remove(fd2.Name())
  252. _, err = fd1.Write([]byte("/x/\n#include " + filepath.Base(fd2.Name()) + "\n"))
  253. if err != nil {
  254. t.Fatal(err)
  255. }
  256. fd2.Write([]byte("/y/\n"))
  257. pats := New(fs, WithCache(true))
  258. err = pats.Load(fd1.Name())
  259. if err != nil {
  260. t.Fatal(err)
  261. }
  262. if pats.matches.len() != 0 {
  263. t.Fatal("Expected empty cache")
  264. }
  265. // Cache some outcomes
  266. for _, letter := range []string{"a", "b", "x", "y"} {
  267. pats.Match(letter)
  268. }
  269. if pats.matches.len() != 4 {
  270. t.Fatal("Expected 4 cached results")
  271. }
  272. // Reload file, expect old outcomes to be preserved
  273. err = pats.Load(fd1.Name())
  274. if err != nil {
  275. t.Fatal(err)
  276. }
  277. if pats.matches.len() != 4 {
  278. t.Fatal("Expected 4 cached results")
  279. }
  280. // Modify the include file, expect empty cache. Ensure the timestamp on
  281. // the file changes.
  282. fd2.Write([]byte("/z/\n"))
  283. fd2.Sync()
  284. fakeTime := time.Now().Add(5 * time.Second)
  285. fs.Chtimes(fd2.Name(), fakeTime, fakeTime)
  286. err = pats.Load(fd1.Name())
  287. if err != nil {
  288. t.Fatal(err)
  289. }
  290. if pats.matches.len() != 0 {
  291. t.Fatal("Expected 0 cached results")
  292. }
  293. // Cache some outcomes again
  294. for _, letter := range []string{"b", "x", "y"} {
  295. pats.Match(letter)
  296. }
  297. // Verify that outcomes preserved on next load
  298. err = pats.Load(fd1.Name())
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. if pats.matches.len() != 3 {
  303. t.Fatal("Expected 3 cached results")
  304. }
  305. // Modify the root file, expect cache to be invalidated
  306. fd1.Write([]byte("/a/\n"))
  307. fd1.Sync()
  308. fakeTime = time.Now().Add(5 * time.Second)
  309. fs.Chtimes(fd1.Name(), fakeTime, fakeTime)
  310. err = pats.Load(fd1.Name())
  311. if err != nil {
  312. t.Fatal(err)
  313. }
  314. if pats.matches.len() != 0 {
  315. t.Fatal("Expected cache invalidation")
  316. }
  317. // Cache some outcomes again
  318. for _, letter := range []string{"b", "x", "y"} {
  319. pats.Match(letter)
  320. }
  321. // Verify that outcomes provided on next load
  322. err = pats.Load(fd1.Name())
  323. if err != nil {
  324. t.Fatal(err)
  325. }
  326. if pats.matches.len() != 3 {
  327. t.Fatal("Expected 3 cached results")
  328. }
  329. }
  330. func TestCommentsAndBlankLines(t *testing.T) {
  331. testFs := newTestFS()
  332. stignore := `
  333. // foo
  334. //bar
  335. //!baz
  336. //#dex
  337. // ips
  338. `
  339. pats := New(testFs, WithCache(true))
  340. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  341. if err != nil {
  342. t.Error(err)
  343. }
  344. if len(pats.patterns) > 0 {
  345. t.Errorf("Expected no patterns")
  346. }
  347. }
  348. var result ignoreresult.R
  349. func BenchmarkMatch(b *testing.B) {
  350. testFs := newTestFS()
  351. stignore := `
  352. .frog
  353. .frog*
  354. .frogfox
  355. .whale
  356. .whale/*
  357. .dolphin
  358. .dolphin/*
  359. ~ferret~.*
  360. .ferret.*
  361. flamingo.*
  362. flamingo
  363. *.crow
  364. *.crow
  365. `
  366. pats := New(testFs)
  367. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  368. if err != nil {
  369. b.Error(err)
  370. }
  371. b.ResetTimer()
  372. for i := 0; i < b.N; i++ {
  373. result = pats.Match("filename")
  374. }
  375. }
  376. func BenchmarkMatchCached(b *testing.B) {
  377. stignore := `
  378. .frog
  379. .frog*
  380. .frogfox
  381. .whale
  382. .whale/*
  383. .dolphin
  384. .dolphin/*
  385. ~ferret~.*
  386. .ferret.*
  387. flamingo.*
  388. flamingo
  389. *.crow
  390. *.crow
  391. `
  392. // Caches per file, hence write the patterns to a file.
  393. fs := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?content=true")
  394. fd, err := osutil.TempFile(fs, "", "")
  395. if err != nil {
  396. b.Fatal(err)
  397. }
  398. _, err = fd.Write([]byte(stignore))
  399. defer fd.Close()
  400. defer fs.Remove(fd.Name())
  401. if err != nil {
  402. b.Fatal(err)
  403. }
  404. // Load the patterns
  405. pats := New(fs, WithCache(true))
  406. err = pats.Load(fd.Name())
  407. if err != nil {
  408. b.Fatal(err)
  409. }
  410. // Cache the outcome for "filename"
  411. pats.Match("filename")
  412. // This load should now load the cached outcomes as the set of patterns
  413. // has not changed.
  414. err = pats.Load(fd.Name())
  415. if err != nil {
  416. b.Fatal(err)
  417. }
  418. b.ResetTimer()
  419. for i := 0; i < b.N; i++ {
  420. result = pats.Match("filename")
  421. }
  422. }
  423. func TestCacheReload(t *testing.T) {
  424. fs := fs.NewFilesystem(fs.FilesystemTypeFake, rand.String(32)+"?content=true")
  425. fd, err := osutil.TempFile(fs, "", "")
  426. if err != nil {
  427. t.Fatal(err)
  428. }
  429. defer fd.Close()
  430. defer fs.Remove(fd.Name())
  431. // Ignore file matches f1 and f2
  432. _, err = fd.Write([]byte("f1\nf2\n"))
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. pats := New(fs, WithCache(true))
  437. err = pats.Load(fd.Name())
  438. if err != nil {
  439. t.Fatal(err)
  440. }
  441. // Verify that both are ignored
  442. if !pats.Match("f1").IsIgnored() {
  443. t.Error("Unexpected non-match for f1")
  444. }
  445. if !pats.Match("f2").IsIgnored() {
  446. t.Error("Unexpected non-match for f2")
  447. }
  448. if pats.Match("f3").IsIgnored() {
  449. t.Error("Unexpected match for f3")
  450. }
  451. // Rewrite file to match f1 and f3
  452. err = fd.Truncate(0)
  453. if err != nil {
  454. t.Fatal(err)
  455. }
  456. _, err = fd.Seek(0, io.SeekStart)
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. _, err = fd.Write([]byte("f1\nf3\n"))
  461. if err != nil {
  462. t.Fatal(err)
  463. }
  464. fd.Sync()
  465. fakeTime := time.Now().Add(5 * time.Second)
  466. fs.Chtimes(fd.Name(), fakeTime, fakeTime)
  467. err = pats.Load(fd.Name())
  468. if err != nil {
  469. t.Fatal(err)
  470. }
  471. // Verify that the new patterns are in effect
  472. if !pats.Match("f1").IsIgnored() {
  473. t.Error("Unexpected non-match for f1")
  474. }
  475. if pats.Match("f2").IsIgnored() {
  476. t.Error("Unexpected match for f2")
  477. }
  478. if !pats.Match("f3").IsIgnored() {
  479. t.Error("Unexpected non-match for f3")
  480. }
  481. }
  482. func TestHash(t *testing.T) {
  483. testFs := newTestFS()
  484. p1 := New(testFs, WithCache(true))
  485. err := p1.Load(".stignore")
  486. if err != nil {
  487. t.Fatal(err)
  488. }
  489. // Same list of patterns as .stignore, after expansion
  490. stignore := `
  491. dir2/dfile
  492. dir3
  493. bfile
  494. dir1/cfile
  495. **/efile
  496. /ffile
  497. lost+found
  498. `
  499. p2 := New(testFs, WithCache(true))
  500. err = p2.Parse(bytes.NewBufferString(stignore), ".stignore")
  501. if err != nil {
  502. t.Fatal(err)
  503. }
  504. // Not same list of patterns
  505. stignore = `
  506. dir2/dfile
  507. dir3
  508. bfile
  509. dir1/cfile
  510. /ffile
  511. lost+found
  512. `
  513. p3 := New(testFs, WithCache(true))
  514. err = p3.Parse(bytes.NewBufferString(stignore), ".stignore")
  515. if err != nil {
  516. t.Fatal(err)
  517. }
  518. if p1.Hash() == "" {
  519. t.Error("p1 hash blank")
  520. }
  521. if p2.Hash() == "" {
  522. t.Error("p2 hash blank")
  523. }
  524. if p3.Hash() == "" {
  525. t.Error("p3 hash blank")
  526. }
  527. if p1.Hash() != p2.Hash() {
  528. t.Error("p1-p2 hashes differ")
  529. }
  530. if p1.Hash() == p3.Hash() {
  531. t.Error("p1-p3 hashes same")
  532. }
  533. }
  534. func TestHashOfEmpty(t *testing.T) {
  535. testFs := newTestFS()
  536. p1 := New(testFs, WithCache(true))
  537. err := p1.Load(".stignore")
  538. if err != nil {
  539. t.Fatal(err)
  540. }
  541. firstHash := p1.Hash()
  542. // Reloading with a non-existent file should empty the patterns and
  543. // recalculate the hash.
  544. // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 is
  545. // the sah256 of nothing.
  546. p1.Load("file/does/not/exist")
  547. secondHash := p1.Hash()
  548. if firstHash == secondHash {
  549. t.Error("hash did not change")
  550. }
  551. if secondHash != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
  552. t.Error("second hash is not hash of empty string")
  553. }
  554. if len(p1.patterns) != 0 {
  555. t.Error("there are more than zero patterns")
  556. }
  557. }
  558. func TestWindowsPatterns(t *testing.T) {
  559. testFs := newTestFS()
  560. // We should accept patterns as both a/b and a\b and match that against
  561. // both kinds of slash as well.
  562. if !build.IsWindows {
  563. t.Skip("Windows specific test")
  564. return
  565. }
  566. stignore := `
  567. a/b
  568. c\d
  569. `
  570. pats := New(testFs, WithCache(true))
  571. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  572. if err != nil {
  573. t.Fatal(err)
  574. }
  575. tests := []string{`a\b`, `c\d`}
  576. for _, pat := range tests {
  577. if !pats.Match(pat).IsIgnored() {
  578. t.Errorf("Should match %s", pat)
  579. }
  580. }
  581. }
  582. func TestAutomaticCaseInsensitivity(t *testing.T) {
  583. testFs := newTestFS()
  584. // We should do case insensitive matching by default on some platforms.
  585. if !build.IsWindows && !build.IsDarwin {
  586. t.Skip("Windows/Mac specific test")
  587. return
  588. }
  589. stignore := `
  590. A/B
  591. c/d
  592. `
  593. pats := New(testFs, WithCache(true))
  594. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  595. if err != nil {
  596. t.Fatal(err)
  597. }
  598. tests := []string{`a/B`, `C/d`}
  599. for _, pat := range tests {
  600. if !pats.Match(pat).IsIgnored() {
  601. t.Errorf("Should match %s", pat)
  602. }
  603. }
  604. }
  605. func TestCommas(t *testing.T) {
  606. testFs := newTestFS()
  607. stignore := `
  608. foo,bar.txt
  609. {baz,quux}.txt
  610. `
  611. pats := New(testFs, WithCache(true))
  612. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. tests := []struct {
  617. name string
  618. match bool
  619. }{
  620. {"foo.txt", false},
  621. {"bar.txt", false},
  622. {"foo,bar.txt", true},
  623. {"baz.txt", true},
  624. {"quux.txt", true},
  625. {"baz,quux.txt", false},
  626. }
  627. for _, tc := range tests {
  628. if pats.Match(tc.name).IsIgnored() != tc.match {
  629. t.Errorf("Match of %s was %v, should be %v", tc.name, !tc.match, tc.match)
  630. }
  631. }
  632. }
  633. func TestIssue3164(t *testing.T) {
  634. testFs := newTestFS()
  635. stignore := `
  636. (?d)(?i)*.part
  637. (?d)(?i)/foo
  638. (?d)(?i)**/bar
  639. `
  640. pats := New(testFs, WithCache(true))
  641. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  642. if err != nil {
  643. t.Fatal(err)
  644. }
  645. expanded := pats.Patterns()
  646. t.Log(expanded)
  647. expected := []string{
  648. "(?d)(?i)*.part",
  649. "(?d)(?i)**/*.part",
  650. "(?d)(?i)*.part/**",
  651. "(?d)(?i)**/*.part/**",
  652. "(?d)(?i)/foo",
  653. "(?d)(?i)/foo/**",
  654. "(?d)(?i)**/bar",
  655. "(?d)(?i)bar",
  656. "(?d)(?i)**/bar/**",
  657. "(?d)(?i)bar/**",
  658. }
  659. if len(expanded) != len(expected) {
  660. t.Errorf("Unmatched count: %d != %d", len(expanded), len(expected))
  661. }
  662. for i := range expanded {
  663. if expanded[i] != expected[i] {
  664. t.Errorf("Pattern %d does not match: %s != %s", i, expanded[i], expected[i])
  665. }
  666. }
  667. }
  668. func TestIssue3174(t *testing.T) {
  669. testFs := newTestFS()
  670. stignore := `
  671. *ä*
  672. `
  673. pats := New(testFs, WithCache(true))
  674. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  675. if err != nil {
  676. t.Fatal(err)
  677. }
  678. if !pats.Match("åäö").IsIgnored() {
  679. t.Error("Should match")
  680. }
  681. }
  682. func TestIssue3639(t *testing.T) {
  683. testFs := newTestFS()
  684. stignore := `
  685. foo/
  686. `
  687. pats := New(testFs, WithCache(true))
  688. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  689. if err != nil {
  690. t.Fatal(err)
  691. }
  692. if !pats.Match("foo/bar").IsIgnored() {
  693. t.Error("Should match 'foo/bar'")
  694. }
  695. if pats.Match("foo").IsIgnored() {
  696. t.Error("Should not match 'foo'")
  697. }
  698. }
  699. func TestIssue3674(t *testing.T) {
  700. testFs := newTestFS()
  701. stignore := `
  702. a*b
  703. a**c
  704. `
  705. testcases := []struct {
  706. file string
  707. matches bool
  708. }{
  709. {"ab", true},
  710. {"asdfb", true},
  711. {"ac", true},
  712. {"asdfc", true},
  713. {"as/db", false},
  714. {"as/dc", true},
  715. }
  716. pats := New(testFs, WithCache(true))
  717. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  718. if err != nil {
  719. t.Fatal(err)
  720. }
  721. for _, tc := range testcases {
  722. res := pats.Match(tc.file).IsIgnored()
  723. if res != tc.matches {
  724. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  725. }
  726. }
  727. }
  728. func TestGobwasGlobIssue18(t *testing.T) {
  729. testFs := newTestFS()
  730. stignore := `
  731. a?b
  732. bb?
  733. `
  734. testcases := []struct {
  735. file string
  736. matches bool
  737. }{
  738. {"ab", false},
  739. {"acb", true},
  740. {"asdb", false},
  741. {"bb", false},
  742. {"bba", true},
  743. {"bbaa", false},
  744. }
  745. pats := New(testFs, WithCache(true))
  746. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  747. if err != nil {
  748. t.Fatal(err)
  749. }
  750. for _, tc := range testcases {
  751. res := pats.Match(tc.file).IsIgnored()
  752. if res != tc.matches {
  753. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  754. }
  755. }
  756. }
  757. func TestRoot(t *testing.T) {
  758. testFs := newTestFS()
  759. stignore := `
  760. !/a
  761. /*
  762. `
  763. testcases := []struct {
  764. file string
  765. matches bool
  766. }{
  767. {".", false},
  768. {"a", false},
  769. {"b", true},
  770. }
  771. pats := New(testFs, WithCache(true))
  772. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  773. if err != nil {
  774. t.Fatal(err)
  775. }
  776. for _, tc := range testcases {
  777. res := pats.Match(tc.file).IsIgnored()
  778. if res != tc.matches {
  779. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  780. }
  781. }
  782. }
  783. func TestLines(t *testing.T) {
  784. testFs := newTestFS()
  785. stignore := `
  786. #include excludes
  787. !/a
  788. /*
  789. !/a
  790. `
  791. pats := New(testFs, WithCache(true))
  792. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  793. if err != nil {
  794. t.Fatal(err)
  795. }
  796. expectedLines := []string{
  797. "",
  798. "#include excludes",
  799. "",
  800. "!/a",
  801. "/*",
  802. "!/a",
  803. "",
  804. }
  805. lines := pats.Lines()
  806. if len(lines) != len(expectedLines) {
  807. t.Fatalf("len(Lines()) == %d, expected %d", len(lines), len(expectedLines))
  808. }
  809. for i := range lines {
  810. if lines[i] != expectedLines[i] {
  811. t.Fatalf("Lines()[%d] == %s, expected %s", i, lines[i], expectedLines[i])
  812. }
  813. }
  814. }
  815. func TestDuplicateLines(t *testing.T) {
  816. testFs := newTestFS()
  817. stignore := `
  818. !/a
  819. /*
  820. !/a
  821. `
  822. stignoreFiltered := `
  823. !/a
  824. /*
  825. `
  826. pats := New(testFs, WithCache(true))
  827. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  828. if err != nil {
  829. t.Fatal(err)
  830. }
  831. patsLen := len(pats.patterns)
  832. err = pats.Parse(bytes.NewBufferString(stignoreFiltered), ".stignore")
  833. if err != nil {
  834. t.Fatal(err)
  835. }
  836. if patsLen != len(pats.patterns) {
  837. t.Fatalf("Parsed patterns differ when manually removing duplicate lines")
  838. }
  839. }
  840. func TestIssue4680(t *testing.T) {
  841. testFs := newTestFS()
  842. stignore := `
  843. #snapshot
  844. `
  845. testcases := []struct {
  846. file string
  847. matches bool
  848. }{
  849. {"#snapshot", true},
  850. {"#snapshot/foo", true},
  851. }
  852. pats := New(testFs, WithCache(true))
  853. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  854. if err != nil {
  855. t.Fatal(err)
  856. }
  857. for _, tc := range testcases {
  858. res := pats.Match(tc.file).IsIgnored()
  859. if res != tc.matches {
  860. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  861. }
  862. }
  863. }
  864. func TestIssue4689(t *testing.T) {
  865. testFs := newTestFS()
  866. stignore := `// orig`
  867. pats := New(testFs, WithCache(true))
  868. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  869. if err != nil {
  870. t.Fatal(err)
  871. }
  872. if lines := pats.Lines(); len(lines) != 1 || lines[0] != "// orig" {
  873. t.Fatalf("wrong lines parsing original comment:\n%q", lines)
  874. }
  875. stignore = `// new`
  876. err = pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  877. if err != nil {
  878. t.Fatal(err)
  879. }
  880. if lines := pats.Lines(); len(lines) != 1 || lines[0] != "// new" {
  881. t.Fatalf("wrong lines parsing changed comment:\n%v", lines)
  882. }
  883. }
  884. func TestIssue4901(t *testing.T) {
  885. testFs := newTestFS()
  886. stignore := `
  887. #include unicorn-lazor-death
  888. puppy
  889. `
  890. pats := New(testFs, WithCache(true))
  891. fd, err := pats.fs.Create(".stignore")
  892. if err != nil {
  893. t.Fatalf(err.Error())
  894. }
  895. if _, err := fd.Write([]byte(stignore)); err != nil {
  896. t.Fatal(err)
  897. }
  898. // Cache does not suddenly make the load succeed.
  899. for i := 0; i < 2; i++ {
  900. err := pats.Load(".stignore")
  901. if err == nil {
  902. t.Fatal("expected an error")
  903. }
  904. if err == fs.ErrNotExist {
  905. t.Fatalf("unexpected error type: %T", err)
  906. }
  907. if !IsParseError(err) {
  908. t.Fatal("failure to load included file should be a parse error")
  909. }
  910. }
  911. fd, err = pats.fs.Create("unicorn-lazor-death")
  912. if err != nil {
  913. t.Fatalf(err.Error())
  914. }
  915. if _, err := fd.Write([]byte(" ")); err != nil {
  916. t.Fatal(err)
  917. }
  918. err = pats.Load(".stignore")
  919. if err != nil {
  920. t.Fatalf("unexpected error: %s", err.Error())
  921. }
  922. }
  923. // TestIssue5009 checks that ignored dirs are only skipped if there are no include patterns.
  924. // https://github.com/syncthing/syncthing/issues/5009 (rc-only bug)
  925. func TestIssue5009(t *testing.T) {
  926. testFs := newTestFS()
  927. pats := New(testFs, WithCache(true))
  928. stignore := `
  929. ign1
  930. i*2
  931. `
  932. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  933. t.Fatal(err)
  934. }
  935. if m := pats.Match("ign2"); !m.CanSkipDir() {
  936. t.Error("CanSkipDir should be true without excludes")
  937. }
  938. stignore = `
  939. !iex2
  940. !ign1/ex
  941. ign1
  942. i*2
  943. !ign2
  944. `
  945. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  946. t.Fatal(err)
  947. }
  948. if m := pats.Match("ign2"); m.CanSkipDir() {
  949. t.Error("CanSkipDir should not be true with excludes")
  950. }
  951. }
  952. func TestSpecialChars(t *testing.T) {
  953. testFs := newTestFS()
  954. pats := New(testFs, WithCache(true))
  955. stignore := `(?i)/#recycle
  956. (?i)/#nosync
  957. (?i)/$Recycle.bin
  958. (?i)/$RECYCLE.BIN
  959. (?i)/System Volume Information`
  960. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  961. t.Fatal(err)
  962. }
  963. cases := []string{
  964. "#nosync",
  965. "$RECYCLE.BIN",
  966. filepath.FromSlash("$RECYCLE.BIN/S-1-5-18/desktop.ini"),
  967. }
  968. for _, c := range cases {
  969. if !pats.Match(c).IsIgnored() {
  970. t.Errorf("%q should be ignored", c)
  971. }
  972. }
  973. }
  974. func TestIntlWildcards(t *testing.T) {
  975. testFs := newTestFS()
  976. pats := New(testFs, WithCache(true))
  977. stignore := `1000春
  978. 200?春
  979. 300[0-9]春
  980. 400[0-9]?`
  981. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  982. t.Fatal(err)
  983. }
  984. cases := []string{
  985. "1000春",
  986. "2002春",
  987. "3003春",
  988. "4004春",
  989. }
  990. for _, c := range cases {
  991. if !pats.Match(c).IsIgnored() {
  992. t.Errorf("%q should be ignored", c)
  993. }
  994. }
  995. }
  996. func TestPartialIncludeLine(t *testing.T) {
  997. testFs := newTestFS()
  998. // Loading a partial #include line (no file mentioned) should error but not crash.
  999. pats := New(testFs, WithCache(true))
  1000. cases := []string{
  1001. "#include",
  1002. "#include\n",
  1003. "#include ",
  1004. "#include \n",
  1005. "#include \n\n\n",
  1006. }
  1007. for _, tc := range cases {
  1008. err := pats.Parse(bytes.NewBufferString(tc), ".stignore")
  1009. if err == nil {
  1010. t.Fatal("should error out")
  1011. }
  1012. if !IsParseError(err) {
  1013. t.Fatal("failure to load included file should be a parse error")
  1014. }
  1015. }
  1016. }
  1017. func TestSkipIgnoredDirs(t *testing.T) {
  1018. testFs := newTestFS()
  1019. tcs := []struct {
  1020. pattern string
  1021. expected bool
  1022. }{
  1023. {`!/test`, true},
  1024. {`!/t[eih]t`, true},
  1025. {`!/t*t`, true},
  1026. {`!/t?t`, true},
  1027. {`!/**`, true},
  1028. {`!/parent/test`, false},
  1029. {`!/parent/t[eih]t`, false},
  1030. {`!/parent/t*t`, false},
  1031. {`!/parent/t?t`, false},
  1032. {`!/**.mp3`, false},
  1033. {`!/pa*nt/test`, false},
  1034. {`!/pa[sdf]nt/t[eih]t`, false},
  1035. {`!/lowest/pa[sdf]nt/test`, false},
  1036. {`!/lo*st/parent/test`, false},
  1037. {`/pa*nt/test`, true},
  1038. {`test`, true},
  1039. {`*`, true},
  1040. }
  1041. for _, tc := range tcs {
  1042. pats, err := parseLine(tc.pattern)
  1043. if err != nil {
  1044. t.Error(err)
  1045. }
  1046. for _, pat := range pats {
  1047. if got := pat.allowsSkippingIgnoredDirs(); got != tc.expected {
  1048. t.Errorf(`Pattern "%v": got %v, expected %v`, pat, got, tc.expected)
  1049. }
  1050. }
  1051. }
  1052. pats := New(testFs, WithCache(true))
  1053. stignore := `
  1054. /foo/ign*
  1055. !/f*
  1056. !/bar
  1057. *
  1058. `
  1059. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  1060. t.Fatal(err)
  1061. }
  1062. if m := pats.Match("whatever"); !m.CanSkipDir() {
  1063. t.Error("CanSkipDir should be true")
  1064. }
  1065. stignore = `
  1066. !/foo/ign*
  1067. *
  1068. `
  1069. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  1070. t.Fatal(err)
  1071. }
  1072. if m := pats.Match("whatever"); m.CanSkipDir() {
  1073. t.Error("CanSkipDir should be false")
  1074. }
  1075. }
  1076. func TestEmptyPatterns(t *testing.T) {
  1077. testFs := newTestFS()
  1078. // These patterns are all invalid and should be rejected as such (without panicking...)
  1079. tcs := []string{
  1080. "!",
  1081. "(?d)",
  1082. "(?i)",
  1083. }
  1084. for _, tc := range tcs {
  1085. m := New(testFs)
  1086. err := m.Parse(strings.NewReader(tc), ".stignore")
  1087. if err == nil {
  1088. t.Error("Should reject invalid pattern", tc)
  1089. }
  1090. if !IsParseError(err) {
  1091. t.Fatal("bad pattern should be a parse error")
  1092. }
  1093. }
  1094. }
  1095. func TestWindowsLineEndings(t *testing.T) {
  1096. testFs := newTestFS()
  1097. if !build.IsWindows {
  1098. t.Skip("Windows specific")
  1099. }
  1100. lines := "foo\nbar\nbaz\n"
  1101. m := New(testFs)
  1102. if err := m.Parse(strings.NewReader(lines), ".stignore"); err != nil {
  1103. t.Fatal(err)
  1104. }
  1105. if err := WriteIgnores(testFs, ".stignore", m.Lines()); err != nil {
  1106. t.Fatal(err)
  1107. }
  1108. fd, err := testFs.Open(".stignore")
  1109. if err != nil {
  1110. t.Fatal(err)
  1111. }
  1112. bs, err := io.ReadAll(fd)
  1113. fd.Close()
  1114. if err != nil {
  1115. t.Fatal(err)
  1116. }
  1117. unixLineEndings := bytes.Count(bs, []byte("\n"))
  1118. windowsLineEndings := bytes.Count(bs, []byte("\r\n"))
  1119. if unixLineEndings == 0 || windowsLineEndings != unixLineEndings {
  1120. t.Error("expected there to be a non-zero number of Windows line endings")
  1121. }
  1122. }