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