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