walk_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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 scanner
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/rand"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. rdebug "runtime/debug"
  18. "sort"
  19. "sync"
  20. "testing"
  21. "github.com/d4l3k/messagediff"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/ignore"
  24. "github.com/syncthing/syncthing/lib/osutil"
  25. "github.com/syncthing/syncthing/lib/protocol"
  26. "github.com/syncthing/syncthing/lib/sha256"
  27. "golang.org/x/text/unicode/norm"
  28. )
  29. type testfile struct {
  30. name string
  31. length int64
  32. hash string
  33. }
  34. type testfileList []testfile
  35. var testFs fs.Filesystem
  36. var testdata = testfileList{
  37. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  38. {"dir1", 128, ""},
  39. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  40. {"dir2", 128, ""},
  41. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  42. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  43. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  44. }
  45. func init() {
  46. // This test runs the risk of entering infinite recursion if it fails.
  47. // Limit the stack size to 10 megs to crash early in that case instead of
  48. // potentially taking down the box...
  49. rdebug.SetMaxStack(10 * 1 << 20)
  50. testFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  51. }
  52. func TestWalkSub(t *testing.T) {
  53. ignores := ignore.New(testFs)
  54. err := ignores.Load(".stignore")
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. fchan := Walk(context.TODO(), Config{
  59. Filesystem: testFs,
  60. Subs: []string{"dir2"},
  61. Matcher: ignores,
  62. Hashers: 2,
  63. })
  64. var files []protocol.FileInfo
  65. for f := range fchan {
  66. files = append(files, f)
  67. }
  68. // The directory contains two files, where one is ignored from a higher
  69. // level. We should see only the directory and one of the files.
  70. if len(files) != 2 {
  71. t.Fatalf("Incorrect length %d != 2", len(files))
  72. }
  73. if files[0].Name != "dir2" {
  74. t.Errorf("Incorrect file %v != dir2", files[0])
  75. }
  76. if files[1].Name != filepath.Join("dir2", "cfile") {
  77. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  78. }
  79. }
  80. func TestWalk(t *testing.T) {
  81. ignores := ignore.New(testFs)
  82. err := ignores.Load(".stignore")
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. t.Log(ignores)
  87. fchan := Walk(context.TODO(), Config{
  88. Filesystem: testFs,
  89. Matcher: ignores,
  90. Hashers: 2,
  91. })
  92. var tmp []protocol.FileInfo
  93. for f := range fchan {
  94. tmp = append(tmp, f)
  95. }
  96. sort.Sort(fileList(tmp))
  97. files := fileList(tmp).testfiles()
  98. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  99. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  100. }
  101. }
  102. func TestVerify(t *testing.T) {
  103. blocksize := 16
  104. // data should be an even multiple of blocksize long
  105. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  106. buf := bytes.NewBuffer(data)
  107. progress := newByteCounter()
  108. defer progress.Close()
  109. blocks, err := Blocks(context.TODO(), buf, blocksize, -1, progress, false)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. if exp := len(data) / blocksize; len(blocks) != exp {
  114. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  115. }
  116. if int64(len(data)) != progress.Total() {
  117. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  118. }
  119. buf = bytes.NewBuffer(data)
  120. err = verify(buf, blocksize, blocks)
  121. t.Log(err)
  122. if err != nil {
  123. t.Fatal("Unexpected verify failure", err)
  124. }
  125. buf = bytes.NewBuffer(append(data, '\n'))
  126. err = verify(buf, blocksize, blocks)
  127. t.Log(err)
  128. if err == nil {
  129. t.Fatal("Unexpected verify success")
  130. }
  131. buf = bytes.NewBuffer(data[:len(data)-1])
  132. err = verify(buf, blocksize, blocks)
  133. t.Log(err)
  134. if err == nil {
  135. t.Fatal("Unexpected verify success")
  136. }
  137. data[42] = 42
  138. buf = bytes.NewBuffer(data)
  139. err = verify(buf, blocksize, blocks)
  140. t.Log(err)
  141. if err == nil {
  142. t.Fatal("Unexpected verify success")
  143. }
  144. }
  145. func TestNormalization(t *testing.T) {
  146. if runtime.GOOS == "darwin" {
  147. t.Skip("Normalization test not possible on darwin")
  148. return
  149. }
  150. os.RemoveAll("testdata/normalization")
  151. defer os.RemoveAll("testdata/normalization")
  152. tests := []string{
  153. "0-A", // ASCII A -- accepted
  154. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  155. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  156. "2-\xC3\x85", // NFC 'Å' -- accepted
  157. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  158. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  159. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  160. }
  161. numInvalid := 2
  162. if runtime.GOOS == "windows" {
  163. // On Windows, in case 5 the character gets replaced with a
  164. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  165. // which means it suddenly becomes valid (sort of).
  166. numInvalid--
  167. }
  168. numValid := len(tests) - numInvalid
  169. for _, s1 := range tests {
  170. // Create a directory for each of the interesting strings above
  171. if err := testFs.MkdirAll(filepath.Join("normalization", s1), 0755); err != nil {
  172. t.Fatal(err)
  173. }
  174. for _, s2 := range tests {
  175. // Within each dir, create a file with each of the interesting
  176. // file names. Ensure that the file doesn't exist when it's
  177. // created. This detects and fails if there's file name
  178. // normalization stuff at the filesystem level.
  179. if fd, err := testFs.OpenFile(filepath.Join("normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  180. t.Fatal(err)
  181. } else {
  182. fd.Write([]byte("test"))
  183. fd.Close()
  184. }
  185. }
  186. }
  187. // We can normalize a directory name, but we can't descend into it in the
  188. // same pass due to how filepath.Walk works. So we run the scan twice to
  189. // make sure it all gets done. In production, things will be correct
  190. // eventually...
  191. walkDir(testFs, "normalization", nil, nil, 0)
  192. tmp := walkDir(testFs, "normalization", nil, nil, 0)
  193. files := fileList(tmp).testfiles()
  194. // We should have one file per combination, plus the directories
  195. // themselves, plus the "testdata/normalization" directory
  196. expectedNum := numValid*numValid + numValid + 1
  197. if len(files) != expectedNum {
  198. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  199. }
  200. // The file names should all be in NFC form.
  201. for _, f := range files {
  202. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  203. if !norm.NFC.IsNormalString(f.name) {
  204. t.Errorf("File name %q is not NFC normalized", f.name)
  205. }
  206. }
  207. }
  208. func TestIssue1507(t *testing.T) {
  209. w := &walker{}
  210. c := make(chan protocol.FileInfo, 100)
  211. fn := w.walkAndHashFiles(context.TODO(), c, c)
  212. fn("", nil, protocol.ErrClosed)
  213. }
  214. func TestWalkSymlinkUnix(t *testing.T) {
  215. if runtime.GOOS == "windows" {
  216. t.Skip("skipping unsupported symlink test")
  217. return
  218. }
  219. // Create a folder with a symlink in it
  220. os.RemoveAll("_symlinks")
  221. os.Mkdir("_symlinks", 0755)
  222. defer os.RemoveAll("_symlinks")
  223. os.Symlink("../testdata", "_symlinks/link")
  224. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks")
  225. for _, path := range []string{".", "link"} {
  226. // Scan it
  227. files := walkDir(fs, path, nil, nil, 0)
  228. // Verify that we got one symlink and with the correct attributes
  229. if len(files) != 1 {
  230. t.Errorf("expected 1 symlink, not %d", len(files))
  231. }
  232. if len(files[0].Blocks) != 0 {
  233. t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks))
  234. }
  235. if files[0].SymlinkTarget != "../testdata" {
  236. t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget)
  237. }
  238. }
  239. }
  240. func TestWalkSymlinkWindows(t *testing.T) {
  241. if runtime.GOOS != "windows" {
  242. t.Skip("skipping unsupported symlink test")
  243. }
  244. // Create a folder with a symlink in it
  245. name := "_symlinks-win"
  246. os.RemoveAll(name)
  247. os.Mkdir(name, 0755)
  248. defer os.RemoveAll(name)
  249. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, name)
  250. if err := osutil.DebugSymlinkForTestsOnly("../testdata", "_symlinks/link"); err != nil {
  251. // Probably we require permissions we don't have.
  252. t.Skip(err)
  253. }
  254. for _, path := range []string{".", "link"} {
  255. // Scan it
  256. files := walkDir(fs, path, nil, nil, 0)
  257. // Verify that we got zero symlinks
  258. if len(files) != 0 {
  259. t.Errorf("expected zero symlinks, not %d", len(files))
  260. }
  261. }
  262. }
  263. func TestWalkRootSymlink(t *testing.T) {
  264. // Create a folder with a symlink in it
  265. tmp, err := ioutil.TempDir("", "")
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. defer os.RemoveAll(tmp)
  270. link := tmp + "/link"
  271. dest, _ := filepath.Abs("testdata/dir1")
  272. if err := osutil.DebugSymlinkForTestsOnly(dest, link); err != nil {
  273. if runtime.GOOS == "windows" {
  274. // Probably we require permissions we don't have.
  275. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  276. } else {
  277. t.Fatal(err)
  278. }
  279. }
  280. // Scan it
  281. files := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, link), ".", nil, nil, 0)
  282. // Verify that we got two files
  283. if len(files) != 2 {
  284. t.Errorf("expected two files, not %d", len(files))
  285. }
  286. }
  287. func TestBlocksizeHysteresis(t *testing.T) {
  288. // Verify that we select the right block size in the presence of old
  289. // file information.
  290. if testing.Short() {
  291. t.Skip("long and hard test")
  292. }
  293. sf := fs.NewWalkFilesystem(&singleFileFS{
  294. name: "testfile.dat",
  295. filesize: 500 << 20, // 500 MiB
  296. })
  297. current := make(fakeCurrentFiler)
  298. runTest := func(expectedBlockSize int) {
  299. files := walkDir(sf, ".", current, nil, 0)
  300. if len(files) != 1 {
  301. t.Fatalf("expected one file, not %d", len(files))
  302. }
  303. if s := files[0].BlockSize(); s != expectedBlockSize {
  304. t.Fatalf("incorrect block size %d != expected %d", s, expectedBlockSize)
  305. }
  306. }
  307. // Scan with no previous knowledge. We should get a 512 KiB block size.
  308. runTest(512 << 10)
  309. // Scan on the assumption that previous size was 256 KiB. Retain 256 KiB
  310. // block size.
  311. current["testfile.dat"] = protocol.FileInfo{
  312. Name: "testfile.dat",
  313. Size: 500 << 20,
  314. RawBlockSize: 256 << 10,
  315. }
  316. runTest(256 << 10)
  317. // Scan on the assumption that previous size was 1 MiB. Retain 1 MiB
  318. // block size.
  319. current["testfile.dat"] = protocol.FileInfo{
  320. Name: "testfile.dat",
  321. Size: 500 << 20,
  322. RawBlockSize: 1 << 20,
  323. }
  324. runTest(1 << 20)
  325. // Scan on the assumption that previous size was 128 KiB. Move to 512
  326. // KiB because the difference is large.
  327. current["testfile.dat"] = protocol.FileInfo{
  328. Name: "testfile.dat",
  329. Size: 500 << 20,
  330. RawBlockSize: 128 << 10,
  331. }
  332. runTest(512 << 10)
  333. // Scan on the assumption that previous size was 2 MiB. Move to 512
  334. // KiB because the difference is large.
  335. current["testfile.dat"] = protocol.FileInfo{
  336. Name: "testfile.dat",
  337. Size: 500 << 20,
  338. RawBlockSize: 2 << 20,
  339. }
  340. runTest(512 << 10)
  341. }
  342. func TestWalkReceiveOnly(t *testing.T) {
  343. sf := fs.NewWalkFilesystem(&singleFileFS{
  344. name: "testfile.dat",
  345. filesize: 1024,
  346. })
  347. current := make(fakeCurrentFiler)
  348. // Initial scan, no files in the CurrentFiler. Should pick up the file and
  349. // set the ReceiveOnly flag on it, because that's the flag we give the
  350. // walker to set.
  351. files := walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  352. if len(files) != 1 {
  353. t.Fatal("Should have scanned one file")
  354. }
  355. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  356. t.Fatal("Should have set the ReceiveOnly flag")
  357. }
  358. // Update the CurrentFiler and scan again. It should not return
  359. // anything, because the file has not changed. This verifies that the
  360. // ReceiveOnly flag is properly ignored and doesn't trigger a rescan
  361. // every time.
  362. cur := files[0]
  363. current[cur.Name] = cur
  364. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  365. if len(files) != 0 {
  366. t.Fatal("Should not have scanned anything")
  367. }
  368. // Now pretend the file was previously ignored instead. We should pick up
  369. // the difference in flags and set just the LocalReceive flags.
  370. cur.LocalFlags = protocol.FlagLocalIgnored
  371. current[cur.Name] = cur
  372. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  373. if len(files) != 1 {
  374. t.Fatal("Should have scanned one file")
  375. }
  376. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  377. t.Fatal("Should have set the ReceiveOnly flag")
  378. }
  379. }
  380. func walkDir(fs fs.Filesystem, dir string, cfiler CurrentFiler, matcher *ignore.Matcher, localFlags uint32) []protocol.FileInfo {
  381. fchan := Walk(context.TODO(), Config{
  382. Filesystem: fs,
  383. Subs: []string{dir},
  384. AutoNormalize: true,
  385. Hashers: 2,
  386. UseLargeBlocks: true,
  387. CurrentFiler: cfiler,
  388. Matcher: matcher,
  389. LocalFlags: localFlags,
  390. })
  391. var tmp []protocol.FileInfo
  392. for f := range fchan {
  393. tmp = append(tmp, f)
  394. }
  395. sort.Sort(fileList(tmp))
  396. return tmp
  397. }
  398. type fileList []protocol.FileInfo
  399. func (l fileList) Len() int {
  400. return len(l)
  401. }
  402. func (l fileList) Less(a, b int) bool {
  403. return l[a].Name < l[b].Name
  404. }
  405. func (l fileList) Swap(a, b int) {
  406. l[a], l[b] = l[b], l[a]
  407. }
  408. func (l fileList) testfiles() testfileList {
  409. testfiles := make(testfileList, len(l))
  410. for i, f := range l {
  411. if len(f.Blocks) > 1 {
  412. panic("simple test case stuff only supports a single block per file")
  413. }
  414. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  415. if len(f.Blocks) == 1 {
  416. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  417. }
  418. }
  419. return testfiles
  420. }
  421. func (l testfileList) String() string {
  422. var b bytes.Buffer
  423. b.WriteString("{\n")
  424. for _, f := range l {
  425. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  426. }
  427. b.WriteString("}")
  428. return b.String()
  429. }
  430. var initOnce sync.Once
  431. const (
  432. testdataSize = 17 << 20
  433. testdataName = "_random.data"
  434. )
  435. func BenchmarkHashFile(b *testing.B) {
  436. initOnce.Do(initTestFile)
  437. b.ResetTimer()
  438. for i := 0; i < b.N; i++ {
  439. if _, err := HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, ""), testdataName, protocol.MinBlockSize, nil, true); err != nil {
  440. b.Fatal(err)
  441. }
  442. }
  443. b.SetBytes(testdataSize)
  444. b.ReportAllocs()
  445. }
  446. func initTestFile() {
  447. fd, err := os.Create(testdataName)
  448. if err != nil {
  449. panic(err)
  450. }
  451. lr := io.LimitReader(rand.Reader, testdataSize)
  452. if _, err := io.Copy(fd, lr); err != nil {
  453. panic(err)
  454. }
  455. if err := fd.Close(); err != nil {
  456. panic(err)
  457. }
  458. }
  459. func TestStopWalk(t *testing.T) {
  460. // Create tree that is 100 levels deep, with each level containing 100
  461. // files (each 1 MB) and 100 directories (in turn containing 100 files
  462. // and 100 directories, etc). That is, in total > 100^100 files and as
  463. // many directories. It'll take a while to scan, giving us time to
  464. // cancel it and make sure the scan stops.
  465. // Use an errorFs as the backing fs for the rest of the interface
  466. // The way we get it is a bit hacky tho.
  467. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  468. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  469. const numHashers = 4
  470. ctx, cancel := context.WithCancel(context.Background())
  471. fchan := Walk(ctx, Config{
  472. Filesystem: fs,
  473. Hashers: numHashers,
  474. ProgressTickIntervalS: -1, // Don't attempt to build the full list of files before starting to scan...
  475. })
  476. // Receive a few entries to make sure the walker is up and running,
  477. // scanning both files and dirs. Do some quick sanity tests on the
  478. // returned file entries to make sure we are not just reading crap from
  479. // a closed channel or something.
  480. dirs := 0
  481. files := 0
  482. for {
  483. f := <-fchan
  484. t.Log("Scanned", f)
  485. if f.IsDirectory() {
  486. if len(f.Name) == 0 || f.Permissions == 0 {
  487. t.Error("Bad directory entry", f)
  488. }
  489. dirs++
  490. } else {
  491. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  492. t.Error("Bad file entry", f)
  493. }
  494. files++
  495. }
  496. if dirs > 5 && files > 5 {
  497. break
  498. }
  499. }
  500. // Cancel the walker.
  501. cancel()
  502. // Empty out any waiting entries and wait for the channel to close.
  503. // Count them, they should be zero or very few - essentially, each
  504. // hasher has the choice of returning a fully handled entry or
  505. // cancelling, but they should not start on another item.
  506. extra := 0
  507. for range fchan {
  508. extra++
  509. }
  510. t.Log("Extra entries:", extra)
  511. if extra > numHashers {
  512. t.Error("unexpected extra entries received after cancel")
  513. }
  514. }
  515. func TestIssue4799(t *testing.T) {
  516. tmp, err := ioutil.TempDir("", "")
  517. if err != nil {
  518. t.Fatal(err)
  519. }
  520. defer os.RemoveAll(tmp)
  521. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  522. fd, err := fs.Create("foo")
  523. if err != nil {
  524. t.Fatal(err)
  525. }
  526. fd.Close()
  527. files := walkDir(fs, "/foo", nil, nil, 0)
  528. if len(files) != 1 || files[0].Name != "foo" {
  529. t.Error(`Received unexpected file infos when walking "/foo"`, files)
  530. }
  531. }
  532. func TestRecurseInclude(t *testing.T) {
  533. stignore := `
  534. !/dir1/cfile
  535. !efile
  536. !ffile
  537. *
  538. `
  539. ignores := ignore.New(testFs, ignore.WithCache(true))
  540. if err := ignores.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  541. t.Fatal(err)
  542. }
  543. files := walkDir(testFs, ".", nil, ignores, 0)
  544. expected := []string{
  545. filepath.Join("dir1"),
  546. filepath.Join("dir1", "cfile"),
  547. filepath.Join("dir2"),
  548. filepath.Join("dir2", "dir21"),
  549. filepath.Join("dir2", "dir21", "dir22"),
  550. filepath.Join("dir2", "dir21", "dir22", "dir23"),
  551. filepath.Join("dir2", "dir21", "dir22", "dir23", "efile"),
  552. filepath.Join("dir2", "dir21", "dir22", "efile"),
  553. filepath.Join("dir2", "dir21", "dir22", "efile", "efile"),
  554. filepath.Join("dir2", "dir21", "dira"),
  555. filepath.Join("dir2", "dir21", "dira", "efile"),
  556. filepath.Join("dir2", "dir21", "dira", "ffile"),
  557. filepath.Join("dir2", "dir21", "efile"),
  558. filepath.Join("dir2", "dir21", "efile", "ign"),
  559. filepath.Join("dir2", "dir21", "efile", "ign", "efile"),
  560. }
  561. if len(files) != len(expected) {
  562. t.Fatalf("Got %d files %v, expected %d files at %v", len(files), files, len(expected), expected)
  563. }
  564. for i := range files {
  565. if files[i].Name != expected[i] {
  566. t.Errorf("Got %v, expected file at %v", files[i], expected[i])
  567. }
  568. }
  569. }
  570. func TestIssue4841(t *testing.T) {
  571. tmp, err := ioutil.TempDir("", "")
  572. if err != nil {
  573. t.Fatal(err)
  574. }
  575. defer os.RemoveAll(tmp)
  576. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  577. fd, err := fs.Create("foo")
  578. if err != nil {
  579. panic(err)
  580. }
  581. fd.Close()
  582. fchan := Walk(context.TODO(), Config{
  583. Filesystem: fs,
  584. Subs: nil,
  585. AutoNormalize: true,
  586. Hashers: 2,
  587. CurrentFiler: fakeCurrentFiler{
  588. "foo": {
  589. Name: "foo",
  590. Type: protocol.FileInfoTypeFile,
  591. LocalFlags: protocol.FlagLocalIgnored,
  592. Version: protocol.Vector{}.Update(1),
  593. },
  594. },
  595. ShortID: protocol.LocalDeviceID.Short(),
  596. })
  597. var files []protocol.FileInfo
  598. for f := range fchan {
  599. files = append(files, f)
  600. }
  601. sort.Sort(fileList(files))
  602. if len(files) != 1 {
  603. t.Fatalf("Expected 1 file, got %d: %v", len(files), files)
  604. }
  605. if expected := (protocol.Vector{}.Update(protocol.LocalDeviceID.Short())); !files[0].Version.Equal(expected) {
  606. t.Fatalf("Expected Version == %v, got %v", expected, files[0].Version)
  607. }
  608. }
  609. // Verify returns nil or an error describing the mismatch between the block
  610. // list and actual reader contents
  611. func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
  612. hf := sha256.New()
  613. // A 32k buffer is used for copying into the hash function.
  614. buf := make([]byte, 32<<10)
  615. for i, block := range blocks {
  616. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  617. _, err := io.CopyBuffer(hf, lr, buf)
  618. if err != nil {
  619. return err
  620. }
  621. hash := hf.Sum(nil)
  622. hf.Reset()
  623. if !bytes.Equal(hash, block.Hash) {
  624. return fmt.Errorf("hash mismatch %x != %x for block %d", hash, block.Hash, i)
  625. }
  626. }
  627. // We should have reached the end now
  628. bs := make([]byte, 1)
  629. n, err := r.Read(bs)
  630. if n != 0 || err != io.EOF {
  631. return fmt.Errorf("file continues past end of blocks")
  632. }
  633. return nil
  634. }
  635. type fakeCurrentFiler map[string]protocol.FileInfo
  636. func (fcf fakeCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  637. f, ok := fcf[name]
  638. return f, ok
  639. }