blob: e0307c1ab629a6b67181d41a3d5efa5ab9ce7243 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package dockerimg
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "fmt"
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070010 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -070011 "io/fs"
12 "maps"
13 "net/http"
14 "slices"
15 "strings"
16 "text/template"
17
18 "sketch.dev/ant"
19)
20
21func 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 Crawshaw2a5bd6d2025-04-30 14:29:46 -070026 fmt.Fprintf(h, "docker template\n%s\n", dockerfileDefaultTmpl)
Earl Lee2e463fb2025-04-17 11:22:22 -070027 return hex.EncodeToString(h.Sum(nil))
28}
29
David Crawshaw11129492025-04-25 20:41:53 -070030// DefaultImage is intended to ONLY be used by the pushdockerimg.go script.
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070031func DefaultImage() (name, dockerfile, tag string) {
32 return dockerImgName, dockerfileBase, dockerfileBaseHash()
David Crawshaw11129492025-04-25 20:41:53 -070033}
34
Philip Zeyligerbce3a132025-04-30 22:03:39 +000035const (
36 dockerImgRepo = "boldsoftware/sketch"
37 dockerImgName = "ghcr.io/" + dockerImgRepo
38)
David Crawshaw5bff6502025-04-26 09:11:40 -070039
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070040func dockerfileBaseHash() string {
41 h := sha256.New()
42 io.WriteString(h, dockerfileBase)
43 return hex.EncodeToString(h.Sum(nil))[:32]
44}
David Crawshaw11129492025-04-25 20:41:53 -070045
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070046const dockerfileBase = `FROM golang:1.24-bookworm
David Crawshawbe10fa92025-04-18 01:16:00 -070047
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070048RUN 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 Crawshawbe10fa92025-04-18 01:16:00 -070052
David Crawshawbe10fa92025-04-18 01:16:00 -070053ENV PATH="$GOPATH/bin:$PATH"
54
55RUN go install golang.org/x/tools/cmd/goimports@latest
56RUN go install golang.org/x/tools/gopls@latest
57RUN go install mvdan.cc/gofumpt@latest
58
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070059ENV GOTOOLCHAIN=auto
60
David Crawshawbe10fa92025-04-18 01:16:00 -070061RUN mkdir -p /root/.cache/sketch/webui
David Crawshaw11129492025-04-25 20:41:53 -070062`
David Crawshawbe10fa92025-04-18 01:16:00 -070063
David Crawshaw11129492025-04-25 20:41:53 -070064const dockerfileFragment = `
David Crawshawbe10fa92025-04-18 01:16:00 -070065ARG GIT_USER_EMAIL
66ARG GIT_USER_NAME
67
68RUN git config --global user.email "$GIT_USER_EMAIL" && \
69 git config --global user.name "$GIT_USER_NAME"
70
Josh Bleecher Snyderc76a3922025-05-01 01:18:56 +000071LABEL sketch_context="{{.InitFilesHash}}"
David Crawshawbe10fa92025-04-18 01:16:00 -070072COPY . /app
73
74WORKDIR /app{{.SubDir}}
75RUN if [ -f go.mod ]; then go mod download; fi
76
David Crawshaw11129492025-04-25 20:41:53 -070077{{.ExtraCmds}}
78
79CMD ["/bin/sketch"]
80`
81
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070082var dockerfileDefaultTmpl = "FROM " + dockerImgName + ":" + dockerfileBaseHash() + "\n" + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -070083
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070084func 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
128func 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 Crawshawbe10fa92025-04-18 01:16:00 -0700140
Earl Lee2e463fb2025-04-17 11:22:22 -0700141// 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.
145func 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 Crawshaw2a5bd6d2025-04-30 14:29:46 -0700152 var dockerfileExtraCmds string
Earl Lee2e463fb2025-04-17 11:22:22 -0700153 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 Lee2e463fb2025-04-17 11:22:22 -0700160 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 Crawshaw2a5bd6d2025-04-30 14:29:46 -0700180 "required": ["extra_cmds"],
Earl Lee2e463fb2025-04-17 11:22:22 -0700181 "properties": {
Earl Lee2e463fb2025-04-17 11:22:22 -0700182 "extra_cmds": {
183 "type": "string",
184 "description": "Extra commands to add to the dockerfile."
185 }
186 }
187}`),
188 }}
189
Earl Lee2e463fb2025-04-17 11:22:22 -0700190 // 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 Zeyligercc3ba222025-04-23 14:52:21 -0700195 // go test ./dockerimg -httprecord ".*" -rewritewant
Earl Lee2e463fb2025-04-17 11:22:22 -0700196 //
197 // Then look at the changes with:
198 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700199 // git diff dockerimg/testdata/*.dockerfile
Earl Lee2e463fb2025-04-17 11:22:22 -0700200 //
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: `
207Call the dockerfile tool to create a Dockerfile.
208The parameters to dockerfile fill out the From and ExtraCmds
209template variables in the following Go template:
210
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700211` + "```\n" + dockerfileBase + dockerfileFragment + "\n```" + `
Earl Lee2e463fb2025-04-17 11:22:22 -0700212
213In particular:
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700214- Assume it is primarily a Go project.
Earl Lee2e463fb2025-04-17 11:22:22 -0700215- 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 Crawshaw2a5bd6d2025-04-30 14:29:46 -0700217- 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 Crawshaw11129492025-04-25 20:41:53 -0700219- Do NOT expose any ports.
220- Do NOT generate any CMD or ENTRYPOINT extra commands.
Earl Lee2e463fb2025-04-17 11:22:22 -0700221`,
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 Crawshaw2a5bd6d2025-04-30 14:29:46 -0700252 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 Crawshaw11129492025-04-25 20:41:53 -0700259 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700260 buf := new(bytes.Buffer)
David Crawshaw11129492025-04-25 20:41:53 -0700261 err = template.Must(template.New("dockerfile").Parse(tmpl)).Execute(buf, map[string]string{
Josh Bleecher Snyderc76a3922025-05-01 01:18:56 +0000262 "ExtraCmds": dockerfileExtraCmds,
263 "SubDir": subPathWorkingDir,
264 "InitFilesHash": hashInitFiles(initFiles),
Earl Lee2e463fb2025-04-17 11:22:22 -0700265 })
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
275func 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}