-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathhash.go
More file actions
56 lines (48 loc) · 1.55 KB
/
Copy pathhash.go
File metadata and controls
56 lines (48 loc) · 1.55 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
package helpers
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
)
// CalculateSHA256 computes the SHA256 checksum of the file specified by filePath.
// If the file does not exist, it returns an empty string without an error.
// For other errors (e.g., permission issues), it returns the error.
func CalculateSHA256(filePath string) (string, error) {
fileInfo, err := os.Lstat(filePath)
if err != nil {
if os.IsNotExist(err) {
// File does not exist; return empty checksum
return "", nil
}
// An unexpected error occurred; return it
return "", fmt.Errorf("failed to stat file '%s': %w", filePath, err)
}
// Check if the file is a symbolic link
if !fileInfo.Mode().IsRegular() {
return "", fmt.Errorf("symbolic links are not allowed '%s'", filePath)
}
// Attempt to open the file directly
file, err := os.Open(filePath)
if err != nil {
if os.IsNotExist(err) {
// File does not exist; return empty checksum
return "", nil
}
// An unexpected error occurred; return it
return "", fmt.Errorf("failed to open file '%s': %w", filePath, err)
}
// Ensure the file is closed when the function exits
defer file.Close()
// Create a new SHA256 hash instance
hash := sha256.New()
// Copy the file content into the hash
if _, err := io.Copy(hash, file); err != nil {
return "", fmt.Errorf("failed to read file '%s': %w", filePath, err)
}
// Compute the final hash value and encode it as a hexadecimal string
return hex.EncodeToString(hash.Sum(nil)), nil
}