main.go 1.8 KB

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