Some checks failed
Docs Deploy / build_and_deploy (push) Has been cancelled
Generate Docs / cli (push) Has been cancelled
Generate Config Doc / cli (push) Has been cancelled
Go formatting / go-formatting (push) Has been cancelled
Check links / markdown-link-check (push) Has been cancelled
Integration / pre-test (push) Has been cancelled
Integration / test on (push) Has been cancelled
Integration / status (push) Has been cancelled
Lint / Lint Go code (push) Has been cancelled
Test / test (ubuntu-latest) (push) Has been cancelled
76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
package checksum
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"git.cw.tr/mukan-network/mukan-ignite/ignite/pkg/xexec"
|
|
)
|
|
|
|
// Sum reads files from dirPath, calculates sha256 for each file and creates a new checksum
|
|
// file for them in outPath.
|
|
func Sum(dirPath, outPath string) error {
|
|
var b bytes.Buffer
|
|
|
|
files, err := os.ReadDir(dirPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, info := range files {
|
|
path := filepath.Join(dirPath, info.Name())
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
h := sha256.New()
|
|
if _, err := io.Copy(h, f); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Note that checksum entry has two spaces as separator to follow
|
|
// FIPS-180-2 regarding the character prefix for text file types.
|
|
// This is required for tools like sha256sum with a strict verification.
|
|
if _, err := b.WriteString(fmt.Sprintf("%x %s\n", h.Sum(nil), info.Name())); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return os.WriteFile(outPath, b.Bytes(), 0o600)
|
|
}
|
|
|
|
// Binary returns SHA256 hash of executable file, file is searched by name in PATH.
|
|
func Binary(binaryName string) (string, error) {
|
|
// get binary path
|
|
binaryPath, err := xexec.ResolveAbsPath(binaryName)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
f, err := os.Open(binaryPath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer f.Close()
|
|
|
|
h := sha256.New()
|
|
if _, err := io.Copy(h, f); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return fmt.Sprintf("%x", h.Sum(nil)), nil
|
|
}
|
|
|
|
// Strings concatenates all inputs and returns SHA256 hash of them.
|
|
func Strings(inputs ...string) string {
|
|
h := sha256.New()
|
|
for _, input := range inputs {
|
|
h.Write([]byte(input))
|
|
}
|
|
return fmt.Sprintf("%x", h.Sum(nil))
|
|
}
|