| 1 | package workspace |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "io/fs" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | ) |
| 13 | |
| 14 | // Task tree errors. |
| 15 | var ( |
| 16 | // ErrNoChanges means the step left the tree as it found it. |
| 17 | ErrNoChanges = errors.New("workspace: no changes") |
| 18 | // ErrTreeRefused means the tree holds something the runner will not |
| 19 | // commit: a .git entry at any depth, or a device, pipe or socket. |
| 20 | ErrTreeRefused = errors.New("workspace: tree refused") |
| 21 | ) |
| 22 | |
| 23 | // TaskTree is one step's working copy. Dir is all a namespace sees: the |
| 24 | // files at the base commit, no .git. GitDir is the runner's private |
| 25 | // repository beside it (objects borrowed from the project clone), where |
| 26 | // the runner itself commits what changed. No hook, helper, filter or |
| 27 | // config from the repository or the namespace ever runs. |
| 28 | type TaskTree struct { |
| 29 | Dir, GitDir, Git, Branch, Base string |
| 30 | absentSandboxPaths []string |
| 31 | } |
| 32 | |
| 33 | func (t TaskTree) git(ctx context.Context, stdin io.Reader, extra []string, args ...string) (string, error) { |
| 34 | cmd := exec.CommandContext(ctx, t.Git, append([]string{"-c", "core.symlinks=true", "-c", "core.autocrlf=false", "-c", "core.untrackedCache=false", "-c", "core.quotePath=false", "-c", "gc.auto=0"}, args...)...) |
| 35 | cmd.Dir = t.GitDir |
| 36 | env := safeEnv() |
| 37 | env["HOME"] = "/nonexistent" |
| 38 | env["GIT_DIR"] = t.GitDir |
| 39 | env["GIT_WORK_TREE"] = t.Dir |
| 40 | env["GIT_CEILING_DIRECTORIES"] = filepath.Dir(t.GitDir) |
| 41 | for k, v := range env { |
| 42 | cmd.Env = append(cmd.Env, k+"="+v) |
| 43 | } |
| 44 | cmd.Env = append(cmd.Env, extra...) |
| 45 | cmd.Stdin, cmd.Stderr = stdin, io.Discard |
| 46 | out, err := cmd.Output() |
| 47 | return strings.TrimSpace(string(out)), err |
| 48 | } |
| 49 | |
| 50 | // PrepareTaskTree checks out base from the bare project clone into dir, |
| 51 | // with the branch pointing at base in a fresh private repository. Both |
| 52 | // paths are replaced if a previous attempt left them. |
| 53 | func PrepareTaskTree(ctx context.Context, git, clone, base, branch, dir, gitDir string) (TaskTree, error) { |
| 54 | t := TaskTree{Dir: dir, GitDir: gitDir, Git: git, Branch: branch, Base: base} |
| 55 | // No base: the repository has no commits yet. The tree starts empty |
| 56 | // on the task branch, unborn, and its first commit has no parent. |
| 57 | if !filepath.IsAbs(dir) || !filepath.IsAbs(gitDir) || !filepath.IsAbs(clone) || base != "" && !objectID.MatchString(base) || branch == "" || strings.HasPrefix(branch, "-") { |
| 58 | return t, ErrTreeRefused |
| 59 | } |
| 60 | for _, p := range []string{dir, gitDir} { |
| 61 | if err := os.RemoveAll(p); err != nil { |
| 62 | return t, err |
| 63 | } |
| 64 | } |
| 65 | if err := os.MkdirAll(filepath.Dir(gitDir), 0700); err != nil { |
| 66 | return t, err |
| 67 | } |
| 68 | init := exec.CommandContext(ctx, git, "init", "-q", "--bare", "--template=", "--object-format="+objectFormat(base), gitDir) |
| 69 | init.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"} |
| 70 | if err := init.Run(); err != nil { |
| 71 | return t, err |
| 72 | } |
| 73 | objects := filepath.Join(clone, "objects") |
| 74 | if info, err := os.Lstat(objects); err != nil || !info.IsDir() { |
| 75 | return t, ErrTreeRefused |
| 76 | } |
| 77 | if err := os.MkdirAll(filepath.Join(gitDir, "objects", "info"), 0700); err != nil { |
| 78 | return t, err |
| 79 | } |
| 80 | if err := os.WriteFile(filepath.Join(gitDir, "objects", "info", "alternates"), []byte(objects+"\n"), 0600); err != nil { |
| 81 | return t, err |
| 82 | } |
| 83 | // A shallow clone (the context index fetches with depth 1) ends its |
| 84 | // history at a boundary; the private repository keeps the same one. |
| 85 | if raw, err := os.ReadFile(filepath.Join(clone, "shallow")); err == nil { |
| 86 | if err := os.WriteFile(filepath.Join(gitDir, "shallow"), raw, 0600); err != nil { |
| 87 | return t, err |
| 88 | } |
| 89 | } else if !errors.Is(err, os.ErrNotExist) { |
| 90 | return t, err |
| 91 | } |
| 92 | if base == "" { |
| 93 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 94 | return t, err |
| 95 | } |
| 96 | if _, err := t.git(ctx, nil, nil, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil { |
| 97 | return t, err |
| 98 | } |
| 99 | err := t.recordSandboxPaths() |
| 100 | return t, err |
| 101 | } |
| 102 | if id, err := t.git(ctx, nil, nil, "rev-parse", "--verify", "--end-of-options", base+"^{commit}"); err != nil || id != base { |
| 103 | return t, ErrTreeRefused |
| 104 | } |
| 105 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 106 | return t, err |
| 107 | } |
| 108 | if _, err := t.git(ctx, nil, nil, "read-tree", "--end-of-options", base); err != nil { |
| 109 | return t, err |
| 110 | } |
| 111 | if _, err := t.git(ctx, nil, nil, "checkout-index", "-a", "-f"); err != nil { |
| 112 | return t, err |
| 113 | } |
| 114 | if _, err := t.git(ctx, nil, nil, "update-ref", "refs/heads/"+branch, base); err != nil { |
| 115 | return t, err |
| 116 | } |
| 117 | if _, err := t.git(ctx, nil, nil, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil { |
| 118 | return t, err |
| 119 | } |
| 120 | err := t.recordSandboxPaths() |
| 121 | return t, err |
| 122 | } |
| 123 | |
| 124 | // check refuses a tree that holds a .git entry at any depth (it would |
| 125 | // become a gitlink or a nested repository) or a special file. |
| 126 | func (t TaskTree) check() error { |
| 127 | files := 0 |
| 128 | return filepath.WalkDir(t.Dir, func(p string, d fs.DirEntry, err error) error { |
| 129 | if err != nil { |
| 130 | return ErrTreeRefused |
| 131 | } |
| 132 | if p == t.Dir { |
| 133 | return nil |
| 134 | } |
| 135 | if strings.EqualFold(d.Name(), ".git") { |
| 136 | return ErrTreeRefused |
| 137 | } |
| 138 | if files++; files > 500_000 { |
| 139 | return ErrTreeRefused |
| 140 | } |
| 141 | switch m := d.Type(); { |
| 142 | case m.IsDir(), m.IsRegular(), m&fs.ModeSymlink != 0: |
| 143 | return nil |
| 144 | } |
| 145 | return ErrTreeRefused |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | // Commit records everything the step changed as one commit on the base, |
| 150 | // made by the runner (the model never runs git here). ErrNoChanges when |
| 151 | // the tree matches the base. |
| 152 | func (t TaskTree) Commit(ctx context.Context, message, name, email string) (string, error) { |
| 153 | if err := t.check(); err != nil { |
| 154 | return "", err |
| 155 | } |
| 156 | if err := t.removeSandboxMasks(); err != nil { |
| 157 | return "", err |
| 158 | } |
| 159 | if _, err := t.git(ctx, nil, nil, "add", "-A", "--", "."); err != nil { |
| 160 | return "", err |
| 161 | } |
| 162 | tree, err := t.git(ctx, nil, nil, "write-tree") |
| 163 | if err != nil || !objectID.MatchString(tree) { |
| 164 | return "", ErrTreeRefused |
| 165 | } |
| 166 | // Without a base the tree is compared with the empty tree, and the |
| 167 | // commit is the repository's first (no parent). |
| 168 | var baseTree string |
| 169 | parent := []string{} |
| 170 | if t.Base == "" { |
| 171 | baseTree, err = t.git(ctx, strings.NewReader(""), nil, "hash-object", "-t", "tree", "--stdin") |
| 172 | } else { |
| 173 | baseTree, err = t.git(ctx, nil, nil, "rev-parse", "--verify", "--end-of-options", t.Base+"^{tree}") |
| 174 | parent = []string{"-p", t.Base} |
| 175 | } |
| 176 | if err != nil { |
| 177 | return "", err |
| 178 | } |
| 179 | if tree == baseTree { |
| 180 | return "", ErrNoChanges |
| 181 | } |
| 182 | who := []string{"GIT_AUTHOR_NAME=" + name, "GIT_AUTHOR_EMAIL=" + email, "GIT_COMMITTER_NAME=" + name, "GIT_COMMITTER_EMAIL=" + email} |
| 183 | sha, err := t.git(ctx, strings.NewReader(message), who, append([]string{"commit-tree", tree}, parent...)...) |
| 184 | if err != nil || !objectID.MatchString(sha) { |
| 185 | return "", ErrTreeRefused |
| 186 | } |
| 187 | if _, err := t.git(ctx, nil, nil, "update-ref", "refs/heads/"+t.Branch, sha); err != nil { |
| 188 | return "", err |
| 189 | } |
| 190 | return sha, nil |
| 191 | } |
| 192 | |
| 193 | // ChangedFiles lists the paths a commit changed against its base; with |
| 194 | // no base, against its parent, and every path of an initial commit. |
| 195 | func (t TaskTree) ChangedFiles(ctx context.Context, sha string) ([]string, error) { |
| 196 | args := []string{"diff-tree", "--no-commit-id", "--name-only", "-r", "--no-renames", "--no-ext-diff", "--no-textconv"} |
| 197 | if t.Base == "" { |
| 198 | args = append(args, "--root", sha) |
| 199 | } else { |
| 200 | args = append(args, t.Base, sha) |
| 201 | } |
| 202 | out, err := t.git(ctx, nil, nil, args...) |
| 203 | if err != nil { |
| 204 | return nil, err |
| 205 | } |
| 206 | if out == "" { |
| 207 | return nil, nil |
| 208 | } |
| 209 | return strings.Split(out, "\n"), nil |
| 210 | } |
| 211 | |
| 212 | // Remove deletes the working copy and the private repository. |
| 213 | func (t TaskTree) Remove() error { |
| 214 | return errors.Join(os.RemoveAll(t.Dir), os.RemoveAll(t.GitDir)) |
| 215 | } |
| 216 | |
| 217 | // Rebase puts a change on top of the tree's base: the three-way merge of |
| 218 | // the base and commit, with from (the base the change was made on) as |
| 219 | // their merge base, replaces the working copy. Files that conflict carry |
| 220 | // git's conflict markers; their paths are returned for the specialist to |
| 221 | // resolve. The runner still commits on the base, so the new commit is |
| 222 | // the change, rebased. No merge driver or attribute from the repository |
| 223 | // runs (system and global config are off). |
| 224 | func (t *TaskTree) Rebase(ctx context.Context, from, commit string) ([]string, error) { |
| 225 | if !objectID.MatchString(from) || !objectID.MatchString(commit) || !objectID.MatchString(t.Base) { |
| 226 | return nil, ErrTreeRefused |
| 227 | } |
| 228 | for _, c := range []string{from, commit} { |
| 229 | if id, err := t.git(ctx, nil, nil, "rev-parse", "--verify", "--end-of-options", c+"^{commit}"); err != nil || id != c { |
| 230 | return nil, ErrTreeRefused |
| 231 | } |
| 232 | } |
| 233 | out, err := t.git(ctx, nil, nil, "merge-tree", "--write-tree", "--name-only", "--no-messages", "-z", "--merge-base="+from, t.Base, commit) |
| 234 | var exit *exec.ExitError |
| 235 | if err != nil && !(errors.As(err, &exit) && exit.ExitCode() == 1) { |
| 236 | return nil, err |
| 237 | } |
| 238 | fields := strings.Split(strings.TrimRight(out, "\x00"), "\x00") |
| 239 | tree := fields[0] |
| 240 | if !objectID.MatchString(tree) { |
| 241 | return nil, ErrTreeRefused |
| 242 | } |
| 243 | var conflicts []string |
| 244 | for _, p := range fields[1:] { |
| 245 | if p != "" && (len(conflicts) == 0 || conflicts[len(conflicts)-1] != p) { |
| 246 | conflicts = append(conflicts, p) |
| 247 | } |
| 248 | } |
| 249 | entries, err := os.ReadDir(t.Dir) |
| 250 | if err != nil { |
| 251 | return nil, err |
| 252 | } |
| 253 | for _, e := range entries { |
| 254 | if err := os.RemoveAll(filepath.Join(t.Dir, e.Name())); err != nil { |
| 255 | return nil, err |
| 256 | } |
| 257 | } |
| 258 | if _, err := t.git(ctx, nil, nil, "read-tree", "--end-of-options", tree); err != nil { |
| 259 | return nil, err |
| 260 | } |
| 261 | if _, err := t.git(ctx, nil, nil, "checkout-index", "-a", "-f"); err != nil { |
| 262 | return nil, err |
| 263 | } |
| 264 | return conflicts, t.recordSandboxPaths() |
| 265 | } |
| 266 | |