safesight/agent/internal/assets/assets.go
2026-01-17 16:57:51 +08:00

57 lines
998 B
Go

package assets
import (
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"os"
"path/filepath"
)
type FileInfo struct {
Path string `json:"path"`
Sha256 string `json:"sha256"`
Size int64 `json:"size"`
MtimeMS int64 `json:"mtime_ms"`
}
func Info(path string) (FileInfo, error) {
if path == "" {
return FileInfo{}, errors.New("path is empty")
}
st, err := os.Stat(path)
if err != nil {
return FileInfo{}, err
}
if st.IsDir() {
return FileInfo{}, errors.New("path is a directory")
}
f, err := os.Open(path)
if err != nil {
return FileInfo{}, err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return FileInfo{}, err
}
sha := hex.EncodeToString(h.Sum(nil))
return FileInfo{
Path: filepath.ToSlash(path),
Sha256: sha,
Size: st.Size(),
MtimeMS: st.ModTime().UnixMilli(),
}, nil
}
func ExecutableInfo() (FileInfo, error) {
p, err := os.Executable()
if err != nil {
return FileInfo{}, err
}
return Info(p)
}