From c7e47d3a2dff5ac3d7a70b4cb7d4f6fc005344fa Mon Sep 17 00:00:00 2001 From: kajvans <54155240+kajvans@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:31:50 +0200 Subject: [PATCH 1/2] Add --fast mode, shell completions, man page and a GitHub Action (0.2.0) --- .github/workflows/ci.yml | 38 ++++- CHANGELOG.md | 7 + README.md | 33 +++++ action.yml | 109 ++++++++++++++ internal/check/check.go | 56 ++++++- internal/cli/cli.go | 16 +- internal/cli/cli_test.go | 88 +++++++++++ internal/cli/complete.go | 294 +++++++++++++++++++++++++++++++++++++ internal/report/report.go | 3 + internal/scan/cache.go | 90 ++++++++++++ internal/scan/scan.go | 49 +++++-- internal/scan/scan_test.go | 70 +++++++++ scripts/dist.sh | 13 ++ 13 files changed, 849 insertions(+), 17 deletions(-) create mode 100644 action.yml create mode 100644 internal/cli/complete.go create mode 100644 internal/scan/cache.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9eafda..32925b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,10 +144,46 @@ jobs: "$h" seal sample --key k.key -q "$h" check sample --pubkey k.pub --require-signature + action: + name: the GitHub Action (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - name: A folder to protect + shell: bash + run: mkdir demo && echo hello > demo/a.txt + - uses: ./ + with: + command: seal + path: demo + - uses: ./ + with: + command: check + path: demo + - name: Tamper with the folder + shell: bash + run: echo evil >> demo/a.txt + - uses: ./ + id: tampered + continue-on-error: true + with: + command: check + path: demo + - name: The check must have failed + shell: bash + env: + OUTCOME: ${{ steps.tampered.outcome }} + run: test "$OUTCOME" = failure + # Required status check: one name to protect in the branch rules. ci-ok: if: always() - needs: [test, lint, vulncheck, cross-build, dogfood] + needs: [test, lint, vulncheck, cross-build, dogfood, action] runs-on: ubuntu-latest steps: - name: All jobs must have succeeded diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b39c3..0412e2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ Format: [Keep a Changelog](https://keepachangelog.com/). Versions: [Semantic Ver ## [Unreleased] +## [0.2.0] - 2026-10-16 + +### Added +- `--fast` for `seal` and `check`: reuse hashes of files whose size and modification time are unchanged (with `--cache-file`). The report says how many hashes were reused. +- `assay completion bash|zsh|fish|powershell` and `assay man`; the `.deb` installs both. +- A GitHub Action (`uses: SandSoftwareSolutions/assay@v0.2.0`) that downloads a release, verifies its checksum and runs `seal` or `check`. + ## [0.1.1] - 2026-10-16 ### Fixed diff --git a/README.md b/README.md index 7ceaafc..0555550 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,39 @@ In scripts: assay check /srv/site -q || { echo "site changed!" | mail -s alert ops@example.com; } ``` +### Big folders: `--fast` + +`assay check --fast` reuses the hash of every file whose size and modification time have not changed +since the previous run, so a large, mostly unchanged folder is checked in a fraction of the time. +The cache is kept in your user cache directory (override with `--cache-file`). The trade-off: a file +changed *without* touching its modification time is not noticed in fast mode. Use plain `assay check` +when you need certainty; files modified within the last two seconds are always rehashed. The report +says how many hashes were reused. + +### Shell completion and manual page + +```console +$ assay completion bash > /etc/bash_completion.d/assay # also zsh, fish, powershell +$ assay man | gzip > /usr/local/share/man/man1/assay.1.gz +``` + +The `.deb` package installs both for you. + +### In GitHub Actions + +```yaml +- uses: SandSoftwareSolutions/assay@v0.2.0 + with: + command: check + path: dist + pubkey: release.pub + require-signature: "true" +``` + +The action downloads the release archive, verifies it against `SHA256SUMS` and runs `assay`. +Inputs: `command` (`seal` or `check`), `path`, `manifest`, `pubkey`, `require-signature`, `version` +(default `latest`; pin one for reproducible builds) and `args` (extra flags, space separated). + ## Sign it, so the manifest cannot be swapped A hash tells you the files differ from the manifest. It cannot tell you the manifest is genuine: diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..a20158e --- /dev/null +++ b/action.yml @@ -0,0 +1,109 @@ +name: "assay" +description: "Seal a folder, or check that it still matches its seal, with assay (https://github.com/SandSoftwareSolutions/assay)" +author: "Sand Software Solutions" +branding: + icon: "shield" + color: "blue" + +inputs: + command: + description: "seal or check" + default: "check" + path: + description: "The folder to seal or check" + default: "." + manifest: + description: "Manifest file (default: /.assay.json)" + default: "" + pubkey: + description: "Public key file: verify the signature of the manifest (check only)" + default: "" + require-signature: + description: "Fail when the manifest is not signed and verified (check only): true or false" + default: "false" + version: + description: "assay version to use, such as 0.2.0, or latest" + default: "latest" + args: + description: "Extra flags, separated by spaces (no quoting), for example: --exclude node_modules --fast" + default: "" + +outputs: + version: + description: "The assay version that was used" + value: ${{ steps.install.outputs.version }} + +runs: + using: composite + steps: + - id: install + shell: bash + env: + ASSAY_VERSION: ${{ inputs.version }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + case "$RUNNER_OS" in + Linux) os=linux; ext=tar.gz ;; + macOS) os=darwin; ext=tar.gz ;; + Windows) os=windows; ext=zip ;; + *) echo "unsupported runner: $RUNNER_OS" >&2; exit 1 ;; + esac + case "$RUNNER_ARCH" in + X64) arch=amd64 ;; + ARM64) arch=arm64 ;; + *) echo "unsupported architecture: $RUNNER_ARCH" >&2; exit 1 ;; + esac + repo="SandSoftwareSolutions/assay" + version="$ASSAY_VERSION" + if [ "$version" = latest ]; then + version="$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" "https://api.github.com/repos/$repo/releases/latest" \ + | sed -n 's/.*"tag_name": *"v\{0,1\}\([^"]*\)".*/\1/p' | head -n 1)" + fi + version="${version#v}" + if ! printf '%s' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$'; then + echo "not a version number: '$version'" >&2; exit 1 + fi + base="https://github.com/$repo/releases/download/v$version" + archive="assay_${version}_${os}_${arch}.${ext}" + dir="$RUNNER_TEMP/assay-$version" + mkdir -p "$dir" + curl -fsSL -o "$dir/$archive" "$base/$archive" + curl -fsSL -o "$dir/SHA256SUMS" "$base/SHA256SUMS" + expected="$(awk -v f="$archive" '$2 == f {print $1}' "$dir/SHA256SUMS")" + [ -n "$expected" ] || { echo "no checksum listed for $archive" >&2; exit 1; } + if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$dir/$archive" | awk '{print $1}')" + else actual="$(shasum -a 256 "$dir/$archive" | awk '{print $1}')"; fi + if [ "$expected" != "$actual" ]; then echo "checksum mismatch for $archive; refusing to use it" >&2; exit 1; fi + if [ "$ext" = zip ]; then unzip -q -o "$dir/$archive" -d "$dir"; else tar -xzf "$dir/$archive" -C "$dir"; fi + bin="$dir/assay_${version}_${os}_${arch}" + if command -v cygpath >/dev/null 2>&1; then bin="$(cygpath -w "$bin")"; fi + echo "$bin" >> "$GITHUB_PATH" + echo "version=$version" >> "$GITHUB_OUTPUT" + + - id: run + shell: bash + env: + INPUT_COMMAND: ${{ inputs.command }} + INPUT_PATH: ${{ inputs.path }} + INPUT_MANIFEST: ${{ inputs.manifest }} + INPUT_PUBKEY: ${{ inputs.pubkey }} + INPUT_REQUIRE_SIGNATURE: ${{ inputs.require-signature }} + INPUT_ARGS: ${{ inputs.args }} + run: | + set -euo pipefail + case "$INPUT_COMMAND" in + seal|check) ;; + *) echo "command must be seal or check, not '$INPUT_COMMAND'" >&2; exit 2 ;; + esac + args=("$INPUT_COMMAND" "$INPUT_PATH") + if [ -n "$INPUT_MANIFEST" ]; then args+=(-m "$INPUT_MANIFEST"); fi + if [ "$INPUT_COMMAND" = check ]; then + if [ -n "$INPUT_PUBKEY" ]; then args+=(--pubkey "$INPUT_PUBKEY"); fi + if [ "$INPUT_REQUIRE_SIGNATURE" = true ]; then args+=(--require-signature); fi + fi + if [ -n "$INPUT_ARGS" ]; then + read -r -a extra <<< "$INPUT_ARGS" + args+=("${extra[@]}") + fi + assay "${args[@]}" diff --git a/internal/check/check.go b/internal/check/check.go index b875a1c..b34192f 100644 --- a/internal/check/check.go +++ b/internal/check/check.go @@ -5,6 +5,8 @@ package check import ( "context" "crypto/ed25519" + "crypto/sha256" + "encoding/hex" "errors" "fmt" "io/fs" @@ -32,6 +34,10 @@ type SealOptions struct { Workers int Now time.Time Progress func(done, total int) + // Fast reuses hashes of files whose size and modification time did not change since the last run (see + // scan.Cache). CacheFile overrides where that memory is kept. + Fast bool + CacheFile string } // SealResult is what Seal produced. @@ -41,6 +47,8 @@ type SealResult struct { Scan *scan.Result // Previous is the diff against the manifest that was there before, when there was a valid one. Previous *compare.Diff + // Reused is the number of file hashes taken from the fast-mode cache. + Reused int } func manifestPath(dir, given string) string { @@ -83,8 +91,14 @@ func Seal(ctx context.Context, o SealOptions) (*SealResult, error) { patterns = append(patterns, o.Exclude...) matcher := ignore.New(patterns...) + cachePath := "" + var cache *scan.Cache + if o.Fast { + cachePath = fastCachePath(o.Dir, o.Algorithm, o.CacheFile) + cache = scan.LoadCache(cachePath, o.Algorithm) + } res, err := scan.Scan(ctx, scan.Options{Root: o.Dir, Algorithm: o.Algorithm, Ignore: matcher, - Skip: skipPaths(o.Dir, mpath), Workers: o.Workers, Progress: o.Progress}) + Skip: skipPaths(o.Dir, mpath), Workers: o.Workers, Progress: o.Progress, Cache: cache}) if err != nil { return nil, err } @@ -105,7 +119,10 @@ func Seal(ctx context.Context, o SealOptions) (*SealResult, error) { Value: sign.Sign(o.Key, m.Algorithm, m.Root, manifest.IgnoreDigest(m.Ignore)), } } - out := &SealResult{Manifest: m, ManifestPath: mpath, Scan: res} + out := &SealResult{Manifest: m, ManifestPath: mpath, Scan: res, Reused: res.Reused} + if o.Fast { + _ = scan.Save(cachePath, o.Algorithm, res.CacheEntries, o.Now) // best effort: a cache only speeds things up + } if prev, err := manifest.Read(mpath); err == nil { d := compare.Compare(prev.Files, m.Files) out.Previous = &d @@ -150,6 +167,8 @@ type Options struct { Workers int Now time.Time Progress func(done, total int) + Fast bool + CacheFile string } // Result is the outcome of a check. @@ -164,6 +183,8 @@ type Result struct { Signature SignatureStatus KeyID string CheckedAt time.Time + // Reused is the number of file hashes taken from the fast-mode cache. + Reused int } // OK reports whether the folder matches the manifest and nothing is wrong with the manifest. @@ -187,15 +208,24 @@ func Check(ctx context.Context, o Options) (*Result, error) { if err != nil { return nil, err } + cachePath := "" + var cache *scan.Cache + if o.Fast { + cachePath = fastCachePath(o.Dir, m.Algorithm, o.CacheFile) + cache = scan.LoadCache(cachePath, m.Algorithm) + } res, err := scan.Scan(ctx, scan.Options{Root: o.Dir, Algorithm: m.Algorithm, Ignore: ignore.New(m.Ignore...), - Skip: skipPaths(o.Dir, mpath), Workers: o.Workers, Progress: o.Progress}) + Skip: skipPaths(o.Dir, mpath), Workers: o.Workers, Progress: o.Progress, Cache: cache}) if err != nil { return nil, err } + if o.Fast { + _ = scan.Save(cachePath, m.Algorithm, res.CacheEntries, o.Now) + } r := &Result{ ManifestPath: mpath, Manifest: m, Diff: compare.Compare(m.Files, res.Files), Unreadable: res.Unreadable, Skipped: res.Skipped, RootDamaged: !m.RootMatches(), - Signature: SigNone, CheckedAt: o.Now, + Signature: SigNone, CheckedAt: o.Now, Reused: res.Reused, } // Unreadable files must not be reported as removed: they are there, we just cannot see them. if len(res.Unreadable) > 0 { @@ -235,3 +265,21 @@ func dropRemoved(d compare.Diff, unreadable map[string]bool) compare.Diff { d.Removed = removed return d } + +// fastCachePath is where the fast-mode memory of a folder lives: the given file, or a file in the user's cache +// folder named after the folder and the algorithm, so different folders never share one. +func fastCachePath(dir, algorithm, explicit string) string { + if explicit != "" { + return explicit + } + abs, err := filepath.Abs(dir) + if err != nil { + abs = dir + } + sum := sha256.Sum256([]byte(abs + "\x00" + algorithm)) + base, err := os.UserCacheDir() + if err != nil { + base = os.TempDir() + } + return filepath.Join(base, "assay", hex.EncodeToString(sum[:8])+".json") +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index d302d53..b766ed5 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -45,6 +45,8 @@ Usage: assay report [folder] -o file.html write an HTML report of a check assay export [folder] [flags] print the manifest as sha256sum lines assay keygen [-o prefix] create an Ed25519 key pair for signing + assay completion print a completion script (bash, zsh, fish, powershell) + assay man print the manual page assay version The folder defaults to the current directory, the manifest to /.assay.json. @@ -82,6 +84,10 @@ func (a *App) Run(ctx context.Context, args []string) int { code, err = a.export(rest) case "keygen": code, err = a.keygen(rest) + case "completion": + code, err = a.completion(rest) + case "man": + code, err = a.man() case "version", "--version", "-v": fmt.Fprintf(a.Out, "assay %s (commit %s, built %s)\n", Version, Commit, Date) case "help", "-h", "--help": @@ -185,6 +191,8 @@ func (a *App) seal(ctx context.Context, args []string) (int, error) { keyFile := fs.String("key", "", "private key `file`: sign the manifest") workers := fs.Int("workers", 0, "number of parallel hash workers (default: number of CPUs)") quiet := fs.Bool("q", false, "print nothing but errors") + fast := fs.Bool("fast", false, "reuse hashes of files whose size and modification time are unchanged (faster, but trusts them)") + cacheFile := fs.String("cache-file", "", "memory file for --fast (default: your cache folder)") fs.Var(&exclude, "exclude", "ignore `pattern` (repeatable; same rules as .gitignore)") pos, err := parse(fs, args) if err != nil { @@ -201,7 +209,7 @@ func (a *App) seal(ctx context.Context, args []string) (int, error) { } } res, err := check.Seal(ctx, check.SealOptions{Dir: dir, ManifestPath: *manifestFile, Algorithm: *algo, - Exclude: exclude, Key: key, Workers: *workers, Progress: a.progress(*quiet)}) + Exclude: exclude, Key: key, Workers: *workers, Progress: a.progress(*quiet), Fast: *fast, CacheFile: *cacheFile}) if err != nil { return ExitError, err } @@ -230,6 +238,8 @@ type checkFlags struct { workers int quiet, verbose, js bool watch time.Duration + fast bool + cacheFile string } func (a *App) check(ctx context.Context, args []string) (int, error) { @@ -241,6 +251,8 @@ func (a *App) check(ctx context.Context, args []string) (int, error) { fs.IntVar(&f.workers, "workers", 0, "number of parallel hash workers (default: number of CPUs)") fs.BoolVar(&f.quiet, "q", false, "print nothing when everything is fine") fs.BoolVar(&f.verbose, "v", false, "also list skipped entries") + fs.BoolVar(&f.fast, "fast", false, "reuse hashes of files whose size and modification time are unchanged (faster, but trusts them)") + fs.StringVar(&f.cacheFile, "cache-file", "", "memory file for --fast (default: your cache folder)") fs.BoolVar(&f.js, "json", false, "print the result as JSON") fs.DurationVar(&f.watch, "watch", 0, "check again every `interval` (for example 10s) and report changes") pos, err := parse(fs, args) @@ -261,7 +273,7 @@ func (a *App) check(ctx context.Context, args []string) (int, error) { } func (a *App) options(dir string, f checkFlags, progress bool) (check.Options, error) { - o := check.Options{Dir: dir, ManifestPath: f.manifest, Workers: f.workers} + o := check.Options{Dir: dir, ManifestPath: f.manifest, Workers: f.workers, Fast: f.fast, CacheFile: f.cacheFile} if f.pubkey != "" { pub, err := sign.ReadPublic(f.pubkey) if err != nil { diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 9a96ade..84bf765 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -219,3 +219,91 @@ func TestWatchStopsWithContextAndReportsChange(t *testing.T) { t.Fatalf("output: %s", out.String()) } } + +func TestFastModeReusesHashesAndSaysSo(t *testing.T) { + dir := folder(t) + old := time.Now().Add(-time.Hour) + for _, f := range []string{"a.txt", "sub/b.txt"} { + _ = os.Chtimes(filepath.Join(dir, filepath.FromSlash(f)), old, old) + } + cache := filepath.Join(t.TempDir(), "fast.json") + if r := sealWith(t, dir, "--fast", "--cache-file", cache); r.code != ExitOK { + t.Fatalf("seal: %+v", r) + } + r := assay(t, "check", dir, "--fast", "--cache-file", cache) + if r.code != ExitOK || !strings.Contains(r.out, "fast mode: 2 of 2 file hashes were reused") { + t.Fatalf("check --fast: %+v", r) + } + // Without --fast nothing is reused and nothing is said about it. + if r := assay(t, "check", dir); strings.Contains(r.out, "fast mode") { + t.Fatalf("normal check must not use the cache: %s", r.out) + } + // A real change is still found in fast mode. + write(t, dir, "a.txt", "changed content") + if r := assay(t, "check", dir, "--fast", "--cache-file", cache); r.code != ExitChanged || !strings.Contains(r.out, "modified a.txt") { + t.Fatalf("change not found: %+v", r) + } +} + +func sealWith(t *testing.T, dir string, extra ...string) run { + t.Helper() + return assay(t, append([]string{"seal", dir}, extra...)...) +} + +func TestCompletionScriptsListRealCommandsAndFlags(t *testing.T) { + for _, shell := range []string{"bash", "zsh", "fish", "powershell"} { + r := assay(t, "completion", shell) + if r.code != ExitOK { + t.Fatalf("%s: %+v", shell, r) + } + wants := []string{"seal", "check", "report", "keygen", "--fast", "--pubkey", "--json"} + if shell == "fish" { // fish spells long options as "-l name" + wants = []string{"seal", "check", "report", "keygen", "-l fast", "-l pubkey", "-l json"} + } + for _, want := range wants { + if !strings.Contains(r.out, want) { + t.Errorf("%s completion lacks %q", shell, want) + } + } + } + if r := assay(t, "completion", "tcsh"); r.code != ExitError { + t.Fatalf("unknown shell: %+v", r) + } + if r := assay(t, "completion"); r.code != ExitError { + t.Fatalf("no shell: %+v", r) + } +} + +func TestCompletionKnowsWhichFlagsTakeFiles(t *testing.T) { + var app App + var check commandInfo + for _, c := range app.commandInfos() { + if c.Name == "check" { + check = c + } + } + flags := map[string]flagInfo{} + for _, f := range check.Flags { + flags[f.Name] = f + } + for _, name := range []string{"m", "pubkey", "json", "fast", "watch", "cache-file", "require-signature"} { + if _, ok := flags[name]; !ok { + t.Errorf("check should have flag %q (found %v)", name, flags) + } + } + if !flags["pubkey"].File || !flags["m"].File || flags["json"].Arg || !flags["watch"].Arg { + t.Errorf("wrong flag kinds: %+v", flags) + } +} + +func TestManPageMentionsEverything(t *testing.T) { + r := assay(t, "man") + if r.code != ExitOK || !strings.HasPrefix(r.out, ".TH ASSAY 1") { + t.Fatalf("man: %+v", r.code) + } + for _, want := range []string{".SH NAME", ".SH EXIT STATUS", "seal", "completion", `\-\-fast`, ".SH FILES"} { + if !strings.Contains(r.out, want) { + t.Errorf("man page lacks %q", want) + } + } +} diff --git a/internal/cli/complete.go b/internal/cli/complete.go new file mode 100644 index 0000000..932d6d3 --- /dev/null +++ b/internal/cli/complete.go @@ -0,0 +1,294 @@ +package cli + +import ( + "bytes" + "context" + "fmt" + "io" + "sort" + "strings" +) + +// commandInfo describes one command, for completion scripts and the man page. The flags are read from the +// commands themselves (their -h output), so these files can never list a flag that does not exist or miss one. +type commandInfo struct { + Name string + Summary string + Positional string // what follows the command: "folder", "old.json new.json", ... + Flags []flagInfo +} + +type flagInfo struct { + Name string // without dashes + Usage string + Arg bool // takes a value + File bool // the value is a file name +} + +// Long names are written with two dashes, single letters with one. +func (f flagInfo) Dashed() string { + if len(f.Name) == 1 { + return "-" + f.Name + } + return "--" + f.Name +} + +var summaries = []struct{ name, summary, positional string }{ + {"seal", "record a hash of every file in a folder in a manifest", "[folder]"}, + {"check", "compare a folder with its manifest", "[folder]"}, + {"diff", "compare two manifests", " "}, + {"report", "write an HTML report of a check", "[folder]"}, + {"export", "print the manifest as sha256sum lines", "[folder]"}, + {"keygen", "create an Ed25519 key pair for signing", ""}, + {"completion", "print a completion script for a shell", ""}, + {"man", "print the manual page", ""}, + {"version", "print the version", ""}, +} + +// commandInfos returns the commands with the flags each one accepts. +func (a *App) commandInfos() []commandInfo { + var out []commandInfo + for _, s := range summaries { + ci := commandInfo{Name: s.name, Summary: s.summary, Positional: s.positional} + switch s.name { + case "seal", "check", "diff", "report", "export", "keygen": + var buf bytes.Buffer + (&App{Out: io.Discard, Err: &buf}).Run(context.Background(), []string{s.name, "-h"}) + ci.Flags = parseFlagHelp(buf.String()) + } + out = append(out, ci) + } + return out +} + +// parseFlagHelp reads the output of the standard flag package: +// +// -algo string +// hash algorithm: sha256, sha512 (default "sha256") +// -q print nothing but errors +func parseFlagHelp(text string) []flagInfo { + var flags []flagInfo + lines := strings.Split(text, "\n") + for i := 0; i < len(lines); i++ { + line := lines[i] + if !strings.HasPrefix(line, " -") { + continue + } + head := strings.TrimPrefix(line, " -") + usage := "" + if tab := strings.Index(head, "\t"); tab >= 0 { // bool flag: "qusage" + usage = strings.TrimSpace(head[tab+1:]) + head = head[:tab] + } + fields := strings.Fields(head) + if len(fields) == 0 { + continue + } + f := flagInfo{Name: fields[0], Arg: len(fields) > 1} + if usage == "" && i+1 < len(lines) { + usage = strings.TrimSpace(lines[i+1]) + i++ + } + f.Usage = usage + f.File = f.Arg && len(fields) > 1 && fields[1] == "file" + if f.Name == "h" || f.Name == "help" { + continue + } + flags = append(flags, f) + } + sort.SliceStable(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name }) + return flags +} + +func (a *App) completion(args []string) (int, error) { + if len(args) != 1 { + return ExitError, fmt.Errorf("usage: assay completion ") + } + infos := a.commandInfos() + var script string + switch args[0] { + case "bash": + script = bashCompletion(infos) + case "zsh": + script = zshCompletion(infos) + case "fish": + script = fishCompletion(infos) + case "powershell": + script = powershellCompletion(infos) + default: + return ExitError, fmt.Errorf("unknown shell %q (bash, zsh, fish or powershell)", args[0]) + } + fmt.Fprint(a.Out, script) + return ExitOK, nil +} + +func names(infos []commandInfo) []string { + out := make([]string, len(infos)) + for i, c := range infos { + out[i] = c.Name + } + return out +} + +func flagWords(c commandInfo) string { + words := make([]string, len(c.Flags)) + for i, f := range c.Flags { + words[i] = f.Dashed() + } + return strings.Join(words, " ") +} + +func fileFlags(infos []commandInfo) []string { + set := map[string]bool{} + for _, c := range infos { + for _, f := range c.Flags { + if f.File { + set[f.Dashed()] = true + } + } + } + out := make([]string, 0, len(set)) + for k := range set { + out = append(out, k) + } + sort.Strings(out) + return out +} + +func bashCompletion(infos []commandInfo) string { + var b strings.Builder + b.WriteString("# bash completion for assay (generated by \"assay completion bash\")\n_assay() {\n") + b.WriteString(" local cur prev cmd flags\n COMPREPLY=()\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\n cmd=\"${COMP_WORDS[1]}\"\n") + fmt.Fprintf(&b, " if [ \"$COMP_CWORD\" -eq 1 ]; then\n COMPREPLY=( $(compgen -W \"%s\" -- \"$cur\") )\n return\n fi\n", strings.Join(names(infos), " ")) + fmt.Fprintf(&b, " case \"$prev\" in\n %s)\n COMPREPLY=( $(compgen -f -- \"$cur\") )\n return ;;\n --algo)\n COMPREPLY=( $(compgen -W \"sha256 sha512\" -- \"$cur\") )\n return ;;\n esac\n", strings.Join(fileFlags(infos), "|")) + b.WriteString(" case \"$cmd\" in\n") + for _, c := range infos { + switch c.Name { + case "completion": + b.WriteString(" completion) COMPREPLY=( $(compgen -W \"bash zsh fish powershell\" -- \"$cur\") ); return ;;\n") + default: + fmt.Fprintf(&b, " %s) flags=\"%s\" ;;\n", c.Name, flagWords(c)) + } + } + b.WriteString(" esac\n if [[ \"$cur\" == -* ]]; then\n COMPREPLY=( $(compgen -W \"$flags\" -- \"$cur\") )\n else\n COMPREPLY=( $(compgen -d -- \"$cur\") )\n fi\n}\ncomplete -o filenames -F _assay assay\n") + return b.String() +} + +func zshQuote(s string) string { + s = strings.NewReplacer("[", "(", "]", ")", "'", "'\\''").Replace(s) + return s +} + +func zshCompletion(infos []commandInfo) string { + var b strings.Builder + b.WriteString("#compdef assay\n# zsh completion for assay (generated by \"assay completion zsh\")\n\n_assay() {\n local -a commands\n commands=(\n") + for _, c := range infos { + fmt.Fprintf(&b, " '%s:%s'\n", c.Name, zshQuote(strings.ReplaceAll(c.Summary, ":", "\\:"))) + } + b.WriteString(" )\n if (( CURRENT == 2 )); then\n _describe 'command' commands\n return\n fi\n case $words[2] in\n") + for _, c := range infos { + switch c.Name { + case "completion": + b.WriteString(" completion) _values 'shell' bash zsh fish powershell ;;\n") + case "diff": + b.WriteString(" diff) _arguments '--json[print as JSON]' '*:manifest:_files -g \"*.json\"' ;;\n") + case "version", "man": + fmt.Fprintf(&b, " %s) ;;\n", c.Name) + default: + fmt.Fprintf(&b, " %s) _arguments \\\n", c.Name) + for _, f := range c.Flags { + switch { + case f.File: + fmt.Fprintf(&b, " '%s[%s]:file:_files' \\\n", f.Dashed(), zshQuote(f.Usage)) + case f.Name == "algo": + fmt.Fprintf(&b, " '%s[%s]:algorithm:(sha256 sha512)' \\\n", f.Dashed(), zshQuote(f.Usage)) + case f.Arg: + fmt.Fprintf(&b, " '%s[%s]:value:' \\\n", f.Dashed(), zshQuote(f.Usage)) + default: + fmt.Fprintf(&b, " '%s[%s]' \\\n", f.Dashed(), zshQuote(f.Usage)) + } + } + b.WriteString(" '*:folder:_files -/' ;;\n") + } + } + b.WriteString(" esac\n}\n\n_assay \"$@\"\n") + return b.String() +} + +func fishQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", "\\'") + "'" } + +func fishCompletion(infos []commandInfo) string { + var b strings.Builder + b.WriteString("# fish completion for assay (generated by \"assay completion fish\")\ncomplete -c assay -f\n") + for _, c := range infos { + fmt.Fprintf(&b, "complete -c assay -n '__fish_use_subcommand' -a %s -d %s\n", c.Name, fishQuote(c.Summary)) + } + b.WriteString("complete -c assay -n '__fish_seen_subcommand_from completion' -a 'bash zsh fish powershell'\n") + for _, c := range infos { + for _, f := range c.Flags { + opt := "-l " + f.Name + if len(f.Name) == 1 { + opt = "-s " + f.Name + } + arg := "" + switch { + case f.File: + arg = " -r -F" + case f.Name == "algo": + arg = " -x -a 'sha256 sha512'" + case f.Arg: + arg = " -x" + } + fmt.Fprintf(&b, "complete -c assay -n '__fish_seen_subcommand_from %s' %s%s -d %s\n", c.Name, opt, arg, fishQuote(f.Usage)) + } + } + return b.String() +} + +func powershellCompletion(infos []commandInfo) string { + var b strings.Builder + b.WriteString("# PowerShell completion for assay (generated by \"assay completion powershell\")\n") + b.WriteString("$assayFlags = @{\n") + for _, c := range infos { + quoted := make([]string, len(c.Flags)) + for i, f := range c.Flags { + quoted[i] = "'" + f.Dashed() + "'" + } + fmt.Fprintf(&b, " '%s' = @(%s)\n", c.Name, strings.Join(quoted, ", ")) + } + b.WriteString("}\nRegister-ArgumentCompleter -Native -CommandName assay -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $words = $commandAst.CommandElements | ForEach-Object { $_.ToString() }\n") + b.WriteString(" if ($words.Count -le 1 -or ($words.Count -eq 2 -and $wordToComplete -ne '')) {\n $assayFlags.Keys | Sort-Object | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }\n return\n }\n") + b.WriteString(" $cmd = $words[1]\n if ($cmd -eq 'completion') { 'bash','zsh','fish','powershell' | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }; return }\n") + b.WriteString(" if ($assayFlags.ContainsKey($cmd)) {\n $assayFlags[$cmd] | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterName', $_) }\n }\n}\n") + return b.String() +} + +func (a *App) man() (int, error) { + infos := a.commandInfos() + esc := func(s string) string { return strings.NewReplacer(`\`, `\\`, "-", `\-`).Replace(s) } + var b strings.Builder + fmt.Fprintf(&b, ".TH ASSAY 1 \"\" \"assay %s\" \"User Commands\"\n", esc(Version)) + b.WriteString(".SH NAME\nassay \\- see whether files were changed\n") + b.WriteString(".SH SYNOPSIS\n") + for _, c := range infos { + fmt.Fprintf(&b, ".B assay %s\n%s\n.br\n", c.Name, esc(c.Positional)) + } + b.WriteString(".SH DESCRIPTION\n.B assay\nrecords a cryptographic hash of every file in a folder (a \\fImanifest\\fR) and later shows which files were modified, added, removed or renamed. A manifest can be signed with an Ed25519 key, so that replacing it after tampering with the files is noticed. A hash shows that a file changed, not who changed it.\n") + b.WriteString(".SH COMMANDS\n") + for _, c := range infos { + fmt.Fprintf(&b, ".TP\n.B %s %s\n%s.\n", c.Name, esc(c.Positional), esc(c.Summary)) + for _, f := range c.Flags { + arg := "" + if f.Arg { + arg = " \\fIvalue\\fR" + } + fmt.Fprintf(&b, ".RS\n.TP\n\\fB%s\\fR%s\n%s\n.RE\n", esc(f.Dashed()), arg, esc(f.Usage)) + } + } + b.WriteString(".SH EXIT STATUS\n.TP\n.B 0\nNothing changed (check), or the command succeeded.\n.TP\n.B 1\nDifferences were found, the manifest is damaged or a signature is invalid.\n.TP\n.B 2\nAn error: bad usage, unreadable files, no manifest.\n") + b.WriteString(".SH FILES\n.TP\n.I .assay.json\nThe manifest, by default inside the sealed folder.\n.TP\n.I .assayignore\nPatterns (as in .gitignore) for files that are left out; the patterns in effect are stored in the manifest.\n") + b.WriteString(".SH EXAMPLES\n.nf\nassay seal ./backups\nassay check ./backups --json\nassay keygen \\-o release\nassay seal ./dist \\-\\-key release.key\nassay check ./dist \\-\\-pubkey release.pub \\-\\-require\\-signature\n.fi\n") + b.WriteString(".SH SEE ALSO\nhttps://github.com/SandSoftwareSolutions/assay\n.SH LICENSE\nGNU Affero General Public License v3.0 or later.\n") + fmt.Fprint(a.Out, b.String()) + return ExitOK, nil +} diff --git a/internal/report/report.go b/internal/report/report.go index b06c559..5c58a4a 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -77,6 +77,9 @@ func Text(w io.Writer, r *check.Result, o TextOptions) { } } fmt.Fprintln(w, summary(c, r)) + if r.Reused > 0 { + fmt.Fprintf(w, "fast mode: %d of %d file hashes were reused because size and modification time did not change (these were trusted, not read)\n", r.Reused, len(r.Manifest.Files)+len(r.Diff.Added)) + } } func describeChange(ch compare.Change) string { diff --git a/internal/scan/cache.go b/internal/scan/cache.go new file mode 100644 index 0000000..047c7b9 --- /dev/null +++ b/internal/scan/cache.go @@ -0,0 +1,90 @@ +package scan + +import ( + "encoding/json" + "os" + "path/filepath" + "time" +) + +// racyWindow: a file modified within this time before the cache was written may have been changed again within +// the same timestamp tick, so its cached hash is not trusted (the same rule git applies to its index). +const racyWindow = 2 * time.Second + +// CacheEntry remembers what a file looked like when it was hashed. +type CacheEntry struct { + Size int64 `json:"size"` + ModNs int64 `json:"mod_ns"` + Hash string `json:"hash"` +} + +// Cache lets a later scan skip hashing files whose size and modification time did not change. +// +// This is a speed-up, not a security measure: size and modification time can be set by whoever can change the +// file. Use it to make checks of big folders fast on a machine you trust; run without it when tampering is the +// question. +type Cache struct { + Algorithm string `json:"algorithm"` + Created time.Time `json:"created"` + Entries map[string]CacheEntry `json:"entries"` +} + +// LoadCache reads a cache file. A missing, damaged or other-algorithm cache gives an empty one: a cache can +// only ever make a scan faster, never make it fail. +func LoadCache(path, algorithm string) *Cache { + empty := &Cache{Algorithm: algorithm, Entries: map[string]CacheEntry{}} + data, err := os.ReadFile(path) + if err != nil { + return empty + } + var c Cache + if json.Unmarshal(data, &c) != nil || c.Algorithm != algorithm || c.Entries == nil { + return empty + } + return &c +} + +// lookup returns the cached hash when the file still has the size and modification time it had before. +func (c *Cache) lookup(rel string, size, modNs int64) (string, bool) { + if c == nil { + return "", false + } + e, ok := c.Entries[rel] + if !ok || e.Size != size || e.ModNs != modNs { + return "", false + } + if modNs >= c.Created.Add(-racyWindow).UnixNano() { + return "", false + } + return e.Hash, true +} + +// Save writes a cache with the given entries, atomically. +func Save(path, algorithm string, entries map[string]CacheEntry, now time.Time) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + data, err := json.Marshal(Cache{Algorithm: algorithm, Created: now, Entries: entries}) + if err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), ".assay-cache-*.tmp") + if err != nil { + return err + } + name := tmp.Name() + if _, err := tmp.Write(data); err != nil { + tmp.Close() + os.Remove(name) + return err + } + if err := tmp.Close(); err != nil { + os.Remove(name) + return err + } + if err := os.Rename(name, path); err != nil { + os.Remove(name) + return err + } + return nil +} diff --git a/internal/scan/scan.go b/internal/scan/scan.go index 212d9aa..9635204 100644 --- a/internal/scan/scan.go +++ b/internal/scan/scan.go @@ -28,6 +28,8 @@ type Options struct { Workers int // Progress is called with the number of files hashed so far (from several goroutines). Progress func(done, total int) + // Cache, when set, lets files with an unchanged size and modification time reuse their earlier hash. + Cache *Cache } // Problem is a path that could not be read. @@ -42,6 +44,10 @@ type Result struct { Unreadable []Problem // Skipped lists entries that are neither regular files nor directories (symlinks, sockets, ...). Skipped []string + // Reused is the number of hashes taken from the cache instead of reading the file. + Reused int + // CacheEntries describes every hashed file, to be saved for the next scan. + CacheEntries map[string]CacheEntry } // Scan hashes every regular file below opts.Root that is not ignored. Symbolic links are not @@ -106,8 +112,10 @@ func Scan(ctx context.Context, opts Options) (*Result, error) { workers = len(rels) } type outcome struct { - entry manifest.Entry - err error + entry manifest.Entry + err error + cached bool + cache CacheEntry } results := make([]outcome, len(rels)) jobs := make(chan int) @@ -118,8 +126,8 @@ func Scan(ctx context.Context, opts Options) (*Result, error) { go func() { defer wg.Done() for i := range jobs { - entry, err := hashFile(opts.Root, rels[i], opts.Algorithm) - results[i] = outcome{entry: entry, err: err} + entry, ce, cached, err := hashFile(opts.Root, rels[i], opts.Algorithm, opts.Cache) + results[i] = outcome{entry: entry, err: err, cached: cached, cache: ce} if opts.Progress != nil { opts.Progress(int(atomic.AddInt64(&done, 1)), len(rels)) } @@ -145,25 +153,46 @@ send: continue } res.Files = append(res.Files, r.entry) + if r.cached { + res.Reused++ + } + if res.CacheEntries == nil { + res.CacheEntries = map[string]CacheEntry{} + } + res.CacheEntries[rels[i]] = r.cache } sort.Slice(res.Unreadable, func(i, j int) bool { return res.Unreadable[i].Path < res.Unreadable[j].Path }) sort.Strings(res.Skipped) return res, nil } -func hashFile(root, rel, algorithm string) (manifest.Entry, error) { +func hashFile(root, rel, algorithm string, cache *Cache) (manifest.Entry, CacheEntry, bool, error) { + path := filepath.Join(root, filepath.FromSlash(rel)) + st, err := os.Stat(path) + if err != nil { + return manifest.Entry{}, CacheEntry{}, false, err + } + size, modNs := st.Size(), st.ModTime().UnixNano() + if hash, ok := cache.lookup(rel, size, modNs); ok { + return manifest.Entry{Path: rel, Size: size, Hash: hash}, CacheEntry{Size: size, ModNs: modNs, Hash: hash}, true, nil + } h, err := manifest.NewHash(algorithm) if err != nil { - return manifest.Entry{}, err + return manifest.Entry{}, CacheEntry{}, false, err } - f, err := os.Open(filepath.Join(root, filepath.FromSlash(rel))) + f, err := os.Open(path) if err != nil { - return manifest.Entry{}, err + return manifest.Entry{}, CacheEntry{}, false, err } defer f.Close() n, err := io.Copy(h, f) if err != nil { - return manifest.Entry{}, fmt.Errorf("read: %w", err) + return manifest.Entry{}, CacheEntry{}, false, fmt.Errorf("read: %w", err) + } + hash := hex.EncodeToString(h.Sum(nil)) + // If the file changed while it was read, do not remember it: the cached values would not match the content. + if after, err := os.Stat(path); err != nil || after.Size() != size || after.ModTime().UnixNano() != modNs { + return manifest.Entry{Path: rel, Size: n, Hash: hash}, CacheEntry{Size: -1}, false, nil } - return manifest.Entry{Path: rel, Size: n, Hash: hex.EncodeToString(h.Sum(nil))}, nil + return manifest.Entry{Path: rel, Size: n, Hash: hash}, CacheEntry{Size: size, ModNs: modNs, Hash: hash}, false, nil } diff --git a/internal/scan/scan_test.go b/internal/scan/scan_test.go index 67ba66c..830d6f9 100644 --- a/internal/scan/scan_test.go +++ b/internal/scan/scan_test.go @@ -11,6 +11,7 @@ import ( "runtime" "sync/atomic" "testing" + "time" "github.com/SandSoftwareSolutions/assay/internal/ignore" ) @@ -135,3 +136,72 @@ func TestUnknownAlgorithm(t *testing.T) { t.Fatal("expected an error") } } + +func TestCacheReusesUnchangedFilesAndNotesTheTradeOff(t *testing.T) { + root := t.TempDir() + write(t, root, "a.txt", "alpha") + write(t, root, "b.txt", "bravo") + old := time.Now().Add(-time.Hour) + for _, f := range []string{"a.txt", "b.txt"} { + _ = os.Chtimes(filepath.Join(root, f), old, old) + } + first, err := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New()}) + if err != nil || first.Reused != 0 { + t.Fatalf("first scan: %v reused=%d", err, first.Reused) + } + cachePath := filepath.Join(t.TempDir(), "cache.json") + if err := Save(cachePath, "sha256", first.CacheEntries, time.Now()); err != nil { + t.Fatal(err) + } + + // Nothing changed: everything is reused and the result is identical. + second, err := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New(), Cache: LoadCache(cachePath, "sha256")}) + if err != nil || second.Reused != 2 || !reflect.DeepEqual(first.Files, second.Files) { + t.Fatalf("second scan: %v reused=%d", err, second.Reused) + } + + // A real change (new size and time) is hashed again. + write(t, root, "a.txt", "alpha changed") + third, _ := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New(), Cache: LoadCache(cachePath, "sha256")}) + if third.Reused != 1 { + t.Fatalf("only the unchanged file may be reused, got %d", third.Reused) + } + if third.Files[0].Hash == first.Files[0].Hash { + t.Fatal("a changed file must get a new hash") + } + + // The documented trade-off: same size and same modification time but different content is NOT noticed in + // fast mode (a normal scan does see it). + write(t, root, "b.txt", "BRAVO") + _ = os.Chtimes(filepath.Join(root, "b.txt"), old, old) + fast, _ := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New(), Cache: LoadCache(cachePath, "sha256")}) + full, _ := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New()}) + if fast.Files[1].Hash != first.Files[1].Hash { + t.Fatal("fast mode is expected to trust size and time") + } + if full.Files[1].Hash == first.Files[1].Hash { + t.Fatal("a normal scan must see the changed content") + } +} + +func TestCacheDoesNotTrustRecentFilesOrOtherAlgorithmsOrDamage(t *testing.T) { + root := t.TempDir() + write(t, root, "new.txt", "just written") // modified "now": within the racy window + first, _ := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New()}) + cachePath := filepath.Join(t.TempDir(), "cache.json") + _ = Save(cachePath, "sha256", first.CacheEntries, time.Now()) + again, _ := Scan(context.Background(), Options{Root: root, Algorithm: "sha256", Ignore: ignore.New(), Cache: LoadCache(cachePath, "sha256")}) + if again.Reused != 0 { + t.Fatal("a file changed moments before the cache was written must be hashed again") + } + if c := LoadCache(cachePath, "sha512"); len(c.Entries) != 0 { + t.Fatal("a cache of another algorithm must be ignored") + } + _ = os.WriteFile(cachePath, []byte("{broken"), 0o644) + if c := LoadCache(cachePath, "sha256"); len(c.Entries) != 0 { + t.Fatal("a damaged cache must be ignored, not fail") + } + if c := LoadCache(filepath.Join(t.TempDir(), "missing.json"), "sha256"); c == nil || len(c.Entries) != 0 { + t.Fatal("a missing cache must be empty") + } +} diff --git a/scripts/dist.sh b/scripts/dist.sh index 93faab0..02ca48d 100755 --- a/scripts/dist.sh +++ b/scripts/dist.sh @@ -49,6 +49,19 @@ if command -v dpkg-deb >/dev/null 2>&1; then mkdir -p "$pkg/DEBIAN" "$pkg/usr/bin" cp "$WORK/assay_${VERSION}_linux_${arch}/assay" "$pkg/usr/bin/assay" chmod 755 "$pkg/usr/bin/assay" + # Shell completions and the manual page, generated by the program itself. The amd64 binary is the one that can + # run on the build machine; the text is the same for arm64. + host="$WORK/assay_${VERSION}_linux_amd64/assay" + if "$host" version >/dev/null 2>&1; then + mkdir -p "$pkg/usr/share/bash-completion/completions" "$pkg/usr/share/zsh/vendor-completions" \ + "$pkg/usr/share/fish/vendor_completions.d" "$pkg/usr/share/man/man1" + "$host" completion bash > "$pkg/usr/share/bash-completion/completions/assay" + "$host" completion zsh > "$pkg/usr/share/zsh/vendor-completions/_assay" + "$host" completion fish > "$pkg/usr/share/fish/vendor_completions.d/assay.fish" + "$host" man | gzip -9n > "$pkg/usr/share/man/man1/assay.1.gz" + else + echo "[warn] cannot run the linux/amd64 binary here; the .deb gets no completions or manual page" + fi cat > "$pkg/DEBIAN/control" < Date: Fri, 16 Oct 2026 20:33:56 +0200 Subject: [PATCH 2/2] Action: tolerate CR and backslash in checksum output on Windows, show both hashes on mismatch --- action.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/action.yml b/action.yml index a20158e..c9acff7 100644 --- a/action.yml +++ b/action.yml @@ -70,11 +70,11 @@ runs: mkdir -p "$dir" curl -fsSL -o "$dir/$archive" "$base/$archive" curl -fsSL -o "$dir/SHA256SUMS" "$base/SHA256SUMS" - expected="$(awk -v f="$archive" '$2 == f {print $1}' "$dir/SHA256SUMS")" + expected="$(awk -v f="$archive" '$2 == f {print $1}' "$dir/SHA256SUMS" | tr -d '\r')" [ -n "$expected" ] || { echo "no checksum listed for $archive" >&2; exit 1; } - if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$dir/$archive" | awk '{print $1}')" + if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$dir/$archive" | awk '{print $1}' | tr -d '\r\\')" else actual="$(shasum -a 256 "$dir/$archive" | awk '{print $1}')"; fi - if [ "$expected" != "$actual" ]; then echo "checksum mismatch for $archive; refusing to use it" >&2; exit 1; fi + if [ "$expected" != "$actual" ]; then echo "checksum mismatch for $archive (expected $expected, got $actual); refusing to use it" >&2; exit 1; fi if [ "$ext" = zip ]; then unzip -q -o "$dir/$archive" -d "$dir"; else tar -xzf "$dir/$archive" -C "$dir"; fi bin="$dir/assay_${version}_${os}_${arch}" if command -v cygpath >/dev/null 2>&1; then bin="$(cygpath -w "$bin")"; fi