| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | package dockerimg |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 10 | "io" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 11 | "io/fs" |
| 12 | "maps" |
| 13 | "net/http" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "text/template" |
| 17 | |
| 18 | "sketch.dev/ant" |
| 19 | ) |
| 20 | |
| 21 | func hashInitFiles(initFiles map[string]string) string { |
| 22 | h := sha256.New() |
| 23 | for _, path := range slices.Sorted(maps.Keys(initFiles)) { |
| 24 | fmt.Fprintf(h, "%s\n%s\n\n", path, initFiles[path]) |
| 25 | } |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 26 | fmt.Fprintf(h, "docker template\n%s\n", dockerfileDefaultTmpl) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 27 | return hex.EncodeToString(h.Sum(nil)) |
| 28 | } |
| 29 | |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 30 | // DefaultImage is intended to ONLY be used by the pushdockerimg.go script. |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 31 | func DefaultImage() (name, dockerfile, tag string) { |
| 32 | return dockerImgName, dockerfileBase, dockerfileBaseHash() |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 33 | } |
| 34 | |
| Philip Zeyliger | bce3a13 | 2025-04-30 22:03:39 +0000 | [diff] [blame] | 35 | const ( |
| 36 | dockerImgRepo = "boldsoftware/sketch" |
| 37 | dockerImgName = "ghcr.io/" + dockerImgRepo |
| 38 | ) |
| David Crawshaw | 5bff650 | 2025-04-26 09:11:40 -0700 | [diff] [blame] | 39 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 40 | func dockerfileBaseHash() string { |
| 41 | h := sha256.New() |
| 42 | io.WriteString(h, dockerfileBase) |
| 43 | return hex.EncodeToString(h.Sum(nil))[:32] |
| 44 | } |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 45 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 46 | const dockerfileBase = `FROM golang:1.24-bookworm |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 47 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 48 | RUN set -eux; \ |
| 49 | apt-get update; \ |
| 50 | apt-get install -y --no-install-recommends \ |
| 51 | git jq sqlite3 npm nodejs gh ripgrep fzf python3 curl vim |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 52 | |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 53 | ENV PATH="$GOPATH/bin:$PATH" |
| 54 | |
| 55 | RUN go install golang.org/x/tools/cmd/goimports@latest |
| 56 | RUN go install golang.org/x/tools/gopls@latest |
| 57 | RUN go install mvdan.cc/gofumpt@latest |
| 58 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 59 | ENV GOTOOLCHAIN=auto |
| 60 | |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 61 | RUN mkdir -p /root/.cache/sketch/webui |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 62 | ` |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 63 | |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 64 | const dockerfileFragment = ` |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 65 | ARG GIT_USER_EMAIL |
| 66 | ARG GIT_USER_NAME |
| 67 | |
| 68 | RUN git config --global user.email "$GIT_USER_EMAIL" && \ |
| 69 | git config --global user.name "$GIT_USER_NAME" |
| 70 | |
| Josh Bleecher Snyder | c76a392 | 2025-05-01 01:18:56 +0000 | [diff] [blame] | 71 | LABEL sketch_context="{{.InitFilesHash}}" |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 72 | COPY . /app |
| 73 | |
| 74 | WORKDIR /app{{.SubDir}} |
| 75 | RUN if [ -f go.mod ]; then go mod download; fi |
| 76 | |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 77 | {{.ExtraCmds}} |
| 78 | |
| 79 | CMD ["/bin/sketch"] |
| 80 | ` |
| 81 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 82 | var dockerfileDefaultTmpl = "FROM " + dockerImgName + ":" + dockerfileBaseHash() + "\n" + dockerfileFragment |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 83 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 84 | func readPublishedTags() ([]string, error) { |
| 85 | req, err := http.NewRequest("GET", "https://ghcr.io/token?service=ghcr.io&scope=repository:"+dockerImgRepo+":pull", nil) |
| 86 | if err != nil { |
| 87 | return nil, fmt.Errorf("token: %w", err) |
| 88 | } |
| 89 | res, err := http.DefaultClient.Do(req) |
| 90 | if err != nil { |
| 91 | return nil, fmt.Errorf("token: %w", err) |
| 92 | } |
| 93 | body, err := io.ReadAll(res.Body) |
| 94 | res.Body.Close() |
| 95 | if err != nil || res.StatusCode != 200 { |
| 96 | return nil, fmt.Errorf("token: %d: %s: %w", res.StatusCode, body, err) |
| 97 | } |
| 98 | var tokenBody struct { |
| 99 | Token string `json:"token"` |
| 100 | } |
| 101 | if err := json.Unmarshal(body, &tokenBody); err != nil { |
| 102 | return nil, fmt.Errorf("token: %w: %s", err, body) |
| 103 | } |
| 104 | |
| 105 | req, err = http.NewRequest("GET", "https://ghcr.io/v2/"+dockerImgRepo+"/tags/list", nil) |
| 106 | if err != nil { |
| 107 | return nil, fmt.Errorf("tags: %w", err) |
| 108 | } |
| 109 | req.Header.Set("Authorization", "Bearer "+tokenBody.Token) |
| 110 | res, err = http.DefaultClient.Do(req) |
| 111 | if err != nil { |
| 112 | return nil, fmt.Errorf("tags: %w", err) |
| 113 | } |
| 114 | body, err = io.ReadAll(res.Body) |
| 115 | res.Body.Close() |
| 116 | if err != nil || res.StatusCode != 200 { |
| 117 | return nil, fmt.Errorf("tags: %d: %s: %w", res.StatusCode, body, err) |
| 118 | } |
| 119 | var tags struct { |
| 120 | Tags []string `json:"tags"` |
| 121 | } |
| 122 | if err := json.Unmarshal(body, &tags); err != nil { |
| 123 | return nil, fmt.Errorf("tags: %w: %s", err, body) |
| 124 | } |
| 125 | return tags.Tags, nil |
| 126 | } |
| 127 | |
| 128 | func checkTagExists(tag string) error { |
| 129 | tags, err := readPublishedTags() |
| 130 | if err != nil { |
| 131 | return fmt.Errorf("check tag exists: %w", err) |
| 132 | } |
| 133 | for _, t := range tags { |
| 134 | if t == tag { |
| 135 | return nil // found it |
| 136 | } |
| 137 | } |
| 138 | return fmt.Errorf("check tag exists: %q not found in %v", tag, tags) |
| 139 | } |
| David Crawshaw | be10fa9 | 2025-04-18 01:16:00 -0700 | [diff] [blame] | 140 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 141 | // createDockerfile creates a Dockerfile for a git repo. |
| 142 | // It expects the relevant initFiles to have been provided. |
| 143 | // If the sketch binary is being executed in a sub-directory of the repository, |
| 144 | // the relative path is provided on subPathWorkingDir. |
| 145 | func createDockerfile(ctx context.Context, httpc *http.Client, antURL, antAPIKey string, initFiles map[string]string, subPathWorkingDir string) (string, error) { |
| 146 | if subPathWorkingDir == "." { |
| 147 | subPathWorkingDir = "" |
| 148 | } else if subPathWorkingDir != "" && subPathWorkingDir[0] != '/' { |
| 149 | subPathWorkingDir = "/" + subPathWorkingDir |
| 150 | } |
| 151 | toolCalled := false |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 152 | var dockerfileExtraCmds string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 153 | runDockerfile := func(ctx context.Context, input json.RawMessage) (string, error) { |
| 154 | // TODO: unmarshal straight into a struct |
| 155 | var m map[string]any |
| 156 | if err := json.Unmarshal(input, &m); err != nil { |
| 157 | return "", fmt.Errorf(`input=%[1]v (%[1]T), wanted a map[string]any, got: %w`, input, err) |
| 158 | } |
| 159 | var ok bool |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 160 | dockerfileExtraCmds, ok = m["extra_cmds"].(string) |
| 161 | if !ok { |
| 162 | return "", fmt.Errorf(`input["extra_cmds"]=%[1]v (%[1]T), wanted a string`, m["path"]) |
| 163 | } |
| 164 | toolCalled = true |
| 165 | return "OK", nil |
| 166 | } |
| 167 | convo := ant.NewConvo(ctx, antAPIKey) |
| 168 | if httpc != nil { |
| 169 | convo.HTTPC = httpc |
| 170 | } |
| 171 | if antURL != "" { |
| 172 | convo.URL = antURL |
| 173 | } |
| 174 | convo.Tools = []*ant.Tool{{ |
| 175 | Name: "dockerfile", |
| 176 | Description: "Helps define a Dockerfile that sets up a dev environment for this project.", |
| 177 | Run: runDockerfile, |
| 178 | InputSchema: ant.MustSchema(`{ |
| 179 | "type": "object", |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 180 | "required": ["extra_cmds"], |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 181 | "properties": { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 182 | "extra_cmds": { |
| 183 | "type": "string", |
| 184 | "description": "Extra commands to add to the dockerfile." |
| 185 | } |
| 186 | } |
| 187 | }`), |
| 188 | }} |
| 189 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 190 | // TODO: it's basically impossible to one-shot a python env. We need an agent loop for that. |
| 191 | // Right now the prompt contains a set of half-baked workarounds. |
| 192 | |
| 193 | // If you want to edit the model prompt, run: |
| 194 | // |
| Philip Zeyliger | cc3ba22 | 2025-04-23 14:52:21 -0700 | [diff] [blame] | 195 | // go test ./dockerimg -httprecord ".*" -rewritewant |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 196 | // |
| 197 | // Then look at the changes with: |
| 198 | // |
| Philip Zeyliger | cc3ba22 | 2025-04-23 14:52:21 -0700 | [diff] [blame] | 199 | // git diff dockerimg/testdata/*.dockerfile |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 200 | // |
| 201 | // If the dockerfile changes are a strict improvement, commit all the changes. |
| 202 | msg := ant.Message{ |
| 203 | Role: ant.MessageRoleUser, |
| 204 | Content: []ant.Content{{ |
| 205 | Type: ant.ContentTypeText, |
| 206 | Text: ` |
| 207 | Call the dockerfile tool to create a Dockerfile. |
| 208 | The parameters to dockerfile fill out the From and ExtraCmds |
| 209 | template variables in the following Go template: |
| 210 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 211 | ` + "```\n" + dockerfileBase + dockerfileFragment + "\n```" + ` |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 212 | |
| 213 | In particular: |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 214 | - Assume it is primarily a Go project. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 215 | - Python env setup is challenging and often no required, so any RUN commands involving python tooling should be written to let docker build continue if there is a failure. |
| 216 | - Include any tools particular to this repository that can be inferred from the given context. |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 217 | - Append || true to any apt-get install commands in case the package does not exist. |
| 218 | - MINIMIZE the number of extra_cmds generated. Straightforward environments do not need any. |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 219 | - Do NOT expose any ports. |
| 220 | - Do NOT generate any CMD or ENTRYPOINT extra commands. |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 221 | `, |
| 222 | }}, |
| 223 | } |
| 224 | if len(initFiles) > 0 { |
| 225 | msg.Content[0].Text += "Here is the content of several files from the repository that may be relevant:\n\n" |
| 226 | } |
| 227 | |
| 228 | for _, name := range slices.Sorted(maps.Keys(initFiles)) { |
| 229 | msg.Content = append(msg.Content, ant.Content{ |
| 230 | Type: ant.ContentTypeText, |
| 231 | Text: fmt.Sprintf("Here is the contents %s:\n<file>\n%s\n</file>\n\n", name, initFiles[name]), |
| 232 | }) |
| 233 | } |
| 234 | msg.Content = append(msg.Content, ant.Content{ |
| 235 | Type: ant.ContentTypeText, |
| 236 | Text: "Now call the dockerfile tool.", |
| 237 | }) |
| 238 | res, err := convo.SendMessage(msg) |
| 239 | if err != nil { |
| 240 | return "", err |
| 241 | } |
| 242 | if res.StopReason != ant.StopReasonToolUse { |
| 243 | return "", fmt.Errorf("expected stop reason %q, got %q", ant.StopReasonToolUse, res.StopReason) |
| 244 | } |
| 245 | if _, err := convo.ToolResultContents(context.TODO(), res); err != nil { |
| 246 | return "", err |
| 247 | } |
| 248 | if !toolCalled { |
| 249 | return "", fmt.Errorf("no dockerfile returned") |
| 250 | } |
| 251 | |
| David Crawshaw | 2a5bd6d | 2025-04-30 14:29:46 -0700 | [diff] [blame] | 252 | tmpl := dockerfileDefaultTmpl |
| 253 | if tag := dockerfileBaseHash(); checkTagExists(tag) != nil { |
| 254 | // In development, if you edit dockerfileBase but don't release |
| 255 | // (as is reasonable for testing things!) the hash won't exist |
| 256 | // yet. In that case, we skip the sketch image and build it ourselves. |
| 257 | fmt.Printf("published container tag %s:%s missing; building locally\n", dockerImgName, tag) |
| 258 | tmpl = dockerfileBase + dockerfileFragment |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 259 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 260 | buf := new(bytes.Buffer) |
| David Crawshaw | 1112949 | 2025-04-25 20:41:53 -0700 | [diff] [blame] | 261 | err = template.Must(template.New("dockerfile").Parse(tmpl)).Execute(buf, map[string]string{ |
| Josh Bleecher Snyder | c76a392 | 2025-05-01 01:18:56 +0000 | [diff] [blame] | 262 | "ExtraCmds": dockerfileExtraCmds, |
| 263 | "SubDir": subPathWorkingDir, |
| 264 | "InitFilesHash": hashInitFiles(initFiles), |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 265 | }) |
| 266 | if err != nil { |
| 267 | return "", fmt.Errorf("dockerfile template failed: %w", err) |
| 268 | } |
| 269 | |
| 270 | return buf.String(), nil |
| 271 | } |
| 272 | |
| 273 | // For future reference: we can find the current git branch/checkout with: git symbolic-ref -q --short HEAD || git describe --tags --exact-match 2>/dev/null || git rev-parse HEAD |
| 274 | |
| 275 | func readInitFiles(fsys fs.FS) (map[string]string, error) { |
| 276 | result := make(map[string]string) |
| 277 | |
| 278 | err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error { |
| 279 | if err != nil { |
| 280 | return err |
| 281 | } |
| 282 | if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules") { |
| 283 | return fs.SkipDir |
| 284 | } |
| 285 | if !d.Type().IsRegular() { |
| 286 | return nil |
| 287 | } |
| 288 | |
| 289 | // Case 1: Check for README files |
| 290 | // TODO: find README files between the .git root (where we start) |
| 291 | // and the dir that sketch was initialized. This needs more info |
| 292 | // plumbed to this function. |
| 293 | if strings.HasPrefix(strings.ToLower(path), "readme") { |
| 294 | content, err := fs.ReadFile(fsys, path) |
| 295 | if err != nil { |
| 296 | return err |
| 297 | } |
| 298 | result[path] = string(content) |
| 299 | return nil |
| 300 | } |
| 301 | |
| 302 | // Case 2: Check for GitHub workflow files |
| 303 | if strings.HasPrefix(path, ".github/workflows/") { |
| 304 | content, err := fs.ReadFile(fsys, path) |
| 305 | if err != nil { |
| 306 | return err |
| 307 | } |
| 308 | result[path] = string(content) |
| 309 | return nil |
| 310 | } |
| 311 | |
| 312 | return nil |
| 313 | }) |
| 314 | if err != nil { |
| 315 | return nil, err |
| 316 | } |
| 317 | return result, nil |
| 318 | } |