hash.go 1.5 KB

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