| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "io/fs" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "syscall" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "the-valley/change" |
| 20 | "the-valley/rebase" |
| 21 | ) |
| 22 | |
| 23 | // roleEnv, set to "main", makes the test binary valley-restacker itself, |
| 24 | // so a test can run the program as a process of its own. Set to |
| 25 | // "drop-acks", it makes the test binary origin's receive-pack, less its |
| 26 | // answer to a push of the ref dropEnv names (lossyReceivePack). |
| 27 | const roleEnv = "RESTACK_TEST_ROLE" |
| 28 | |
| 29 | func TestMain(m *testing.M) { |
| 30 | switch os.Getenv(roleEnv) { |
| 31 | case "main": |
| 32 | main() |
| 33 | os.Exit(0) |
| 34 | case "drop-acks": |
| 35 | os.Exit(lossyReceivePack(os.Getenv(dropEnv), os.Args[1:])) |
| 36 | } |
| 37 | os.Exit(m.Run()) |
| 38 | } |
| 39 | |
| 40 | // decoy is a repository, and files around it, that an inherited variable |
| 41 | // would point git at instead of the scratch repository. |
| 42 | type decoy struct { |
| 43 | dir, repo string |
| 44 | } |
| 45 | |
| 46 | func newDecoy(t *testing.T, f *fixture) *decoy { |
| 47 | t.Helper() |
| 48 | d := &decoy{dir: t.TempDir()} |
| 49 | d.repo = filepath.Join(d.dir, "decoy.git") |
| 50 | f.run(d.dir, "init", "--quiet", "--bare", "--initial-branch=main", d.repo) |
| 51 | for _, sub := range []string{"wt", "objects/info", "objects/pack", "exec", "template/hooks"} { |
| 52 | if err := os.MkdirAll(filepath.Join(d.dir, sub), 0o755); err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | } |
| 56 | files := map[string]string{ |
| 57 | // Configuration that sends every fetch from origin to the decoy. |
| 58 | "gitconfig": "[url \"" + d.repo + "\"]\n\tinsteadOf = " + f.origin + "\n", |
| 59 | // A program git would run from its exec path to serve a fetch. |
| 60 | "exec/git-upload-pack": "#!/bin/sh\ntouch '" + filepath.Join(d.dir, "ran") + "'\nexit 1\n", |
| 61 | // A template git init would copy into a new repository. |
| 62 | "template/marker": "from the decoy\n", |
| 63 | "grafts": "", |
| 64 | } |
| 65 | for name, content := range files { |
| 66 | if err := os.WriteFile(filepath.Join(d.dir, name), []byte(content), 0o755); err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | } |
| 70 | return d |
| 71 | } |
| 72 | |
| 73 | // digest is every file under the decoy, by path and content. |
| 74 | func (d *decoy) digest(t *testing.T) string { |
| 75 | t.Helper() |
| 76 | h := sha256.New() |
| 77 | err := filepath.WalkDir(d.dir, func(path string, e fs.DirEntry, err error) error { |
| 78 | if err != nil { |
| 79 | return err |
| 80 | } |
| 81 | h.Write([]byte(path + "\n")) |
| 82 | if !e.IsDir() { |
| 83 | data, err := os.ReadFile(path) |
| 84 | if err != nil { |
| 85 | return err |
| 86 | } |
| 87 | h.Write(data) |
| 88 | } |
| 89 | return nil |
| 90 | }) |
| 91 | if err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | return hex.EncodeToString(h.Sum(nil)) |
| 95 | } |
| 96 | |
| 97 | // shape is what a plan says, less what differs from pass to pass: the |
| 98 | // operation and the commits built. |
| 99 | func shape(t *testing.T, out []byte) string { |
| 100 | t.Helper() |
| 101 | var p Plan |
| 102 | if err := json.Unmarshal(out, &p); err != nil { |
| 103 | t.Fatalf("the plan does not read: %v\n%s", err, out) |
| 104 | } |
| 105 | p.Operation = "" |
| 106 | for i := range p.Families { |
| 107 | if w := p.Families[i].Writes; w != nil { |
| 108 | for j := range w.Branches { |
| 109 | w.Branches[j].New = "" |
| 110 | } |
| 111 | for j := range w.Versions { |
| 112 | w.Versions[j].Head, w.Versions[j].Record = "", "" |
| 113 | } |
| 114 | for j := range w.Reports { |
| 115 | w.Reports[j].Commit = "" |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | data, _ := json.Marshal(p) |
| 120 | return string(data) |
| 121 | } |
| 122 | |
| 123 | // No variable that points git at another repository, other programs, |
| 124 | // other attributes or another format, or that gives it configuration, |
| 125 | // reaches what a pass runs. With each inherited, pointing at a decoy, the |
| 126 | // pass plans and builds what it does without, the decoy is untouched, and |
| 127 | // nothing the pass prints names it. |
| 128 | func TestNoInheritedGitVariableReachesAPass(t *testing.T) { |
| 129 | f := newFixture(t, "") |
| 130 | f.readyAs(idA, "alice", "a", "main", "A's title") |
| 131 | f.readyAs(idB, "bob", "b", "a", "B's title") |
| 132 | f.moveMain() |
| 133 | d := newDecoy(t, f) |
| 134 | pass := func(t *testing.T) (string, string) { |
| 135 | t.Helper() |
| 136 | r := newRestacker(t, f) |
| 137 | r.c.state = t.TempDir() |
| 138 | var out, errOut bytes.Buffer |
| 139 | if err := once(context.Background(), reportOnly(t, r.c, "--json"), &out, &errOut); err != nil { |
| 140 | return "failed: " + err.Error(), errOut.String() |
| 141 | } |
| 142 | if _, err := os.Stat(filepath.Join(r.c.state, "scratch", ".git", "marker")); err == nil { |
| 143 | return "the decoy's template reached the scratch repository", errOut.String() |
| 144 | } |
| 145 | return shape(t, out.Bytes()), errOut.String() |
| 146 | } |
| 147 | want, _ := pass(t) |
| 148 | if strings.HasPrefix(want, "failed") { |
| 149 | t.Fatal(want) |
| 150 | } |
| 151 | before := d.digest(t) |
| 152 | head := f.at("refs/heads/a") |
| 153 | for _, tc := range []struct { |
| 154 | name string |
| 155 | vars map[string]string |
| 156 | }{ |
| 157 | {"GIT_DIR", map[string]string{"GIT_DIR": d.repo}}, |
| 158 | {"GIT_WORK_TREE", map[string]string{"GIT_WORK_TREE": filepath.Join(d.dir, "wt")}}, |
| 159 | {"GIT_INDEX_FILE", map[string]string{"GIT_INDEX_FILE": filepath.Join(d.dir, "index")}}, |
| 160 | {"GIT_OBJECT_DIRECTORY", map[string]string{"GIT_OBJECT_DIRECTORY": filepath.Join(d.dir, "objects")}}, |
| 161 | {"GIT_ALTERNATE_OBJECT_DIRECTORIES", map[string]string{"GIT_ALTERNATE_OBJECT_DIRECTORIES": filepath.Join(d.dir, "no-such-objects")}}, |
| 162 | {"GIT_COMMON_DIR", map[string]string{"GIT_COMMON_DIR": d.repo}}, |
| 163 | {"GIT_NAMESPACE", map[string]string{"GIT_NAMESPACE": "decoy"}}, |
| 164 | {"GIT_CONFIG_GLOBAL", map[string]string{"GIT_CONFIG_GLOBAL": filepath.Join(d.dir, "gitconfig")}}, |
| 165 | {"GIT_CONFIG_SYSTEM", map[string]string{"GIT_CONFIG_SYSTEM": filepath.Join(d.dir, "gitconfig"), "GIT_CONFIG_NOSYSTEM": "0"}}, |
| 166 | {"GIT_CONFIG", map[string]string{"GIT_CONFIG": filepath.Join(d.dir, "gitconfig")}}, |
| 167 | {"GIT_CONFIG_COUNT", map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "url." + d.repo + ".insteadOf", "GIT_CONFIG_VALUE_0": f.origin}}, |
| 168 | {"GIT_CONFIG_PARAMETERS", map[string]string{"GIT_CONFIG_PARAMETERS": "'url." + d.repo + ".insteadof'='" + f.origin + "'"}}, |
| 169 | {"GIT_EXEC_PATH", map[string]string{"GIT_EXEC_PATH": filepath.Join(d.dir, "exec")}}, |
| 170 | {"GIT_TEMPLATE_DIR", map[string]string{"GIT_TEMPLATE_DIR": filepath.Join(d.dir, "template")}}, |
| 171 | {"GIT_DEFAULT_HASH", map[string]string{"GIT_DEFAULT_HASH": "sha256"}}, |
| 172 | {"GIT_ATTR_SOURCE", map[string]string{"GIT_ATTR_SOURCE": "no-such-attribute-source"}}, |
| 173 | {"GIT_GRAFT_FILE", map[string]string{"GIT_GRAFT_FILE": filepath.Join(d.dir, "grafts")}}, |
| 174 | } { |
| 175 | t.Run(tc.name, func(t *testing.T) { |
| 176 | if tc.name == "GIT_GRAFT_FILE" { |
| 177 | // A graft that would cut a's commit from its history. |
| 178 | if err := os.WriteFile(filepath.Join(d.dir, "grafts"), []byte(head+"\n"), 0o644); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | defer os.WriteFile(filepath.Join(d.dir, "grafts"), nil, 0o755) |
| 182 | before = d.digest(t) |
| 183 | } |
| 184 | for name, value := range tc.vars { |
| 185 | t.Setenv(name, value) |
| 186 | } |
| 187 | got, stderr := pass(t) |
| 188 | if got != want { |
| 189 | t.Errorf("with %s inherited, the pass says\n%s\nand without\n%s", tc.name, got, want) |
| 190 | } |
| 191 | if after := d.digest(t); after != before { |
| 192 | t.Errorf("with %s inherited, the pass changed the decoy", tc.name) |
| 193 | } |
| 194 | if strings.Contains(stderr, d.dir) { |
| 195 | t.Errorf("with %s inherited, the pass printed\n%s", tc.name, stderr) |
| 196 | } |
| 197 | }) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // The user's own attributes file, which git reads from XDG_CONFIG_HOME or |
| 202 | // HOME whatever configuration it reads, does not change how a pass |
| 203 | // rebases: a merge=union there would resolve a conflict silently. |
| 204 | func TestTheUsersAttributesDoNotChangeARebase(t *testing.T) { |
| 205 | f := newFixture(t, "") |
| 206 | f.git("checkout", "--quiet", "-b", "a", "main") |
| 207 | head := f.commit("a's line", "shared.txt") |
| 208 | f.git("push", "--quiet", "origin", "a") |
| 209 | f.writeRecordAt(idA, "a", head) |
| 210 | f.git("checkout", "--quiet", "main") |
| 211 | if err := os.WriteFile(filepath.Join(f.work, "shared.txt"), []byte("main's line\n"), 0o644); err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | f.git("add", "shared.txt") |
| 215 | f.git("commit", "--quiet", "-m", "main's line") |
| 216 | f.git("push", "--quiet", "origin", "main") |
| 217 | |
| 218 | home := t.TempDir() |
| 219 | for _, dir := range []string{filepath.Join(home, ".config", "git"), filepath.Join(home, "xdg", "git")} { |
| 220 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | if err := os.WriteFile(filepath.Join(dir, "attributes"), []byte("* merge=union\n"), 0o644); err != nil { |
| 224 | t.Fatal(err) |
| 225 | } |
| 226 | } |
| 227 | t.Setenv("HOME", home) |
| 228 | t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "xdg")) |
| 229 | r := newRestacker(t, f) |
| 230 | var out, errOut bytes.Buffer |
| 231 | if err := once(context.Background(), reportOnly(t, r.c, "--json"), &out, &errOut); err != nil { |
| 232 | t.Fatalf("once: %v\n%s", err, errOut.String()) |
| 233 | } |
| 234 | var p Plan |
| 235 | if err := json.Unmarshal(out.Bytes(), &p); err != nil { |
| 236 | t.Fatal(err) |
| 237 | } |
| 238 | if len(p.Families) != 1 || p.Families[0].Writes == nil || p.Families[0].Writes.Result != "conflict" { |
| 239 | t.Errorf("with merge=union in the user's attributes, the pass says %s", out.String()) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // writeRecordAt readies the change id at head on branch, owned by alice. |
| 244 | func (f *fixture) writeRecordAt(id, branch, head string) { |
| 245 | f.t.Helper() |
| 246 | f.writeRecord(id, &change.Record{ |
| 247 | Schema: change.Schema, ChangeID: id, Target: rebase.Target, Owner: "alice", State: change.Ready, Seq: 1, Active: 1, |
| 248 | Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: "A title", Branch: branch, Uploader: "alice"}}, |
| 249 | }, "", head) |
| 250 | } |
| 251 | |
| 252 | // A process whose stderr nobody reads, and is full, still ends: the error |
| 253 | // it ends with is given up on after a few seconds. |
| 254 | func TestABlockedStderrDoesNotHoldTheProcess(t *testing.T) { |
| 255 | self, err := os.Executable() |
| 256 | if err != nil { |
| 257 | t.Fatal(err) |
| 258 | } |
| 259 | r, w, err := os.Pipe() |
| 260 | if err != nil { |
| 261 | t.Fatal(err) |
| 262 | } |
| 263 | defer r.Close() |
| 264 | defer w.Close() |
| 265 | fd := int(w.Fd()) |
| 266 | if err := syscall.SetNonblock(fd, true); err != nil { |
| 267 | t.Fatal(err) |
| 268 | } |
| 269 | chunk := make([]byte, 4096) |
| 270 | for { |
| 271 | if _, err := syscall.Write(fd, chunk); err != nil { |
| 272 | if errors.Is(err, syscall.EAGAIN) { |
| 273 | break |
| 274 | } |
| 275 | t.Fatal(err) |
| 276 | } |
| 277 | } |
| 278 | if err := syscall.SetNonblock(fd, false); err != nil { |
| 279 | t.Fatal(err) |
| 280 | } |
| 281 | cmd := exec.Command(self, "once", "--report-only") |
| 282 | cmd.Env = append(os.Environ(), roleEnv+"=main") |
| 283 | cmd.Stderr = w |
| 284 | start := time.Now() |
| 285 | if err := cmd.Start(); err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | done := make(chan error, 1) |
| 289 | go func() { done <- cmd.Wait() }() |
| 290 | select { |
| 291 | case err := <-done: |
| 292 | var exit *exec.ExitError |
| 293 | if !errors.As(err, &exit) || exit.ExitCode() != 1 { |
| 294 | t.Errorf("the process ended with %v, not the error it could not print", err) |
| 295 | } |
| 296 | if took := time.Since(start); took > sayBound+10*time.Second { |
| 297 | t.Errorf("the process took %v to end", took) |
| 298 | } |
| 299 | case <-time.After(sayBound + 30*time.Second): |
| 300 | cmd.Process.Kill() |
| 301 | t.Fatal("a process whose stderr nobody reads did not end") |
| 302 | } |
| 303 | } |