diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 8c46f71..7ed7fbb 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -31,7 +31,11 @@ jobs: cache: true - name: Generate, vet, and test + # ubuntu-latest ships shellcheck; the flag turns TestShellcheck's skip into a failure if it ever goes missing. + env: + KARKIVE_REQUIRE_SHELLCHECK: "1" run: | + shellcheck --version make generate manifests fmt vet test git diff --exit-code diff --git a/Makefile b/Makefile index 4fb59d9..54645b2 100644 --- a/Makefile +++ b/Makefile @@ -22,6 +22,11 @@ run: generate manifests test: generate go test ./... +# Pipeline scripts only: shellcheck (when installed) plus the script behaviour tests. CI runs the same test with shellcheck required. +.PHONY: test-scripts +test-scripts: + go test ./internal/pipeline/ + .PHONY: fmt fmt: go fmt ./... diff --git a/README.md b/README.md index 1b34888..5721f3d 100644 --- a/README.md +++ b/README.md @@ -508,13 +508,14 @@ kubectl apply -f config/samples/karkive_v1alpha1_backup.yaml | `make generate` | Deepcopy for `api/` | | `make manifests` | CRDs, RBAC and webhook manifests, plus the chart's CRD templates | | `make test` | `go test ./...` | +| `make test-scripts` | Pipeline scripts only: `shellcheck` on each script as the operator composes it (skipped when `shellcheck` is not installed) and the script behaviour tests, which run the scripts under `dash`/`bash` with stub tools | | `make fmt vet` | `go fmt` / `go vet` | | `make docker-build` | Operator image (`IMG`, default `ghcr.io/code2z/karkive:dev`) | | `make install` / `uninstall` | Apply / delete CRDs | CI: -- **CI** (`ci.yaml`, pushes to `main`, tags `v*` and PRs; `docs/` changes skip it): `make generate manifests fmt vet test`, failing on a dirty tree, then builds the `linux/amd64` operator image and lints the chart. Pushes to `main` publish `ghcr.io/code2z/karkive:latest`, `main` and `sha-`; tags `v*` publish semver tags and push the chart to `oci://ghcr.io/code2z/charts`. +- **CI** (`ci.yaml`, pushes to `main`, tags `v*` and PRs; `docs/` changes skip it): `make generate manifests fmt vet test`, failing on a dirty tree, with `shellcheck` required, then builds the `linux/amd64` operator image and lints the chart. Pushes to `main` publish `ghcr.io/code2z/karkive:latest`, `main` and `sha-`; tags `v*` publish semver tags and push the chart to `oci://ghcr.io/code2z/charts`. - **Runners** (`runners.yaml`): builds `karkive-runner-` only when `runner//` (or the shared rclone installer) changes. The tag comes from `runner//TAG`, `-rclone-r`. A published tag is never overwritten, so bump a version or the `-r` revision with every Dockerfile change, then update `internal/config/config.go` and `defaults.runnerImages` in `values.yaml`. - **Pages** (`pages.yaml`): deploys `docs/` to [karkive.ir](https://karkive.ir). diff --git a/TODO.md b/TODO.md index bc88463..5a45221 100644 --- a/TODO.md +++ b/TODO.md @@ -39,7 +39,7 @@ ## Tests -- [ ] envtest for CronJob apply; shellcheck + bats for pipeline scripts +- [ ] envtest for CronJob apply ## Done @@ -116,6 +116,7 @@ - [x] The Stream scratch check does the byte arithmetic in bash, not awk: the mawk in the redis runner printed free space above 2^31 as `5.23745e+10`, so Redis restores skipped the check - [x] Make S3 sync optional (`spec.s3.enabled`, default true). When false: skip the `s3-sync` container, do not require S3 secret keys or endpoint/bucket. Encrypt still writes `retained/` on the PVC. - [x] Pick the latest restore object by S3 LastModified (rclone `lsf --format tp`), not by name. Stream object names carry seconds +- [x] Script checks in Go instead of bats: `TestShellcheck` lints each script as the operator composes it (helper + stage body, `sh` for Stage and `bash` for Stream) and maps findings back to the source file and line; CI requires shellcheck. Behaviour tests run the shared helpers under `dash`/`bash` with stub tools (step markers, `.step-failed` on error, log file, `truthy`, zstd level, decompress by suffix, `s3_latest` by modification time, best-effort `s3_prune`) ### Speed and size (Stream mode) diff --git a/internal/pipeline/helpers_test.go b/internal/pipeline/helpers_test.go new file mode 100644 index 0000000..6f8ead0 --- /dev/null +++ b/internal/pipeline/helpers_test.go @@ -0,0 +1,212 @@ +package pipeline + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// runHelpers runs body after a helper script under shell, with stub commands first on PATH. Each stub is a /bin/sh script body. +func runHelpers(t *testing.T, shell, helper, body string, env map[string]string, stubs map[string]string) (string, error) { + t.Helper() + sh, err := exec.LookPath(shell) + if err != nil { + t.Skipf("%s not found", shell) + } + bin := t.TempDir() + for name, script := range stubs { + if err := os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\n"+script+"\n"), 0o755); err != nil { + t.Fatal(err) + } + } + cmd := exec.Command(sh, "-c", helper+"\n"+body+"\n") + cmd.Env = []string{"PATH=" + bin + ":" + os.Getenv("PATH")} + for k, v := range env { + cmd.Env = append(cmd.Env, k+"="+v) + } + out, err := cmd.CombinedOutput() + return string(out), err +} + +// stageShell is the /bin/sh of the Debian-based images (dash), or sh where dash is missing. +func stageShell(t *testing.T) string { + t.Helper() + if _, err := exec.LookPath("dash"); err == nil { + return "dash" + } + return "sh" +} + +func exitCode(err error) int { + if err == nil { + return 0 + } + if e, ok := err.(*exec.ExitError); ok { + return e.ExitCode() + } + return -1 +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func TestStagePipelineInitMarksFailureOnNonZeroExit(t *testing.T) { + for _, tc := range []struct { + exit string + wantFailed bool + }{{"exit 3", true}, {"exit 0", false}} { + work := t.TempDir() + _, err := runHelpers(t, stageShell(t), CommonScript(), "pipeline_init\n"+tc.exit, map[string]string{"WORKDIR": work}, nil) + if tc.wantFailed && exitCode(err) != 3 { + t.Errorf("%s: exit %d, want 3", tc.exit, exitCode(err)) + } + if got := fileExists(filepath.Join(work, ".step-failed")); got != tc.wantFailed { + t.Errorf("%s: .step-failed written=%v, want %v", tc.exit, got, tc.wantFailed) + } + } +} + +func TestStagePipelineInitNeedsADirectory(t *testing.T) { + out, err := runHelpers(t, stageShell(t), CommonScript(), "pipeline_init\necho after", nil, nil) + if exitCode(err) != 1 || strings.Contains(out, "after") || !strings.Contains(out, "STEP_DIR, DATA_DIR, or WORKDIR required") { + t.Errorf("exit %d, output:\n%s", exitCode(err), out) + } +} + +func TestStageUnknownEncryptionMethodFails(t *testing.T) { + out, err := runHelpers(t, stageShell(t), CommonScript(), "echo after", map[string]string{"ENCRYPTION_METHOD": "rot13"}, nil) + if exitCode(err) != 1 || strings.Contains(out, "after") || !strings.Contains(out, "unknown ENCRYPTION_METHOD rot13") { + t.Errorf("exit %d, output:\n%s", exitCode(err), out) + } +} + +func TestStageWaitForReturnsOnMarker(t *testing.T) { + work := t.TempDir() + if err := os.WriteFile(filepath.Join(work, ".step-dump-done"), nil, 0o644); err != nil { + t.Fatal(err) + } + out, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init +wait_for "$WORKDIR/.step-dump-done" dump +echo after`, map[string]string{"WORKDIR": work}, map[string]string{"sleep": "exit 0"}) + if err != nil || !strings.Contains(out, "after") { + t.Errorf("err=%v, output:\n%s", err, out) + } +} + +func TestStageWaitForAbortsWhenAPeerFailed(t *testing.T) { + work := t.TempDir() + if err := os.WriteFile(filepath.Join(work, ".step-failed"), nil, 0o644); err != nil { + t.Fatal(err) + } + out, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init +wait_for "$WORKDIR/.step-dump-done" dump +echo after`, map[string]string{"WORKDIR": work}, map[string]string{"sleep": "exit 0"}) + if exitCode(err) != 1 || strings.Contains(out, "after") || !strings.Contains(out, "peer stage failed") { + t.Errorf("exit %d, output:\n%s", exitCode(err), out) + } +} + +func TestStageAlreadyDoneExitSkipsWork(t *testing.T) { + work := t.TempDir() + marker := filepath.Join(work, ".step-fetch-done") + if err := os.WriteFile(marker, nil, 0o644); err != nil { + t.Fatal(err) + } + out, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init +already_done_exit "$MARKER" fetch +echo work`, map[string]string{"WORKDIR": work, "MARKER": marker}, nil) + if err != nil || strings.Contains(out, "work") { + t.Errorf("err=%v, output:\n%s", err, out) + } + if fileExists(filepath.Join(work, ".step-failed")) { + t.Error("a skipped stage must not write .step-failed") + } +} + +func TestStageLogFileOnTheVolume(t *testing.T) { + root := t.TempDir() + for _, tc := range []struct { + enabled string + want bool + }{{"true", true}, {"yes", true}, {"1", true}, {"false", false}, {"", false}} { + logFile := filepath.Join(root, "logs", "pod.log") + _ = os.Remove(logFile) + _, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init +log "hello"`, map[string]string{"WORKDIR": filepath.Join(root, "pod"), "WORKDIR_ROOT": root, "HOSTNAME": "pod", "LOG_FILE_ENABLED": tc.enabled}, nil) + if err != nil { + t.Fatalf("LOG_FILE_ENABLED=%q: %v", tc.enabled, err) + } + b, _ := os.ReadFile(logFile) + if got := strings.Contains(string(b), "hello"); got != tc.want { + t.Errorf("LOG_FILE_ENABLED=%q: logged to file=%v, want %v", tc.enabled, got, tc.want) + } + } +} + +func TestStreamTruthy(t *testing.T) { + out, err := runHelpers(t, "bash", streamCommon(t), `for v in 1 yes YES true TRUE 0 no false True ""; do + if truthy "$v"; then echo "$v=y"; else echo "$v=n"; fi +done`, nil, nil) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + want := "1=y\nyes=y\nYES=y\ntrue=y\nTRUE=y\n0=n\nno=n\nfalse=n\nTrue=n\n=n\n" + if out != want { + t.Errorf("got:\n%s\nwant:\n%s", out, want) + } +} + +func TestStreamZstdLevelFallsBackToThree(t *testing.T) { + for in, want := range map[string]string{"": "3", "9": "9", "19": "19", "-1": "3", "fast": "3", "3 ; rm": "3"} { + out, err := runHelpers(t, "bash", streamCommon(t), "zstd_level", map[string]string{"COMPRESSION_LEVEL": in}, nil) + if err != nil || strings.TrimSpace(out) != want { + t.Errorf("COMPRESSION_LEVEL=%q: got %q (err %v), want %q", in, out, err, want) + } + } +} + +func TestStreamDecompressBySuffix(t *testing.T) { + stubs := map[string]string{ + "zstd": "cat >/dev/null; echo zstd", + "pigz": "exit 1", // missing pigz: falls back to gzip + "gzip": "cat >/dev/null; echo gzip", + } + for obj, want := range map[string]string{ + "mysqldump-db-2026.sql.zst.gpg": "zstd", + "redis-2026.rdb.zst.age": "zstd", + "mysqldump-db-2026.sql.gz.gpg": "gzip", + "pg_dump-db-2026.dump.gpg": "raw", + } { + out, err := runHelpers(t, "bash", streamCommon(t), `echo raw | decompress_stream "$OBJ"`, map[string]string{"OBJ": obj}, stubs) + if err != nil || strings.TrimSpace(out) != want { + t.Errorf("%s: got %q (err %v), want %q", obj, out, err, want) + } + } +} + +func TestStreamS3LatestByModTimeNotName(t *testing.T) { + stubs := map[string]string{"rclone": `printf '%s\n' '2026-12-02 03:00:00|pg_dump-app-2026-11-30-03-00-00.dump.gpg' '2026-12-01 03:00:00|pg_dump-app-2026-12-01-03-00-00.dump.gpg'`} + out, err := runHelpers(t, "bash", streamCommon(t), `S3_PREFIX=s3:bucket/app +s3_latest 'pg_dump-*'`, nil, stubs) + if err != nil || strings.TrimSpace(out) != "pg_dump-app-2026-11-30-03-00-00.dump.gpg" { + t.Errorf("got %q (err %v)", out, err) + } +} + +func TestStreamS3PruneIsBestEffort(t *testing.T) { + run := t.TempDir() + stubs := map[string]string{"rclone": `case "$1" in + lsf) echo "access denied" >&2; exit 1 ;; + *) echo "unexpected rclone $1" >&2; exit 2 ;; +esac`} + out, err := runHelpers(t, "bash", streamCommon(t), `S3_PREFIX=s3:bucket/app +s3_prune 'pg_dump-*' +echo after`, map[string]string{"RUN_DIR": run}, stubs) + if err != nil || !strings.Contains(out, "WARN: listing for prune failed") || !strings.Contains(out, "access denied") || !strings.Contains(out, "after") || strings.Contains(out, "unexpected") { + t.Errorf("err=%v, output:\n%s", err, out) + } +} diff --git a/internal/pipeline/scripts/backup/compress.sh b/internal/pipeline/scripts/backup/compress.sh index eb5e913..6afc8f8 100644 --- a/internal/pipeline/scripts/backup/compress.sh +++ b/internal/pipeline/scripts/backup/compress.sh @@ -1,6 +1,6 @@ set -eu umask 0002 -STAGE=compress +STAGE='compress' # Shared PVC is reused across Jobs; scope scratch to this pod # so peers never see stale .step-* markers from a prior run. DATA_ROOT="${DATA_DIR:-${PGDUMP_DIR:?DATA_DIR or PGDUMP_DIR required}}" @@ -16,6 +16,8 @@ case "${DUMP_PREFIX}" in pvcdump) PLAIN_GLOB='pvcdump-*.tar' ;; *) PLAIN_GLOB='pg_dump-*.pgdump' ;; esac +# PLAIN_GLOB is a glob and must expand. +# shellcheck disable=SC2086 ls "${DATA_DIR}"/${PLAIN_GLOB} >/dev/null 2>&1 || { log "ERROR: no ${PLAIN_GLOB} after dump marker" >&2 mark_failed diff --git a/internal/pipeline/scripts/backup/encrypt.sh b/internal/pipeline/scripts/backup/encrypt.sh index 715327e..89a3d25 100644 --- a/internal/pipeline/scripts/backup/encrypt.sh +++ b/internal/pipeline/scripts/backup/encrypt.sh @@ -16,6 +16,8 @@ case "${DUMP_PREFIX}" in pvcdump) GZ_GLOB='pvcdump-*.tar.gz' ;; *) GZ_GLOB='pg_dump-*.pgdump.gz' ;; esac +# GZ_GLOB is a glob and must expand. +# shellcheck disable=SC2086 ls "${DATA_DIR}"/${GZ_GLOB} >/dev/null 2>&1 || { log "ERROR: no ${GZ_GLOB} after compress marker" >&2 mark_failed diff --git a/internal/pipeline/scripts/common.sh b/internal/pipeline/scripts/common.sh index 2207635..9e73f98 100644 --- a/internal/pipeline/scripts/common.sh +++ b/internal/pipeline/scripts/common.sh @@ -1,3 +1,5 @@ +# shellcheck disable=SC3028 +# SC3028 above, for every Stage script: HOSTNAME is not a POSIX sh variable, but the container runtime sets it to the pod name, which names each pod's scratch directory. # Shared pipeline helpers. Callers set STAGE and DATA_DIR (backup) or WORKDIR # (restore), then pipeline_init. @@ -55,7 +57,7 @@ pipeline_init() { chmod 666 "${LOG_FILE}" 2>/dev/null || true fi fi - trap 'ec=$?; [ "$ec" -eq 0 ] || mark_failed' EXIT + trap '[ "$?" -eq 0 ] || mark_failed' EXIT } prune_pipeline_logs() { diff --git a/internal/pipeline/scripts/restore/mysqlrestore.sh b/internal/pipeline/scripts/restore/mysqlrestore.sh index 4ab7508..d57a07c 100644 --- a/internal/pipeline/scripts/restore/mysqlrestore.sh +++ b/internal/pipeline/scripts/restore/mysqlrestore.sh @@ -80,6 +80,8 @@ FILTERED="${WORKDIR}/dump.filtered.sql" echo "SET SESSION unique_checks=0;" echo "SET SESSION foreign_key_checks=0;" echo "SET SESSION autocommit=0;" + # The backticks quote MariaDB identifiers; nothing here should expand. + # shellcheck disable=SC2016 sed -E \ -e '/^SET[[:space:]]+@@GLOBAL\.GTID_PURGED/d' \ -e '/^SET[[:space:]]+@@SESSION\.SQL_LOG_BIN/d' \ diff --git a/internal/pipeline/scripts/stream/common.sh b/internal/pipeline/scripts/stream/common.sh index aac2931..9c57f51 100644 --- a/internal/pipeline/scripts/stream/common.sh +++ b/internal/pipeline/scripts/stream/common.sh @@ -44,6 +44,8 @@ stream_init() { : > "${LOG_FILE}" fi encryption_init + # rc is assigned inside the trap string. + # shellcheck disable=SC2154 trap 'rc=$?; rm -rf "${RUN_DIR}"; [ "$rc" -eq 0 ] || log "ERROR: failed with exit ${rc}"; exit "$rc"' EXIT } diff --git a/internal/pipeline/scripts/stream/restore.sh b/internal/pipeline/scripts/stream/restore.sh index a466da6..77b157b 100644 --- a/internal/pipeline/scripts/stream/restore.sh +++ b/internal/pipeline/scripts/stream/restore.sh @@ -211,6 +211,8 @@ restore_mariadb() { { echo "SET SESSION unique_checks=0; SET SESSION foreign_key_checks=0; SET SESSION autocommit=0;" # Stage-mode dumps use --databases (CREATE DATABASE + USE ): drop those so the data lands in the target name. + # The backticks quote MariaDB identifiers; nothing here should expand. + # shellcheck disable=SC2016 fetch | decompress_stream "${OBJ}" | sed -E \ -e '/^CREATE DATABASE /d' \ -e '/^USE `[^`]*`;$/d' \ @@ -324,6 +326,8 @@ redis_push_to_target() { t=$(date +%s) log "db${db}: pushing ${n} keys to ${REDIS_HOST}:${REDIS_PORT:-6379} with MIGRATE" if ! { + # RESP framing: $6 is a literal bulk-string length, not a variable. + # shellcheck disable=SC2016 printf '*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n' "${#db}" "${db}" local_redis -n "${db}" --scan --count 1000 < /dev/null | redis_migrate_resp "${db}" } | local_redis --pipe --pipe-timeout 0 > "${RUN_DIR}/push.out" 2> "${RUN_DIR}/push.err"; then diff --git a/internal/pipeline/shellcheck_test.go b/internal/pipeline/shellcheck_test.go new file mode 100644 index 0000000..e378e39 --- /dev/null +++ b/internal/pipeline/shellcheck_test.go @@ -0,0 +1,185 @@ +package pipeline + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path" + "sort" + "strings" + "testing" +) + +// requireShellcheckEnv makes TestShellcheck fail instead of skip when shellcheck is missing. CI sets it. +const requireShellcheckEnv = "KARKIVE_REQUIRE_SHELLCHECK" + +// usageCodes depend on what the rest of the script uses: a variable assigned in a shared helper but read by only some stages (SC2034), or a helper function that only some stages call (SC2317, SC2329). In a helper they are reported only when every composed script triggers them, that is when no stage uses the thing at all. +var usageCodes = map[int]bool{2034: true, 2317: true, 2329: true} + +type scComment struct { + Line int `json:"line"` + Column int `json:"column"` + Level string `json:"level"` + Code int `json:"code"` + Message string `json:"message"` +} + +func (c scComment) at(file string, line int) string { + return fmt.Sprintf("%s:%d:%d: %s SC%d: %s", file, line, c.Column, c.Level, c.Code, c.Message) +} + +// scriptFamily is one helper plus the bodies the operator puts after it. +type scriptFamily struct { + dialect string // shellcheck --shell: Stage scripts run under /bin/sh (dash or BusyBox ash), Stream scripts under bash + common string // helper file, as reported in findings + bodies []familyBody +} + +type familyBody struct { + file string // body file, as reported in findings + composed string // what the container runs + body string +} + +// TestShellcheck lints every embedded script the way the operator runs it: a Stage script is common.sh plus the stage body under /bin/sh, a Stream script is stream/common.sh plus backup.sh or restore.sh under bash. Findings point at the source file and line. runner/install-rclone.sh is checked on its own. +func TestShellcheck(t *testing.T) { + sc, err := exec.LookPath("shellcheck") + if err != nil { + if os.Getenv(requireShellcheckEnv) != "" { + t.Fatalf("shellcheck not found and %s is set", requireShellcheckEnv) + } + t.Skipf("shellcheck not found; set %s to fail instead", requireShellcheckEnv) + } + + var findings []string + for _, fam := range scriptFamilies(t) { + findings = append(findings, checkFamily(t, sc, fam)...) + } + + rclone, err := os.ReadFile("../../runner/install-rclone.sh") + if err != nil { + t.Fatal(err) + } + for _, c := range runShellcheck(t, sc, "sh", string(rclone)) { + findings = append(findings, c.at("runner/install-rclone.sh", c.Line)) + } + + sort.Strings(findings) + for _, f := range findings { + t.Error(f) + } +} + +func scriptFamilies(t *testing.T) []scriptFamily { + t.Helper() + stage := scriptFamily{dialect: "sh", common: "scripts/common.sh"} + for _, dir := range []struct { + fsys fs.FS + name string + compose func(string) (string, error) + }{ + {backupScripts, "scripts/backup", BackupScript}, + {restoreScripts, "scripts/restore", RestoreScript}, + } { + for _, name := range shellFiles(t, dir.fsys, dir.name) { + composed, err := dir.compose(name) + if err != nil { + t.Fatal(err) + } + body, err := fs.ReadFile(dir.fsys, path.Join(dir.name, name)) + if err != nil { + t.Fatal(err) + } + stage.bodies = append(stage.bodies, familyBody{file: path.Join(dir.name, name), composed: composed, body: string(body)}) + } + } + + stream := scriptFamily{dialect: "bash", common: "scripts/stream/common.sh"} + for _, name := range shellFiles(t, streamScripts, "scripts/stream") { + if name == "common.sh" { + continue + } + composed, err := StreamScript(name) + if err != nil { + t.Fatal(err) + } + body, err := streamScripts.ReadFile("scripts/stream/" + name) + if err != nil { + t.Fatal(err) + } + stream.bodies = append(stream.bodies, familyBody{file: "scripts/stream/" + name, composed: composed, body: string(body)}) + } + + if len(stage.bodies) == 0 || len(stream.bodies) == 0 { + t.Fatalf("found %d Stage and %d Stream scripts", len(stage.bodies), len(stream.bodies)) + } + return []scriptFamily{stage, stream} +} + +func shellFiles(t *testing.T, fsys fs.FS, dir string) []string { + t.Helper() + entries, err := fs.ReadDir(fsys, dir) + if err != nil { + t.Fatal(err) + } + var names []string + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".sh") { + names = append(names, e.Name()) + } + } + return names +} + +// checkFamily lints each composed script and maps every finding back to the helper or the body. A helper finding shows up once per composed script, so it is reported once, and usage-dependent ones only when all of them have it. +func checkFamily(t *testing.T, sc string, fam scriptFamily) []string { + t.Helper() + var out []string + inCommon := map[scComment]int{} + for _, b := range fam.bodies { + if !strings.HasSuffix(b.composed, b.body) { + t.Fatalf("%s: composed script does not end with the body", b.file) + } + prefixLines := strings.Count(b.composed[:len(b.composed)-len(b.body)], "\n") + for _, c := range runShellcheck(t, sc, fam.dialect, b.composed) { + if c.Line > prefixLines { + out = append(out, c.at(b.file, c.Line-prefixLines)) + } else { + inCommon[c]++ + } + } + } + for c, n := range inCommon { + if usageCodes[c.Code] && n < len(fam.bodies) { + continue + } + out = append(out, c.at(fam.common, c.Line)) + } + return out +} + +func runShellcheck(t *testing.T, sc, dialect, script string) []scComment { + t.Helper() + cmd := exec.Command(sc, "--format=json1", "--shell="+dialect, "-") + cmd.Stdin = strings.NewReader(script) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + if err := cmd.Run(); err != nil { + // Exit 1 means findings; anything else is a shellcheck error. + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 { + t.Fatalf("shellcheck: %v\n%s", err, stderr.String()) + } + } + var res struct { + Comments []scComment `json:"comments"` + } + if err := json.Unmarshal(stdout.Bytes(), &res); err != nil { + t.Fatalf("shellcheck output: %v\n%s", err, stdout.String()) + } + return res.Comments +}