-
Notifications
You must be signed in to change notification settings - Fork 8
/
filehash.go
70 lines (60 loc) · 1.77 KB
/
filehash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Copyright (C) 2020-2022 Arm Limited or its affiliates and Contributors. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package filesystem
import (
"context"
"fmt"
"github.com/ARM-software/golang-utils/utils/commonerrors"
"github.com/ARM-software/golang-utils/utils/hashing"
)
type fileHashing struct {
algo hashing.IHash
}
func (h *fileHashing) CalculateWithContext(ctx context.Context, f File) (string, error) {
if f == nil {
return "", commonerrors.ErrUndefined
}
return h.algo.CalculateWithContext(ctx, f)
}
func (h *fileHashing) Calculate(f File) (string, error) {
if f == nil {
return "", commonerrors.ErrUndefined
}
return h.algo.Calculate(f)
}
func (h *fileHashing) GetType() string {
return h.algo.GetType()
}
func (h *fileHashing) CalculateFileWithContext(ctx context.Context, fs FS, path string) (string, error) {
return h.calculateFile(fs, path, func(m *fileHashing, f File) (string, error) { return m.CalculateWithContext(ctx, f) })
}
func (h *fileHashing) CalculateFile(fs FS, path string) (string, error) {
return h.calculateFile(fs, path, func(m *fileHashing, f File) (string, error) { return m.Calculate(f) })
}
func (h *fileHashing) calculateFile(fs FS, path string, hashFunc func(h *fileHashing, f File) (string, error)) (string, error) {
ok, err := fs.IsFile(path)
if err != nil || !ok {
if err != nil {
return "", err
}
err = fmt.Errorf("not a file [%v]: %w", path, commonerrors.ErrInvalid)
return "", err
}
f, err := fs.GenericOpen(path)
if err != nil {
return "", err
}
defer func() { _ = f.Close() }()
return hashFunc(h, f)
}
func NewFileHash(hashType string) (IFileHash, error) {
algo, err := hashing.NewHashingAlgorithm(hashType)
if err != nil {
return nil, err
}
return &fileHashing{
algo: algo,
}, nil
}