ignore_test.go 25 KB

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