main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright (C) 2015 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 main
  7. import (
  8. "flag"
  9. "fmt"
  10. "io"
  11. "os"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/sha256"
  14. )
  15. func main() {
  16. period := flag.Duration("period", 200*time.Millisecond, "Sleep period between checks")
  17. flag.Parse()
  18. file := flag.Arg(0)
  19. if file == "" {
  20. fmt.Println("Expects a path as an argument")
  21. return
  22. }
  23. exists := true
  24. size := int64(0)
  25. mtime := time.Time{}
  26. var hash [sha256.Size]byte
  27. for {
  28. time.Sleep(*period)
  29. newExists := true
  30. fi, err := os.Stat(file)
  31. if err != nil && os.IsNotExist(err) {
  32. newExists = false
  33. } else if err != nil {
  34. fmt.Println("stat:", err)
  35. return
  36. }
  37. if newExists != exists {
  38. exists = newExists
  39. if !newExists {
  40. fmt.Println(file, "does not exist")
  41. } else {
  42. fmt.Println(file, "appeared")
  43. }
  44. }
  45. if !exists {
  46. size = 0
  47. mtime = time.Time{}
  48. hash = [sha256.Size]byte{}
  49. continue
  50. }
  51. if fi.IsDir() {
  52. fmt.Println(file, "is directory")
  53. return
  54. }
  55. newSize := fi.Size()
  56. newMtime := fi.ModTime()
  57. newHash, err := sha256file(file)
  58. if err != nil {
  59. fmt.Println("sha256file:", err)
  60. }
  61. if newSize != size || newMtime != mtime || newHash != hash {
  62. fmt.Println(file, "Size:", newSize, "Mtime:", newMtime, "Hash:", fmt.Sprintf("%x", newHash))
  63. hash = newHash
  64. size = newSize
  65. mtime = newMtime
  66. }
  67. }
  68. }
  69. func sha256file(fname string) (hash [sha256.Size]byte, err error) {
  70. f, err := os.Open(fname)
  71. if err != nil {
  72. return
  73. }
  74. defer f.Close()
  75. h := sha256.New()
  76. io.Copy(h, f)
  77. hb := h.Sum(nil)
  78. copy(hash[:], hb)
  79. return
  80. }