hash.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package hash
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "encoding/json"
  6. "io"
  7. "io/ioutil"
  8. "log"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. )
  14. const FDHASHFILENAME = ".fdhashes3"
  15. var dirHashes map[string]Fdhashes
  16. // Fdhashes struct for holding all informations about one folder.
  17. type Fdhashes struct {
  18. Path string
  19. Hashes map[string]string
  20. Times map[string]time.Time
  21. Dirty bool
  22. }
  23. func init() {
  24. dirHashes = make(map[string]Fdhashes)
  25. }
  26. func LoadHashfile(fileStr string) (*Fdhashes, error) {
  27. fileInfo, err := os.Stat(fileStr)
  28. if err != nil {
  29. return nil, err
  30. }
  31. if fileInfo.IsDir() {
  32. fileStr = filepath.Join(fileStr, FDHASHFILENAME)
  33. }
  34. dir, name := filepath.Split(fileStr)
  35. if strings.ToLower(name) != FDHASHFILENAME {
  36. fileStr = filepath.Join(dir, FDHASHFILENAME)
  37. }
  38. dir = filepath.ToSlash(filepath.Clean(dir))
  39. var data Fdhashes
  40. file, err := ioutil.ReadFile(fileStr)
  41. if err != nil {
  42. return nil, err
  43. }
  44. err = json.Unmarshal([]byte(file), &data)
  45. if err != nil {
  46. return nil, err
  47. }
  48. if data.Path != dir {
  49. data.Path = dir
  50. data.Dirty = true
  51. }
  52. return &data, nil
  53. }
  54. func GetHash(path string, name string) (string, error) {
  55. fileInfo, err := os.Stat(path)
  56. if err != nil {
  57. return "", err
  58. }
  59. if !fileInfo.IsDir() {
  60. path, _ = filepath.Split(path)
  61. }
  62. path = filepath.Clean(path)
  63. fdHashes, ok := dirHashes[path]
  64. if !ok {
  65. fh, err := LoadHashfile(path)
  66. if err != nil {
  67. return "", err
  68. }
  69. dirHashes[path] = *fh
  70. fdHashes = *fh
  71. }
  72. hash := fdHashes.Hashes[name]
  73. return hash, nil
  74. }
  75. func GetFileHash(fileStr string) string {
  76. f, err := os.Open(fileStr)
  77. if err != nil {
  78. log.Fatal(err)
  79. }
  80. defer f.Close()
  81. h := sha256.New()
  82. if _, err := io.Copy(h, f); err != nil {
  83. log.Fatal(err)
  84. }
  85. return hex.EncodeToString(h.Sum(nil))
  86. }