ignore_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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. // The pattern above is normalized when parsing, and in order for this
  679. // string to match the pattern, it needs to use the same normalization. And
  680. // Go always uses NFC regardless of OS, while we use NFD on macos.
  681. if !pats.Match(nativeUnicodeNorm("åäö")).IsIgnored() {
  682. t.Error("Should match")
  683. }
  684. }
  685. func TestIssue3639(t *testing.T) {
  686. testFs := newTestFS()
  687. stignore := `
  688. foo/
  689. `
  690. pats := New(testFs, WithCache(true))
  691. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  692. if err != nil {
  693. t.Fatal(err)
  694. }
  695. if !pats.Match("foo/bar").IsIgnored() {
  696. t.Error("Should match 'foo/bar'")
  697. }
  698. if pats.Match("foo").IsIgnored() {
  699. t.Error("Should not match 'foo'")
  700. }
  701. }
  702. func TestIssue3674(t *testing.T) {
  703. testFs := newTestFS()
  704. stignore := `
  705. a*b
  706. a**c
  707. `
  708. testcases := []struct {
  709. file string
  710. matches bool
  711. }{
  712. {"ab", true},
  713. {"asdfb", true},
  714. {"ac", true},
  715. {"asdfc", true},
  716. {"as/db", false},
  717. {"as/dc", true},
  718. }
  719. pats := New(testFs, WithCache(true))
  720. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  721. if err != nil {
  722. t.Fatal(err)
  723. }
  724. for _, tc := range testcases {
  725. res := pats.Match(tc.file).IsIgnored()
  726. if res != tc.matches {
  727. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  728. }
  729. }
  730. }
  731. func TestGobwasGlobIssue18(t *testing.T) {
  732. testFs := newTestFS()
  733. stignore := `
  734. a?b
  735. bb?
  736. `
  737. testcases := []struct {
  738. file string
  739. matches bool
  740. }{
  741. {"ab", false},
  742. {"acb", true},
  743. {"asdb", false},
  744. {"bb", false},
  745. {"bba", true},
  746. {"bbaa", false},
  747. }
  748. pats := New(testFs, WithCache(true))
  749. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  750. if err != nil {
  751. t.Fatal(err)
  752. }
  753. for _, tc := range testcases {
  754. res := pats.Match(tc.file).IsIgnored()
  755. if res != tc.matches {
  756. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  757. }
  758. }
  759. }
  760. func TestRoot(t *testing.T) {
  761. testFs := newTestFS()
  762. stignore := `
  763. !/a
  764. /*
  765. `
  766. testcases := []struct {
  767. file string
  768. matches bool
  769. }{
  770. {".", false},
  771. {"a", false},
  772. {"b", true},
  773. }
  774. pats := New(testFs, WithCache(true))
  775. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  776. if err != nil {
  777. t.Fatal(err)
  778. }
  779. for _, tc := range testcases {
  780. res := pats.Match(tc.file).IsIgnored()
  781. if res != tc.matches {
  782. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  783. }
  784. }
  785. }
  786. func TestLines(t *testing.T) {
  787. testFs := newTestFS()
  788. stignore := `
  789. #include excludes
  790. !/a
  791. /*
  792. !/a
  793. `
  794. pats := New(testFs, WithCache(true))
  795. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  796. if err != nil {
  797. t.Fatal(err)
  798. }
  799. expectedLines := []string{
  800. "",
  801. "#include excludes",
  802. "",
  803. "!/a",
  804. "/*",
  805. "!/a",
  806. "",
  807. }
  808. lines := pats.Lines()
  809. if len(lines) != len(expectedLines) {
  810. t.Fatalf("len(Lines()) == %d, expected %d", len(lines), len(expectedLines))
  811. }
  812. for i := range lines {
  813. if lines[i] != expectedLines[i] {
  814. t.Fatalf("Lines()[%d] == %s, expected %s", i, lines[i], expectedLines[i])
  815. }
  816. }
  817. }
  818. func TestDuplicateLines(t *testing.T) {
  819. testFs := newTestFS()
  820. stignore := `
  821. !/a
  822. /*
  823. !/a
  824. `
  825. stignoreFiltered := `
  826. !/a
  827. /*
  828. `
  829. pats := New(testFs, WithCache(true))
  830. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  831. if err != nil {
  832. t.Fatal(err)
  833. }
  834. patsLen := len(pats.patterns)
  835. err = pats.Parse(bytes.NewBufferString(stignoreFiltered), ".stignore")
  836. if err != nil {
  837. t.Fatal(err)
  838. }
  839. if patsLen != len(pats.patterns) {
  840. t.Fatalf("Parsed patterns differ when manually removing duplicate lines")
  841. }
  842. }
  843. func TestIssue4680(t *testing.T) {
  844. testFs := newTestFS()
  845. stignore := `
  846. #snapshot
  847. `
  848. testcases := []struct {
  849. file string
  850. matches bool
  851. }{
  852. {"#snapshot", true},
  853. {"#snapshot/foo", true},
  854. }
  855. pats := New(testFs, WithCache(true))
  856. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  857. if err != nil {
  858. t.Fatal(err)
  859. }
  860. for _, tc := range testcases {
  861. res := pats.Match(tc.file).IsIgnored()
  862. if res != tc.matches {
  863. t.Errorf("Matches(%q) == %v, expected %v", tc.file, res, tc.matches)
  864. }
  865. }
  866. }
  867. func TestIssue4689(t *testing.T) {
  868. testFs := newTestFS()
  869. stignore := `// orig`
  870. pats := New(testFs, WithCache(true))
  871. err := pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  872. if err != nil {
  873. t.Fatal(err)
  874. }
  875. if lines := pats.Lines(); len(lines) != 1 || lines[0] != "// orig" {
  876. t.Fatalf("wrong lines parsing original comment:\n%q", lines)
  877. }
  878. stignore = `// new`
  879. err = pats.Parse(bytes.NewBufferString(stignore), ".stignore")
  880. if err != nil {
  881. t.Fatal(err)
  882. }
  883. if lines := pats.Lines(); len(lines) != 1 || lines[0] != "// new" {
  884. t.Fatalf("wrong lines parsing changed comment:\n%v", lines)
  885. }
  886. }
  887. func TestIssue4901(t *testing.T) {
  888. testFs := newTestFS()
  889. stignore := `
  890. #include unicorn-lazor-death
  891. puppy
  892. `
  893. pats := New(testFs, WithCache(true))
  894. fd, err := pats.fs.Create(".stignore")
  895. if err != nil {
  896. t.Fatalf(err.Error())
  897. }
  898. if _, err := fd.Write([]byte(stignore)); err != nil {
  899. t.Fatal(err)
  900. }
  901. // Cache does not suddenly make the load succeed.
  902. for i := 0; i < 2; i++ {
  903. err := pats.Load(".stignore")
  904. if err == nil {
  905. t.Fatal("expected an error")
  906. }
  907. if err == fs.ErrNotExist {
  908. t.Fatalf("unexpected error type: %T", err)
  909. }
  910. if !IsParseError(err) {
  911. t.Fatal("failure to load included file should be a parse error")
  912. }
  913. }
  914. fd, err = pats.fs.Create("unicorn-lazor-death")
  915. if err != nil {
  916. t.Fatalf(err.Error())
  917. }
  918. if _, err := fd.Write([]byte(" ")); err != nil {
  919. t.Fatal(err)
  920. }
  921. err = pats.Load(".stignore")
  922. if err != nil {
  923. t.Fatalf("unexpected error: %s", err.Error())
  924. }
  925. }
  926. // TestIssue5009 checks that ignored dirs are only skipped if there are no include patterns.
  927. // https://github.com/syncthing/syncthing/issues/5009 (rc-only bug)
  928. func TestIssue5009(t *testing.T) {
  929. testFs := newTestFS()
  930. pats := New(testFs, WithCache(true))
  931. stignore := `
  932. ign1
  933. i*2
  934. `
  935. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  936. t.Fatal(err)
  937. }
  938. if m := pats.Match("ign2"); !m.CanSkipDir() {
  939. t.Error("CanSkipDir should be true without excludes")
  940. }
  941. stignore = `
  942. !iex2
  943. !ign1/ex
  944. ign1
  945. i*2
  946. !ign2
  947. `
  948. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  949. t.Fatal(err)
  950. }
  951. if m := pats.Match("ign2"); m.CanSkipDir() {
  952. t.Error("CanSkipDir should not be true with excludes")
  953. }
  954. }
  955. func TestSpecialChars(t *testing.T) {
  956. testFs := newTestFS()
  957. pats := New(testFs, WithCache(true))
  958. stignore := `(?i)/#recycle
  959. (?i)/#nosync
  960. (?i)/$Recycle.bin
  961. (?i)/$RECYCLE.BIN
  962. (?i)/System Volume Information`
  963. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  964. t.Fatal(err)
  965. }
  966. cases := []string{
  967. "#nosync",
  968. "$RECYCLE.BIN",
  969. filepath.FromSlash("$RECYCLE.BIN/S-1-5-18/desktop.ini"),
  970. }
  971. for _, c := range cases {
  972. if !pats.Match(c).IsIgnored() {
  973. t.Errorf("%q should be ignored", c)
  974. }
  975. }
  976. }
  977. func TestIntlWildcards(t *testing.T) {
  978. testFs := newTestFS()
  979. pats := New(testFs, WithCache(true))
  980. stignore := `1000春
  981. 200?春
  982. 300[0-9]春
  983. 400[0-9]?`
  984. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  985. t.Fatal(err)
  986. }
  987. cases := []string{
  988. "1000春",
  989. "2002春",
  990. "3003春",
  991. "4004春",
  992. }
  993. for _, c := range cases {
  994. if !pats.Match(c).IsIgnored() {
  995. t.Errorf("%q should be ignored", c)
  996. }
  997. }
  998. }
  999. func TestPartialIncludeLine(t *testing.T) {
  1000. testFs := newTestFS()
  1001. // Loading a partial #include line (no file mentioned) should error but not crash.
  1002. pats := New(testFs, WithCache(true))
  1003. cases := []string{
  1004. "#include",
  1005. "#include\n",
  1006. "#include ",
  1007. "#include \n",
  1008. "#include \n\n\n",
  1009. }
  1010. for _, tc := range cases {
  1011. err := pats.Parse(bytes.NewBufferString(tc), ".stignore")
  1012. if err == nil {
  1013. t.Fatal("should error out")
  1014. }
  1015. if !IsParseError(err) {
  1016. t.Fatal("failure to load included file should be a parse error")
  1017. }
  1018. }
  1019. }
  1020. func TestSkipIgnoredDirs(t *testing.T) {
  1021. testFs := newTestFS()
  1022. tcs := []struct {
  1023. pattern string
  1024. expected bool
  1025. }{
  1026. {`!/test`, true},
  1027. {`!/t[eih]t`, true},
  1028. {`!/t*t`, true},
  1029. {`!/t?t`, true},
  1030. {`!/**`, true},
  1031. {`!/parent/test`, false},
  1032. {`!/parent/t[eih]t`, false},
  1033. {`!/parent/t*t`, false},
  1034. {`!/parent/t?t`, false},
  1035. {`!/**.mp3`, false},
  1036. {`!/pa*nt/test`, false},
  1037. {`!/pa[sdf]nt/t[eih]t`, false},
  1038. {`!/lowest/pa[sdf]nt/test`, false},
  1039. {`!/lo*st/parent/test`, false},
  1040. {`/pa*nt/test`, true},
  1041. {`test`, true},
  1042. {`*`, true},
  1043. }
  1044. for _, tc := range tcs {
  1045. pats, err := parseLine(tc.pattern)
  1046. if err != nil {
  1047. t.Error(err)
  1048. }
  1049. for _, pat := range pats {
  1050. if got := pat.allowsSkippingIgnoredDirs(); got != tc.expected {
  1051. t.Errorf(`Pattern "%v": got %v, expected %v`, pat, got, tc.expected)
  1052. }
  1053. }
  1054. }
  1055. pats := New(testFs, WithCache(true))
  1056. stignore := `
  1057. /foo/ign*
  1058. !/f*
  1059. !/bar
  1060. *
  1061. `
  1062. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  1063. t.Fatal(err)
  1064. }
  1065. if m := pats.Match("whatever"); !m.CanSkipDir() {
  1066. t.Error("CanSkipDir should be true")
  1067. }
  1068. stignore = `
  1069. !/foo/ign*
  1070. *
  1071. `
  1072. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  1073. t.Fatal(err)
  1074. }
  1075. if m := pats.Match("whatever"); m.CanSkipDir() {
  1076. t.Error("CanSkipDir should be false")
  1077. }
  1078. }
  1079. func TestEmptyPatterns(t *testing.T) {
  1080. testFs := newTestFS()
  1081. // These patterns are all invalid and should be rejected as such (without panicking...)
  1082. tcs := []string{
  1083. "!",
  1084. "(?d)",
  1085. "(?i)",
  1086. }
  1087. for _, tc := range tcs {
  1088. m := New(testFs)
  1089. err := m.Parse(strings.NewReader(tc), ".stignore")
  1090. if err == nil {
  1091. t.Error("Should reject invalid pattern", tc)
  1092. }
  1093. if !IsParseError(err) {
  1094. t.Fatal("bad pattern should be a parse error")
  1095. }
  1096. }
  1097. }
  1098. func TestWindowsLineEndings(t *testing.T) {
  1099. testFs := newTestFS()
  1100. if !build.IsWindows {
  1101. t.Skip("Windows specific")
  1102. }
  1103. lines := "foo\nbar\nbaz\n"
  1104. m := New(testFs)
  1105. if err := m.Parse(strings.NewReader(lines), ".stignore"); err != nil {
  1106. t.Fatal(err)
  1107. }
  1108. if err := WriteIgnores(testFs, ".stignore", m.Lines()); err != nil {
  1109. t.Fatal(err)
  1110. }
  1111. fd, err := testFs.Open(".stignore")
  1112. if err != nil {
  1113. t.Fatal(err)
  1114. }
  1115. bs, err := io.ReadAll(fd)
  1116. fd.Close()
  1117. if err != nil {
  1118. t.Fatal(err)
  1119. }
  1120. unixLineEndings := bytes.Count(bs, []byte("\n"))
  1121. windowsLineEndings := bytes.Count(bs, []byte("\r\n"))
  1122. if unixLineEndings == 0 || windowsLineEndings != unixLineEndings {
  1123. t.Error("expected there to be a non-zero number of Windows line endings")
  1124. }
  1125. }