12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package hash
- import (
- "encoding/json"
- "io/ioutil"
- "os"
- "path/filepath"
- "strings"
- "time"
- )
- const FDHASHFILENAME = ".fdhashes3"
- var dirHashes map[string]Fdhashes
- // Fdhashes struct for holding all informations about one folder.
- type Fdhashes struct {
- Path string
- Hashes map[string]string
- Times map[string]time.Time
- Dirty bool
- }
- func init() {
- dirHashes = make(map[string]Fdhashes)
- }
- func LoadHashfile(fileStr string) (*Fdhashes, error) {
- fileInfo, err := os.Stat(fileStr)
- if err != nil {
- return nil, err
- }
- if fileInfo.IsDir() {
- fileStr = filepath.Join(fileStr, FDHASHFILENAME)
- }
- dir, name := filepath.Split(fileStr)
- if strings.ToLower(name) != FDHASHFILENAME {
- fileStr = filepath.Join(dir, FDHASHFILENAME)
- }
- dir = filepath.ToSlash(filepath.Clean(dir))
- var data Fdhashes
- file, err := ioutil.ReadFile(fileStr)
- if err != nil {
- return nil, err
- }
- err = json.Unmarshal([]byte(file), &data)
- if err != nil {
- return nil, err
- }
- if data.Path != dir {
- data.Path = dir
- data.Dirty = true
- }
- return &data, nil
- }
- func GetHash(path string, name string) (string, error) {
- fileInfo, err := os.Stat(path)
- if err != nil {
- return "", err
- }
- if !fileInfo.IsDir() {
- path, _ = filepath.Split(path)
- }
- path = filepath.Clean(path)
- fdHashes, ok := dirHashes[path]
- if !ok {
- fh, err := LoadHashfile(path)
- if err != nil {
- return "", err
- }
- dirHashes[path] = *fh
- fdHashes = *fh
- }
- hash, _ := fdHashes.Hashes[name]
- return hash, nil
- }
|