refactor: simplify codebase (-209 lines)
This commit is contained in:
@@ -2,6 +2,7 @@ package fileutil
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -18,13 +19,11 @@ func EnsureDir(path string) error {
|
||||
if !info.IsDir() {
|
||||
return fmt.Errorf("file already exists at %s", path)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func FileExists(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
@@ -32,7 +31,6 @@ func DeleteFile(path string) error {
|
||||
if !FileExists(path) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
@@ -43,10 +41,10 @@ func GetFileHash(path string) (string, error) {
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%x", hash.Sum(nil)), nil
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
@@ -16,12 +17,11 @@ type HashIndex struct {
|
||||
func NewHashIndex(ctx context.Context, root string) (*HashIndex, error) {
|
||||
index := &HashIndex{files: make(map[string]string)}
|
||||
|
||||
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if err != nil || info.IsDir() {
|
||||
if err != nil || d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -36,12 +36,9 @@ func NewHashIndex(ctx context.Context, root string) (*HashIndex, error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
sum := hex.EncodeToString(h.Sum(nil))
|
||||
index.files[sum] = path
|
||||
|
||||
index.files[hex.EncodeToString(h.Sum(nil))] = path
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -51,6 +48,5 @@ func NewHashIndex(ctx context.Context, root string) (*HashIndex, error) {
|
||||
|
||||
func (h *HashIndex) Find(hash string) (string, bool) {
|
||||
path, ok := h.files[hash]
|
||||
|
||||
return path, ok
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user