Browse Source

adding GetHash to lib

Wilfried Klaas 2 years ago
parent
commit
c951c94597
2 changed files with 27 additions and 18 deletions
  1. 3 0
      gohash.code-workspace
  2. 24 18
      pkg/hash/hash.go

+ 3 - 0
gohash.code-workspace

@@ -5,6 +5,9 @@
 		},
 		{
 			"path": "..\\VideoCat"
+		},
+		{
+			"path": "..\\go-micro"
 		}
 	],
 	"settings": {}

+ 24 - 18
pkg/hash/hash.go

@@ -11,6 +11,8 @@ import (
 
 const FDHASHFILENAME = ".fdhashes3"
 
+var dirHashes map[string]Fdhashes
+
 // Fdhashes struct for holding all informations about one folder.
 type Fdhashes struct {
 	Path   string
@@ -19,6 +21,10 @@ type Fdhashes struct {
 	Dirty  bool
 }
 
+func init() {
+	dirHashes = make(map[string]Fdhashes)
+}
+
 func LoadHashfile(fileStr string) (*Fdhashes, error) {
 	fileInfo, err := os.Stat(fileStr)
 	if err != nil {
@@ -49,25 +55,25 @@ func LoadHashfile(fileStr string) (*Fdhashes, error) {
 	return &data, nil
 }
 
-/*
-func LoadHashfile(fileStr string) Fdhashes {
-	dir, _ := filepath.Split(fileStr)
-	dir = filepath.ToSlash(filepath.Clean(dir))
-	data := Fdhashes{Path: dir, Hashes: make(map[string]string), Times: make(map[string]time.Time), Dirty: false}
-	if !rewrite {
-		file, err := ioutil.ReadFile(fileStr)
-		if err != nil {
-			panic(err)
-		}
-		err = json.Unmarshal([]byte(file), &data)
+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 {
-			log.Printf("can't read file %s", fileStr)
+			return "", err
 		}
+		dirHashes[path] = *fh
+		fdHashes = *fh
 	}
-	if data.Path != dir {
-		data.Path = dir
-		data.Dirty = true
-	}
-	return data
+
+	hash, _ := fdHashes.Hashes[name]
+	return hash, nil
 }
-*/