JOJ3/pkg/healthcheck/verify.go
周赵嘉程521432910016 5a860f1203 feat: repo health check (#16) (#17)
- repo size
- forbidden files
- meta files
- ascii character in files
- integrity check
- ascii character in the commit message
- release tag check

Co-authored-by: Boming Zhang <bomingzh@sjtu.edu.cn>
Co-authored-by: zzjc1234 <2359047351@qq.com>
Co-authored-by: Hydraallen <wangruiallen@gmail.com>
Reviewed-on: FOCS-dev/JOJ3#17
Co-authored-by: 周赵嘉程521432910016 <zzjc123@sjtu.edu.cn>
Co-committed-by: 周赵嘉程521432910016 <zzjc123@sjtu.edu.cn>
2024-09-11 20:09:27 +08:00

60 lines
1.6 KiB
Go

package healthcheck
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// getChecksum calculates the SHA-256 checksum of a file
func getChecksum(filePath string) (string, error) {
// Open the file
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
// Calculate SHA-256
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
// checkFileChecksum checks if a single file's checksum matches the expected value
func checkFileChecksum(rootDir, fileName, expectedChecksum string) error {
filePath := filepath.Join(rootDir, strings.TrimSpace(fileName))
actualChecksum, err := getChecksum(filePath)
if err != nil {
return fmt.Errorf("Error reading file %s: %v", filePath, err)
}
if actualChecksum != expectedChecksum {
return fmt.Errorf("Checksum for %s failed. Expected %s, but got %s. Please revert your changes or contact the teaching team if you have a valid reason for adjusting them.", filePath, expectedChecksum, actualChecksum)
}
return nil
}
func VerifyFiles(rootDir string, checkFileNameList string, checkFileSumList string) error {
if len(checkFileNameList) == 0 {
return nil
}
fileNames := strings.Split(checkFileNameList, ",")
checkSums := strings.Split(checkFileSumList, ",")
// Check each file's checksum
for i, fileName := range fileNames {
expectedChecksum := strings.TrimSpace(checkSums[i])
err := checkFileChecksum(rootDir, fileName, expectedChecksum)
if err != nil {
return err
}
}
return nil
}