diff --git a/README.md b/README.md
index b26535e1..a6f9549e 100644
--- a/README.md
+++ b/README.md
@@ -1314,8 +1314,8 @@ had regressed.
```bash
scripts/conformance/rubyspec/run.sh # judge against the baseline
UPDATE_BASELINE=1 scripts/conformance/rubyspec/run.sh # re-record after a win
-# point it at an existing corpus instead of cloning:
-SPECDIR=/path/to/ruby-spec CACHE=/path/to/ruby-spec scripts/conformance/rubyspec/run.sh
+# point it at an existing ruby/spec clone (checked out at the pinned commit):
+SPECDIR=/path/to/ruby-spec scripts/conformance/rubyspec/run.sh
```
### CI layering
diff --git a/scripts/conformance/rubyspec/README.md b/scripts/conformance/rubyspec/README.md
index 19b876cf..d6dba7a0 100644
--- a/scripts/conformance/rubyspec/README.md
+++ b/scripts/conformance/rubyspec/README.md
@@ -77,18 +77,30 @@ ratchet cannot be mistaken for a failing one.
## Usage
```sh
-# Run the ratchet (clones the pinned corpus to /tmp on first run):
+# Run the ratchet (clones the pinned corpus into the user cache directory on
+# first run — ~/Library/Caches/rbgo/rubyspec-corpus on macOS,
+# ${XDG_CACHE_HOME:-~/.cache}/rbgo/rubyspec-corpus elsewhere):
scripts/conformance/rubyspec/run.sh
# Re-record the baseline after a genuine improvement:
UPDATE_BASELINE=1 scripts/conformance/rubyspec/run.sh
-# Point at an existing checkout instead of cloning:
+# Point at an existing ruby/spec clone instead (it is CHECKED OUT at SPEC_SHA):
SPECDIR=~/src/ruby-spec scripts/conformance/rubyspec/run.sh
```
Environment overrides: `RBGO`, `SPECDIR`, `CACHE`, `JOBS`, `TIMEOUT`.
+The corpus is put in place by [`cmd/specpin`](cmd/specpin/main.go) (#857). It
+prints `corpus:
@ ` with the commit **read back from git** after
+checkout — not the `SPEC_SHA` constant, so a cache left at another commit can no
+longer be reported as the pinned one. It never deletes a directory: one that is
+neither empty nor a git checkout of its own (at its top level) is refused, where
+the script used to `rm -rf` whatever `CACHE` named. A `SPECDIR` clone already
+at `SPEC_SHA` is used as is, offline; one at another commit is moved with
+`git checkout --force` only if its `origin` is `SPEC_URL` exactly, and refused
+otherwise — so do not point it at a tree with work in progress.
+
## Re-recording the baseline
When a change improves conformance, regenerate `BASELINE` in the same PR
@@ -226,7 +238,8 @@ a NoMethodError expectation it asks a real rbgo whether the method exists at all
no instance is constructed), and reports the ones that do not.
```bash
-go run ./scripts/conformance/rubyspec/cmd/phantom -root /tmp/rubyspec-corpus -rbgo /tmp/rbgo-rubyspec
+# the corpus run.sh pinned (macOS path; ~/.cache/rbgo/rubyspec-corpus on Linux)
+go run ./scripts/conformance/rubyspec/cmd/phantom -root ~/Library/Caches/rbgo/rubyspec-corpus -rbgo /tmp/rbgo-rubyspec
```
Measured on `main` after #849: **59 attributable expectations over 2206 spec
@@ -270,7 +283,7 @@ re-recorded — a static read, needing no sweep, and so runnable on a loaded
machine where a sweep is not:
```bash
-go run ./scripts/conformance/rubyspec/cmd/guards -root /tmp/rubyspec-corpus -list
+go run ./scripts/conformance/rubyspec/cmd/guards -root ~/Library/Caches/rbgo/rubyspec-corpus -list
```
It separates the two shapes, because they do opposite things:
diff --git a/scripts/conformance/rubyspec/cmd/specpin/main.go b/scripts/conformance/rubyspec/cmd/specpin/main.go
new file mode 100644
index 00000000..2d6bb2df
--- /dev/null
+++ b/scripts/conformance/rubyspec/cmd/specpin/main.go
@@ -0,0 +1,280 @@
+// Copyright (c) the go-embedded-ruby/ruby authors
+//
+// SPDX-License-Identifier: BSD-3-Clause
+
+// Command specpin puts the ruby/spec corpus at exactly one commit, in a
+// directory that survives a reboot, and says which commit it actually holds
+// (#857).
+//
+// specpin -sha <40-hex> -url [-cache ]
+//
+// It prints the corpus directory on stdout, for run.sh to use, and
+// `corpus: @ ` on stderr.
+//
+// Why it is a program and not four lines of run.sh. The four lines it replaces
+// had three defects, and the third is the reason this is written in a language
+// that can be tested:
+//
+// 1. The cache defaulted to /tmp/rubyspec-corpus, which macOS purges and most
+// Linux distributions empty at boot. The corpus a baseline was measured
+// against was not a durable artefact.
+//
+// 2. ⛔ A cache that existed was reused WITHOUT checking its commit, and the
+// log then printed `corpus: @ $SPEC_SHA` — the CONSTANT, not what was
+// checked out. A cache from another SPEC_SHA reads as a sweep with files
+// added or missing, and cmd/ratchet's MISSING FROM THE SWEEP is the very
+// verdict a regression produces. The line meant to say which corpus was
+// measured could only ever say the one that was asked for.
+//
+// 3. ⛔⛔ `rm -rf "$CACHE"` ran whenever "$SPECDIR/language" was absent. That
+// condition is true of almost every directory on a machine. `CACHE=$HOME`,
+// one slip on a command line, met it and deleted the home directory.
+//
+// So: the commit is READ BACK from git after every path that can change it, a
+// directory that is not already a ruby/spec checkout of its own is never
+// deleted, and only an empty or absent one is cloned into.
+//
+// The default directory is os.UserCacheDir()/rbgo/rubyspec-corpus —
+// ~/Library/Caches on macOS, $XDG_CACHE_HOME or ~/.cache elsewhere — which is
+// what #857 suggested, from the one place that already knows each platform's
+// answer.
+//
+// It uses `flag`, as the eight commands beside it do, rather than cobra: this
+// module is the interpreter that other programs embed, and a dependency added
+// for a script would be added to every one of them.
+//
+// Exit status: 0 the corpus is at -sha; 2 it is not, or could not be made so,
+// or the directory was refused. There is no 1: there is no verdict here to
+// disagree with, only a precondition that holds or does not.
+package main
+
+import (
+ "bytes"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+var osExit = os.Exit
+
+func main() {
+ osExit(run(os.Args[1:], os.Stdout, os.Stderr))
+}
+
+func run(args []string, stdout, stderr io.Writer) int {
+ fs := flag.NewFlagSet("specpin", flag.ContinueOnError)
+ fs.SetOutput(stderr)
+ sha := fs.String("sha", "", "the full 40-hex commit the corpus must be at (required)")
+ url := fs.String("url", "", "where to clone or fetch it from (required)")
+ cache := fs.String("cache", "", "the corpus directory (default: /rbgo/rubyspec-corpus)")
+ if err := fs.Parse(args); err != nil {
+ return 2
+ }
+ if *sha == "" || *url == "" {
+ fmt.Fprintln(stderr, "specpin: -sha and -url are required")
+ return 2
+ }
+ dir := *cache
+ if dir == "" {
+ base, err := os.UserCacheDir()
+ if err != nil {
+ fmt.Fprintf(stderr, "specpin: no user cache directory on this machine (%v); name one with -cache\n", err)
+ return 2
+ }
+ dir = filepath.Join(base, "rbgo", "rubyspec-corpus")
+ }
+ got, err := pin(dir, *sha, *url)
+ if err != nil {
+ fmt.Fprintf(stderr, "specpin: %v\n", err)
+ return 2
+ }
+ fmt.Fprintf(stderr, "corpus: %s @ %s\n", dir, got)
+ fmt.Fprintln(stdout, dir)
+ return 0
+}
+
+var fullSHA = regexp.MustCompile(`^[0-9a-f]{40}$`)
+
+// pin makes dir a ruby/spec checkout at sha and returns the commit it READ
+// BACK, which is the only value the caller may report.
+//
+// ⛔ A short or mistyped SHA is refused before anything touches the disk. A
+// prefix would be resolved by git against whatever the clone happens to hold,
+// and an identifier reconstructed from a prefix has already cost this fleet
+// four wrong measurements.
+func pin(dir, sha, url string) (string, error) {
+ if !fullSHA.MatchString(sha) {
+ return "", fmt.Errorf("-sha must be a full 40-character lowercase hex commit, got %q", sha)
+ }
+
+ fi, err := os.Stat(dir)
+ switch {
+ case errors.Is(err, fs.ErrNotExist):
+ if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
+ return "", err
+ }
+ if err := git("", "clone", "--quiet", "--filter=blob:none", url, dir); err != nil {
+ return "", fmt.Errorf("clone %s into %s failed (offline?): %w", url, dir, err)
+ }
+ case err != nil:
+ return "", err
+ case !fi.IsDir():
+ return "", fmt.Errorf("%s exists and is not a directory; refusing to touch it", dir)
+ default:
+ own, err := ownCheckout(dir)
+ if err != nil {
+ return "", err
+ }
+ if !own {
+ empty, err := isEmpty(dir)
+ if err != nil {
+ return "", err
+ }
+ if !empty {
+ // ⛔ The line that replaced `rm -rf "$CACHE"`. A directory that is
+ // not a checkout of its own and holds anything at all is someone's
+ // directory, and the right answer to a mistyped CACHE is to say so.
+ return "", fmt.Errorf("%s is not empty and is not a git checkout of its own; refusing to delete or reuse it — point -cache at an empty directory or at an existing ruby/spec clone", dir)
+ }
+ if err := git("", "clone", "--quiet", "--filter=blob:none", url, dir); err != nil {
+ return "", fmt.Errorf("clone %s into %s failed (offline?): %w", url, dir, err)
+ }
+ }
+ }
+
+ if head, err := revParse(dir); err == nil && head == sha {
+ // Already there. Nothing is fetched, so a machine with the right corpus
+ // and no network still measures.
+ return checkTree(dir, head)
+ }
+
+ // ⛔ Everything below MOVES the checkout — a fetch writes its refs, and
+ // `checkout --force` discards its work tree's changes. Being a checkout of
+ // its own is not enough for that: any clone is, and SPECDIR pointed at the
+ // wrong one (the first run of this very wiring was pointed at a scratch
+ // repository) would have it fetched into and overwritten. So it must be a
+ // clone OF -url. Read raw from the config, not through `remote get-url`,
+ // which applies the host's url.insteadOf rewrites and would refuse a clone
+ // this command made itself.
+ //
+ // The early return above is NOT held to this: a tree already at sha and
+ // shaped like ruby/spec is the corpus by content, whatever it was cloned
+ // from, and nothing there is moved.
+ if origin, _ := gitOut(dir, "config", "--get", "remote.origin.url"); origin != url {
+ return "", fmt.Errorf("%s is at another commit and its origin is %q, not %s; refusing to fetch into it or check it out — point -cache at an empty directory or at a clone of %s", dir, origin, url, url)
+ }
+
+ // Fetching by SHA is the cheap path and GitHub serves it; a server that
+ // refuses a SHA want gets an ordinary fetch of every ref instead.
+ if err := git(dir, "fetch", "--quiet", "--filter=blob:none", "origin", sha); err != nil {
+ if err2 := git(dir, "fetch", "--quiet", "--filter=blob:none", "origin"); err2 != nil {
+ return "", fmt.Errorf("fetch of %s into %s failed (offline?): %v; %w", sha, dir, err, err2)
+ }
+ }
+ if err := git(dir, "checkout", "--quiet", "--force", sha); err != nil {
+ return "", fmt.Errorf("checkout of %s in %s failed — is it a commit of %s? %w", sha, dir, url, err)
+ }
+ // ONE refusal for "HEAD is not where it was asked to be", whether git could
+ // not say where HEAD is or said somewhere else. They were two arms, and a
+ // mutation sweep showed the first held nothing: a failed read leaves head
+ // empty, which is never sha, so the second refused anyway — with a worse
+ // message. The read error now travels in the one that remains.
+ head, err := revParse(dir)
+ if err != nil || head != sha {
+ return "", fmt.Errorf("%s is at %q after checking out %s (read back: %v) — a post-checkout hook, or something else, moved it", dir, head, sha, err)
+ }
+ return checkTree(dir, head)
+}
+
+// checkTree refuses a commit that is not shaped like ruby/spec, so a -url that
+// points at the wrong repository fails here and not as a sweep of zero files.
+func checkTree(dir, head string) (string, error) {
+ for _, suite := range []string{"language", "core"} {
+ fi, err := os.Stat(filepath.Join(dir, suite))
+ if err != nil || !fi.IsDir() {
+ return "", fmt.Errorf("%s @ %s has no %s/ directory; this is not a ruby/spec checkout", dir, head, suite)
+ }
+ }
+ return head, nil
+}
+
+// ownCheckout reports whether dir is the TOP of a git work tree.
+//
+// ⛔ Not merely "inside one". A cache directory created under some other
+// repository — the interpreter's own clone, say — answers `git rev-parse HEAD`
+// with THAT repository's commit, and a fetch there would fetch into it. Only a
+// directory that is its own toplevel is ours to move.
+func ownCheckout(dir string) (bool, error) {
+ var out bytes.Buffer
+ cmd := exec.Command("git", "-C", dir, "rev-parse", "--show-toplevel")
+ cmd.Stdout = &out
+ if err := cmd.Run(); err != nil {
+ var exited *exec.ExitError
+ if errors.As(err, &exited) {
+ return false, nil // git ran and said: not a work tree
+ }
+ return false, fmt.Errorf("could not run git: %w", err)
+ }
+ // Compared as FILES, not as paths. A path comparison needs both sides made
+ // absolute and symlink-free first — macOS's /var is /private/var, and git
+ // answers with the resolved one — and every step of that normalisation is
+ // an error arm that cannot fire on a directory already stat'ed by the
+ // caller. A mutation sweep deleted all three and nothing failed, because
+ // nothing could. os.SameFile asks the filesystem the question directly.
+ //
+ // ⛔ The two Stat errors are discarded ON PURPOSE, and this is why it is
+ // safe: os.SameFile answers false for a nil FileInfo (it type-asserts, it
+ // does not dereference), and false is "not ours" — the refusing direction,
+ // in which the caller will not fetch into dir or clone over it. A sweep
+ // showed both `if err != nil` arms changing no answer at all; keeping them
+ // would keep two lines nothing can ever hold.
+ top, _ := os.Stat(strings.TrimSpace(out.String()))
+ here, _ := os.Stat(dir)
+ return os.SameFile(top, here), nil
+}
+
+func isEmpty(dir string) (bool, error) {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return false, err
+ }
+ return len(entries) == 0, nil
+}
+
+func revParse(dir string) (string, error) {
+ return gitOut(dir, "rev-parse", "HEAD")
+}
+
+// gitOut runs git in dir and returns its trimmed stdout.
+func gitOut(dir string, args ...string) (string, error) {
+ var out bytes.Buffer
+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
+ cmd.Stdout = &out
+ if err := cmd.Run(); err != nil {
+ return "", fmt.Errorf("git %s in %s: %w", strings.Join(args, " "), dir, err)
+ }
+ return strings.TrimSpace(out.String()), nil
+}
+
+func git(dir string, args ...string) error {
+ if dir != "" {
+ args = append([]string{"-C", dir}, args...)
+ }
+ var errb bytes.Buffer
+ cmd := exec.Command("git", args...)
+ cmd.Stderr = &errb
+ if err := cmd.Run(); err != nil {
+ if msg := strings.TrimSpace(errb.String()); msg != "" {
+ return fmt.Errorf("%w: %s", err, msg)
+ }
+ return err
+ }
+ return nil
+}
diff --git a/scripts/conformance/rubyspec/cmd/specpin/main_test.go b/scripts/conformance/rubyspec/cmd/specpin/main_test.go
new file mode 100644
index 00000000..a6b25d6b
--- /dev/null
+++ b/scripts/conformance/rubyspec/cmd/specpin/main_test.go
@@ -0,0 +1,362 @@
+// Copyright (c) the go-embedded-ruby/ruby authors
+//
+// SPDX-License-Identifier: BSD-3-Clause
+
+package main
+
+import (
+ "bytes"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// needGit skips when the host has no git at all. That is not a build failure
+// hidden as a skip (#687): this command's whole job is to drive git, and a host
+// without it cannot arrange any of these conditions.
+func needGit(t *testing.T) {
+ t.Helper()
+ if _, err := exec.LookPath("git"); err != nil {
+ t.Skip("no git on this host; specpin drives git and cannot be exercised without it")
+ }
+}
+
+func gitT(t *testing.T, dir string, args ...string) string {
+ t.Helper()
+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
+ cmd.Env = append(os.Environ(),
+ "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.invalid",
+ "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.invalid",
+ "GIT_CONFIG_NOSYSTEM=1",
+ )
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("git %v in %s: %v\n%s", args, dir, err, out)
+ }
+ return strings.TrimSpace(string(out))
+}
+
+func writeFile(t *testing.T, path, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// upstream builds a repository shaped like ruby/spec with two commits and
+// returns its path and both SHAs. The OLDER one is the pin target in most
+// rows, so a tool that merely cloned and stayed on the default branch would be
+// caught: the tip is not what was asked for.
+func upstream(t *testing.T) (url, older, tip string) {
+ t.Helper()
+ dir := filepath.Join(t.TempDir(), "spec")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ gitT(t, dir, "init", "--quiet", "--initial-branch=master")
+ writeFile(t, filepath.Join(dir, "language", "a_spec.rb"), "# one\n")
+ writeFile(t, filepath.Join(dir, "core", "b_spec.rb"), "# one\n")
+ gitT(t, dir, "add", "-A")
+ gitT(t, dir, "commit", "--quiet", "-m", "one")
+ older = gitT(t, dir, "rev-parse", "HEAD")
+ writeFile(t, filepath.Join(dir, "core", "c_spec.rb"), "# two\n")
+ gitT(t, dir, "add", "-A")
+ gitT(t, dir, "commit", "--quiet", "-m", "two")
+ tip = gitT(t, dir, "rev-parse", "HEAD")
+ return dir, older, tip
+}
+
+func TestAnAbsentCacheIsClonedAtTheAskedCommitNotTheTip(t *testing.T) {
+ needGit(t)
+ url, older, _ := upstream(t)
+ dir := filepath.Join(t.TempDir(), "cache", "rubyspec-corpus")
+
+ got, err := pin(dir, older, url)
+ if err != nil {
+ t.Fatalf("pin: %v", err)
+ }
+ if got != older {
+ t.Fatalf("pin reported %s, want %s", got, older)
+ }
+ if head := gitT(t, dir, "rev-parse", "HEAD"); head != older {
+ t.Fatalf("the checkout is at %s, want %s", head, older)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "core", "c_spec.rb")); err == nil {
+ t.Fatal("a file from the TIP is present, so the checkout is not at the asked commit")
+ }
+}
+
+// ⭐ #857's own case: a cache that exists, at the wrong commit. The old run.sh
+// reused it and printed the pinned SHA beside it.
+func TestACacheAtAnotherCommitIsMovedNotReused(t *testing.T) {
+ needGit(t)
+ url, older, tip := upstream(t)
+ dir := filepath.Join(t.TempDir(), "rubyspec-corpus")
+ gitT(t, filepath.Dir(dir), "clone", "--quiet", url, dir)
+ if head := gitT(t, dir, "rev-parse", "HEAD"); head != tip {
+ t.Fatalf("setup: the cache should start at the tip %s, is at %s", tip, head)
+ }
+
+ got, err := pin(dir, older, url)
+ if err != nil {
+ t.Fatalf("pin: %v", err)
+ }
+ if got != older {
+ t.Fatalf("pin reported %s, want %s", got, older)
+ }
+ if head := gitT(t, dir, "rev-parse", "HEAD"); head != older {
+ t.Fatalf("the cache stayed at %s; it had to move to %s", head, older)
+ }
+}
+
+// The accepting side: a cache already at the commit is used as is, with no
+// network. The URL here does not exist, so any fetch would fail the test.
+func TestACacheAlreadyAtTheCommitNeedsNoNetwork(t *testing.T) {
+ needGit(t)
+ url, _, tip := upstream(t)
+ dir := filepath.Join(t.TempDir(), "rubyspec-corpus")
+ gitT(t, filepath.Dir(dir), "clone", "--quiet", url, dir)
+
+ got, err := pin(dir, tip, filepath.Join(t.TempDir(), "no-such-remote"))
+ if err != nil {
+ t.Fatalf("pin of a cache already at the commit tried the network: %v", err)
+ }
+ if got != tip {
+ t.Fatalf("pin reported %s, want %s", got, tip)
+ }
+}
+
+// ⛔⛔ The line that replaced `rm -rf "$CACHE"`. A mistyped CACHE pointing at a
+// directory with anything in it must be refused, and what was in it must still
+// be there afterwards.
+func TestADirectoryThatIsNotACheckoutIsNeverDeleted(t *testing.T) {
+ needGit(t)
+ url, older, _ := upstream(t)
+ dir := t.TempDir() // stands for $HOME
+ precious := filepath.Join(dir, "thesis.tex")
+ writeFile(t, precious, "three years of work\n")
+
+ if _, err := pin(dir, older, url); err == nil {
+ t.Fatal("pin accepted a non-empty directory that is not a checkout")
+ }
+ b, err := os.ReadFile(precious)
+ if err != nil || string(b) != "three years of work\n" {
+ t.Fatalf("the directory's contents were touched: %v %q", err, b)
+ }
+}
+
+// ⛔ A cache directory INSIDE another repository answers `rev-parse HEAD` with
+// that repository's commit. It must not be mistaken for a checkout, and the
+// outer repository must not be fetched into or moved.
+func TestADirectoryInsideAnotherRepositoryIsNotTreatedAsTheCorpus(t *testing.T) {
+ needGit(t)
+ url, older, _ := upstream(t)
+ outer := t.TempDir()
+ gitT(t, outer, "init", "--quiet", "--initial-branch=main")
+ writeFile(t, filepath.Join(outer, "README"), "the interpreter\n")
+ writeFile(t, filepath.Join(outer, "cache", "keep"), "x\n")
+ gitT(t, outer, "add", "-A")
+ gitT(t, outer, "commit", "--quiet", "-m", "outer")
+ before := gitT(t, outer, "rev-parse", "HEAD")
+
+ if _, err := pin(filepath.Join(outer, "cache"), older, url); err == nil {
+ t.Fatal("pin accepted a non-empty subdirectory of another repository as the corpus")
+ }
+ if after := gitT(t, outer, "rev-parse", "HEAD"); after != before {
+ t.Fatalf("the OUTER repository moved from %s to %s", before, after)
+ }
+}
+
+// ⛔⛔ Found by the first end-to-end run of run.sh: SPECDIR named a scratch
+// directory that happened to be a git repository of its own, and specpin went
+// straight to `fetch`. It failed only because that repository had no origin.
+// Here the foreign repository is the worst case — it even HOLDS the asked
+// commit, so fetch and `checkout --force` would both have succeeded and thrown
+// its uncommitted work away. It must be refused, and left exactly as it was.
+func TestACheckoutOfAnotherRemoteIsNeitherFetchedIntoNorMoved(t *testing.T) {
+ needGit(t)
+ url, older, tip := upstream(t)
+ dir := filepath.Join(t.TempDir(), "someone-elses-clone")
+ gitT(t, filepath.Dir(dir), "clone", "--quiet", url, dir)
+ // The fork EXISTS and holds the commit. A first version of this test named
+ // a path with nothing at it, and passed with the guard deleted: the fetch
+ // failed on its own, and its message quoted the path the assertion looked
+ // for. Only a remote that would SERVE the commit shows what the guard stops.
+ fork := filepath.Join(t.TempDir(), "their-fork")
+ gitT(t, filepath.Dir(fork), "clone", "--quiet", "--bare", url, fork)
+ gitT(t, dir, "remote", "set-url", "origin", fork)
+ wip := filepath.Join(dir, "core", "c_spec.rb")
+ writeFile(t, wip, "# uncommitted work\n")
+
+ _, err := pin(dir, older, url)
+ if err == nil {
+ t.Fatal("pin moved a checkout whose origin is not -url")
+ }
+ if !strings.Contains(err.Error(), "their-fork") {
+ t.Fatalf("the refusal does not name the origin it found: %v", err)
+ }
+ if head := gitT(t, dir, "rev-parse", "HEAD"); head != tip {
+ t.Fatalf("HEAD moved from %s to %s", tip, head)
+ }
+ if b, err := os.ReadFile(wip); err != nil || string(b) != "# uncommitted work\n" {
+ t.Fatalf("the uncommitted work was discarded: %v %q", err, b)
+ }
+
+ // The other side: the same clone with its origin put back IS moved, so
+ // what refused above was the origin and nothing else.
+ gitT(t, dir, "remote", "set-url", "origin", url)
+ gitT(t, dir, "checkout", "--quiet", "--", ".")
+ if got, err := pin(dir, older, url); err != nil || got != older {
+ t.Fatalf("pin of a clone of -url = %q, %v; want %s", got, err, older)
+ }
+}
+
+func TestAnEmptyDirectoryIsClonedInto(t *testing.T) {
+ needGit(t)
+ url, older, _ := upstream(t)
+ dir := t.TempDir()
+ if got, err := pin(dir, older, url); err != nil || got != older {
+ t.Fatalf("pin into an empty directory = %q, %v; want %s", got, err, older)
+ }
+}
+
+func TestRefusals(t *testing.T) {
+ needGit(t)
+ url, older, _ := upstream(t)
+
+ t.Run("a short SHA is refused before the disk is touched", func(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "never-created")
+ if _, err := pin(dir, older[:7], url); err == nil {
+ t.Fatal("pin accepted a 7-character prefix")
+ }
+ if _, err := os.Stat(dir); err == nil {
+ t.Fatal("the directory was created for a SHA that was refused")
+ }
+ })
+ t.Run("a commit the remote does not have", func(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "c")
+ if _, err := pin(dir, strings.Repeat("ab", 20), url); err == nil {
+ t.Fatal("pin reported success for a commit that does not exist")
+ }
+ })
+ t.Run("a repository that is not shaped like ruby/spec", func(t *testing.T) {
+ other := filepath.Join(t.TempDir(), "other")
+ if err := os.MkdirAll(other, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ gitT(t, other, "init", "--quiet", "--initial-branch=master")
+ writeFile(t, filepath.Join(other, "README"), "not ruby/spec\n")
+ gitT(t, other, "add", "-A")
+ gitT(t, other, "commit", "--quiet", "-m", "x")
+ sha := gitT(t, other, "rev-parse", "HEAD")
+ if _, err := pin(filepath.Join(t.TempDir(), "c"), sha, other); err == nil {
+ t.Fatal("pin accepted a checkout with no language/ or core/")
+ }
+ })
+ t.Run("a path that is a file", func(t *testing.T) {
+ f := filepath.Join(t.TempDir(), "file")
+ writeFile(t, f, "x")
+ if _, err := pin(f, older, url); err == nil {
+ t.Fatal("pin accepted a regular file as the corpus directory")
+ }
+ })
+}
+
+// TestTheReportedCommitIsTheOneReadBack holds defect 2 at the CLI boundary:
+// stdout carries the directory alone (run.sh captures it), and the stderr line
+// names the commit git reports, which here is asserted against git itself
+// rather than against the flag that was passed.
+func TestTheReportedCommitIsTheOneReadBack(t *testing.T) {
+ needGit(t)
+ url, older, _ := upstream(t)
+ dir := filepath.Join(t.TempDir(), "rubyspec-corpus")
+ var out, errb bytes.Buffer
+
+ if code := run([]string{"-sha", older, "-url", url, "-cache", dir}, &out, &errb); code != 0 {
+ t.Fatalf("exit %d: %s", code, errb.String())
+ }
+ if out.String() != dir+"\n" {
+ t.Fatalf("stdout = %q, want exactly the directory", out.String())
+ }
+ head := gitT(t, dir, "rev-parse", "HEAD")
+ if !strings.Contains(errb.String(), "corpus: "+dir+" @ "+head) {
+ t.Fatalf("stderr = %q, want the commit git reports (%s)", errb.String(), head)
+ }
+
+ // A missing flag is refused with a message that NAMES the flag. pin would
+ // refuse an empty -sha too, one layer down, but as "-sha must be a full
+ // 40-character … got \"\"" — true, and useless to someone who forgot it.
+ // The required-flags check exists for its message, so its message is what
+ // is held.
+ for _, args := range [][]string{{"-url", url}, {"-sha", older}} {
+ out.Reset()
+ errb.Reset()
+ if code := run(args, &out, &errb); code != 2 {
+ t.Fatalf("run(%v) exited %d, want 2", args, code)
+ }
+ if !strings.Contains(errb.String(), "-sha and -url are required") {
+ t.Fatalf("run(%v) stderr = %q, want it to name the missing flags", args, errb.String())
+ }
+ if out.Len() != 0 {
+ t.Fatalf("a refusal printed a directory on stdout: %q — run.sh would use it", out.String())
+ }
+ }
+}
+
+// TestTheCommitIsReadBackAfterCheckoutNotAssumed holds defect 2 where it can
+// actually happen. A checkout that exits 0 has not necessarily left HEAD where
+// it was asked to: a post-checkout hook runs afterwards and can move it, and
+// this machine, like many, has global hooks. The old run.sh printed the pinned
+// constant whatever HEAD said; this asks git again and refuses a mismatch.
+//
+// The hook directory is forced through GIT_CONFIG_COUNT, which outranks every
+// config file, so the test is hermetic against the host's own core.hooksPath.
+// It is set AFTER the fixtures are built, so only pin's own git runs see it.
+func TestTheCommitIsReadBackAfterCheckoutNotAssumed(t *testing.T) {
+ needGit(t)
+
+ withHook := func(t *testing.T, script string) {
+ t.Helper()
+ hooks := t.TempDir()
+ p := filepath.Join(hooks, "post-checkout")
+ if err := os.WriteFile(p, []byte("#!/bin/sh\n"+script+"\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("GIT_CONFIG_COUNT", "1")
+ t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath")
+ t.Setenv("GIT_CONFIG_VALUE_0", hooks)
+ }
+
+ t.Run("a hook that moves HEAD elsewhere is caught", func(t *testing.T) {
+ url, older, tip := upstream(t)
+ dir := filepath.Join(t.TempDir(), "rubyspec-corpus")
+ gitT(t, filepath.Dir(dir), "clone", "--quiet", url, dir)
+ // The guard variable stops the hook re-entering on its own checkout.
+ withHook(t, `[ -n "$SPECPIN_HOOK_RAN" ] && exit 0
+SPECPIN_HOOK_RAN=1 git checkout --quiet --force `+tip)
+
+ _, err := pin(dir, older, url)
+ if err == nil {
+ t.Fatalf("pin reported %s although a hook left HEAD at %s", older, tip)
+ }
+ if !strings.Contains(err.Error(), tip) {
+ t.Fatalf("the refusal does not name where HEAD actually is (%s): %v", tip, err)
+ }
+ })
+
+ t.Run("a hook that leaves no readable HEAD is caught", func(t *testing.T) {
+ url, older, _ := upstream(t)
+ dir := filepath.Join(t.TempDir(), "rubyspec-corpus")
+ gitT(t, filepath.Dir(dir), "clone", "--quiet", url, dir)
+ withHook(t, `rm -f "$(git rev-parse --git-dir)/HEAD"`)
+
+ if got, err := pin(dir, older, url); err == nil {
+ t.Fatalf("pin reported %q with no HEAD left to read", got)
+ }
+ })
+}
diff --git a/scripts/conformance/rubyspec/run.sh b/scripts/conformance/rubyspec/run.sh
index d36b50ff..290ec844 100755
--- a/scripts/conformance/rubyspec/run.sh
+++ b/scripts/conformance/rubyspec/run.sh
@@ -36,8 +36,8 @@
#
# Env:
# RBGO path to the rbgo binary (default: built from ./cmd/rbgo)
-# SPECDIR ruby/spec checkout (default: cloned to CACHE at SPEC_SHA)
-# CACHE clone cache dir (default: /tmp/rubyspec-corpus)
+# SPECDIR ruby/spec checkout (default: CACHE; moved to SPEC_SHA)
+# CACHE clone cache dir (default: /rbgo/rubyspec-corpus)
# JOBS parallelism (default: number of CPUs)
# TIMEOUT per-file timeout seconds (default: 25)
# UPDATE_BASELINE=1 rewrite BASELINE from this sweep and exit 0
@@ -46,7 +46,7 @@ set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$HERE/../../.." && pwd)"
RBGO="${RBGO:-/tmp/rbgo-rubyspec}"
-CACHE="${CACHE:-/tmp/rubyspec-corpus}"
+CACHE="${CACHE:-}"
SPECDIR="${SPECDIR:-$CACHE}"
TIMEOUT="${TIMEOUT:-25}"
JOBS="${JOBS:-$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)}"
@@ -67,19 +67,13 @@ echo "rbgo: $RBGO"
echo
echo "== ruby/spec corpus =="
-if [ ! -d "$SPECDIR/language" ]; then
- if ! command -v git >/dev/null 2>&1; then
- echo "git missing and no corpus at $SPECDIR — cannot run ratchet" >&2
- exit 2
- fi
- rm -rf "$CACHE"
- git clone --filter=blob:none "$SPEC_URL" "$CACHE" >/dev/null 2>&1 || {
- echo "clone failed (offline?) — cannot run ratchet" >&2; exit 2; }
- (cd "$CACHE" && git checkout -q "$SPEC_SHA") || {
- echo "checkout of $SPEC_SHA failed" >&2; exit 2; }
- SPECDIR="$CACHE"
-fi
-echo "corpus: $SPECDIR @ $SPEC_SHA"
+# cmd/specpin (#857) puts the corpus at SPEC_SHA and prints `corpus: @
+# ` with the commit READ BACK from git, not this constant. It never
+# deletes a directory: one that is neither empty nor a checkout of its own is
+# refused, where this block used to `rm -rf` it.
+SPECDIR="$(cd "$REPO_ROOT" && GOWORK=off go run ./scripts/conformance/rubyspec/cmd/specpin \
+ -sha "$SPEC_SHA" -url "$SPEC_URL" ${SPECDIR:+-cache "$SPECDIR"})" || {
+ echo "no corpus at $SPEC_SHA — cannot run ratchet" >&2; exit 2; }
# Install the MSpec shim in place of ruby/spec's real spec_helper.
cp "$HERE/spec_helper.rb" "$SPECDIR/spec_helper.rb"