MCPcopy Create free account
hub / github.com/ddev/ddev / FileHash

Function FileHash

pkg/fileutil/file_hash.go:15–56  ·  view source on GitHub ↗

FileHash returns string of hash of filePath passed in And optional string can be added to content that will be hashed

(filePath string, optionalExtraString string)

Source from the content-addressed store, hash-verified

13// FileHash returns string of hash of filePath passed in
14// And optional string can be added to content that will be hashed
15func FileHash(filePath string, optionalExtraString string) (string, error) {
16 file, err := os.Open(filePath)
17 if err != nil {
18 return "", err
19 }
20 defer func() {
21 err = file.Close()
22 if err != nil {
23 util.Warning("unable to close file: %v", err)
24 }
25 }()
26
27 hash := sha1.New()
28 if _, err := io.Copy(hash, file); err != nil {
29 return "", err
30 }
31 // Include file location in the hash, if in a different
32 // place it should not hash the same
33 // file.Name() is the full path of the file
34
35 canonicalFileName := file.Name()
36
37 // Use a canonical filename in unix-style format so that we don't
38 // get caught by differences in filename format on Windows.
39 if nodeps.IsWindows() {
40 canonicalFileName = util.WindowsPathToCygwinPath(canonicalFileName)
41 }
42 if _, err := hash.Write([]byte(canonicalFileName)); err != nil {
43 return "", err
44 }
45
46 // Add optional string to hash if provided
47 if len(optionalExtraString) > 0 {
48 if _, err := hash.Write([]byte(optionalExtraString)); err != nil {
49 return "", err
50 }
51 }
52
53 sum := hash.Sum(nil)
54
55 return fmt.Sprintf("%x", sum), nil
56}

Callers 2

GetMutagenConfigFileHashFunction · 0.92
TestFileHashFunction · 0.92

Calls 4

WarningFunction · 0.92
IsWindowsFunction · 0.92
WindowsPathToCygwinPathFunction · 0.92
WriteMethod · 0.65

Tested by 1

TestFileHashFunction · 0.74