12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package hash
- import (
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "io"
- "io/ioutil"
- "log"
- "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
- }
- func GetFileHash(fileStr string) string {
- f, err := os.Open(fileStr)
- if err != nil {
- log.Fatal(err)
- }
- defer f.Close()
- h := sha256.New()
- if _, err := io.Copy(h, f); err != nil {
- log.Fatal(err)
- }
- return hex.EncodeToString(h.Sum(nil))
- }
|