blob: d0ba6c37bd292a5b6ec2481f912a256413600df6 [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
David Crawshawbe10fa92025-04-18 01:16:00 -070071COPY . /app
72
73WORKDIR /app{{.SubDir}}
74RUN if [ -f go.mod ]; then go mod download; fi
75
David Crawshaw11129492025-04-25 20:41:53 -070076{{.ExtraCmds}}
77
78CMD ["/bin/sketch"]
79`
80
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070081var dockerfileDefaultTmpl = "FROM " + dockerImgName + ":" + dockerfileBaseHash() + "\n" + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -070082
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070083func readPublishedTags() ([]string, error) {
84 req, err := http.NewRequest("GET", "https://ghcr.io/token?service=ghcr.io&scope=repository:"+dockerImgRepo+":pull", nil)
85 if err != nil {
86 return nil, fmt.Errorf("token: %w", err)
87 }
88 res, err := http.DefaultClient.Do(req)
89 if err != nil {
90 return nil, fmt.Errorf("token: %w", err)
91 }
92 body, err := io.ReadAll(res.Body)
93 res.Body.Close()
94 if err != nil || res.StatusCode != 200 {
95 return nil, fmt.Errorf("token: %d: %s: %w", res.StatusCode, body, err)
96 }
97 var tokenBody struct {
98 Token string `json:"token"`
99 }
100 if err := json.Unmarshal(body, &tokenBody); err != nil {
101 return nil, fmt.Errorf("token: %w: %s", err, body)
102 }
103
104 req, err = http.NewRequest("GET", "https://ghcr.io/v2/"+dockerImgRepo+"/tags/list", nil)
105 if err != nil {
106 return nil, fmt.Errorf("tags: %w", err)
107 }
108 req.Header.Set("Authorization", "Bearer "+tokenBody.Token)
109 res, err = http.DefaultClient.Do(req)
110 if err != nil {
111 return nil, fmt.Errorf("tags: %w", err)
112 }
113 body, err = io.ReadAll(res.Body)
114 res.Body.Close()
115 if err != nil || res.StatusCode != 200 {
116 return nil, fmt.Errorf("tags: %d: %s: %w", res.StatusCode, body, err)
117 }
118 var tags struct {
119 Tags []string `json:"tags"`
120 }
121 if err := json.Unmarshal(body, &tags); err != nil {
122 return nil, fmt.Errorf("tags: %w: %s", err, body)
123 }
124 return tags.Tags, nil
125}
126
127func checkTagExists(tag string) error {
128 tags, err := readPublishedTags()
129 if err != nil {
130 return fmt.Errorf("check tag exists: %w", err)
131 }
132 for _, t := range tags {
133 if t == tag {
134 return nil // found it
135 }
136 }
137 return fmt.Errorf("check tag exists: %q not found in %v", tag, tags)
138}
David Crawshawbe10fa92025-04-18 01:16:00 -0700139
Earl Lee2e463fb2025-04-17 11:22:22 -0700140// createDockerfile creates a Dockerfile for a git repo.
141// It expects the relevant initFiles to have been provided.
142// If the sketch binary is being executed in a sub-directory of the repository,
143// the relative path is provided on subPathWorkingDir.
144func createDockerfile(ctx context.Context, httpc *http.Client, antURL, antAPIKey string, initFiles map[string]string, subPathWorkingDir string) (string, error) {
145 if subPathWorkingDir == "." {
146 subPathWorkingDir = ""
147 } else if subPathWorkingDir != "" && subPathWorkingDir[0] != '/' {
148 subPathWorkingDir = "/" + subPathWorkingDir
149 }
150 toolCalled := false
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700151 var dockerfileExtraCmds string
Earl Lee2e463fb2025-04-17 11:22:22 -0700152 runDockerfile := func(ctx context.Context, input json.RawMessage) (string, error) {
153 // TODO: unmarshal straight into a struct
154 var m map[string]any
155 if err := json.Unmarshal(input, &m); err != nil {
156 return "", fmt.Errorf(`input=%[1]v (%[1]T), wanted a map[string]any, got: %w`, input, err)
157 }
158 var ok bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700159 dockerfileExtraCmds, ok = m["extra_cmds"].(string)
160 if !ok {
161 return "", fmt.Errorf(`input["extra_cmds"]=%[1]v (%[1]T), wanted a string`, m["path"])
162 }
163 toolCalled = true
164 return "OK", nil
165 }
166 convo := ant.NewConvo(ctx, antAPIKey)
167 if httpc != nil {
168 convo.HTTPC = httpc
169 }
170 if antURL != "" {
171 convo.URL = antURL
172 }
173 convo.Tools = []*ant.Tool{{
174 Name: "dockerfile",
175 Description: "Helps define a Dockerfile that sets up a dev environment for this project.",
176 Run: runDockerfile,
177 InputSchema: ant.MustSchema(`{
178 "type": "object",
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700179 "required": ["extra_cmds"],
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 "properties": {
Earl Lee2e463fb2025-04-17 11:22:22 -0700181 "extra_cmds": {
182 "type": "string",
183 "description": "Extra commands to add to the dockerfile."
184 }
185 }
186}`),
187 }}
188
Earl Lee2e463fb2025-04-17 11:22:22 -0700189 // TODO: it's basically impossible to one-shot a python env. We need an agent loop for that.
190 // Right now the prompt contains a set of half-baked workarounds.
191
192 // If you want to edit the model prompt, run:
193 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700194 // go test ./dockerimg -httprecord ".*" -rewritewant
Earl Lee2e463fb2025-04-17 11:22:22 -0700195 //
196 // Then look at the changes with:
197 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700198 // git diff dockerimg/testdata/*.dockerfile
Earl Lee2e463fb2025-04-17 11:22:22 -0700199 //
200 // If the dockerfile changes are a strict improvement, commit all the changes.
201 msg := ant.Message{
202 Role: ant.MessageRoleUser,
203 Content: []ant.Content{{
204 Type: ant.ContentTypeText,
205 Text: `
206Call the dockerfile tool to create a Dockerfile.
207The parameters to dockerfile fill out the From and ExtraCmds
208template variables in the following Go template:
209
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700210` + "```\n" + dockerfileBase + dockerfileFragment + "\n```" + `
Earl Lee2e463fb2025-04-17 11:22:22 -0700211
212In particular:
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700213- Assume it is primarily a Go project.
Earl Lee2e463fb2025-04-17 11:22:22 -0700214- 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.
215- Include any tools particular to this repository that can be inferred from the given context.
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700216- Append || true to any apt-get install commands in case the package does not exist.
217- MINIMIZE the number of extra_cmds generated. Straightforward environments do not need any.
David Crawshaw11129492025-04-25 20:41:53 -0700218- Do NOT expose any ports.
219- Do NOT generate any CMD or ENTRYPOINT extra commands.
Earl Lee2e463fb2025-04-17 11:22:22 -0700220`,
221 }},
222 }
223 if len(initFiles) > 0 {
224 msg.Content[0].Text += "Here is the content of several files from the repository that may be relevant:\n\n"
225 }
226
227 for _, name := range slices.Sorted(maps.Keys(initFiles)) {
228 msg.Content = append(msg.Content, ant.Content{
229 Type: ant.ContentTypeText,
230 Text: fmt.Sprintf("Here is the contents %s:\n<file>\n%s\n</file>\n\n", name, initFiles[name]),
231 })
232 }
233 msg.Content = append(msg.Content, ant.Content{
234 Type: ant.ContentTypeText,
235 Text: "Now call the dockerfile tool.",
236 })
237 res, err := convo.SendMessage(msg)
238 if err != nil {
239 return "", err
240 }
241 if res.StopReason != ant.StopReasonToolUse {
242 return "", fmt.Errorf("expected stop reason %q, got %q", ant.StopReasonToolUse, res.StopReason)
243 }
244 if _, err := convo.ToolResultContents(context.TODO(), res); err != nil {
245 return "", err
246 }
247 if !toolCalled {
248 return "", fmt.Errorf("no dockerfile returned")
249 }
250
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700251 tmpl := dockerfileDefaultTmpl
252 if tag := dockerfileBaseHash(); checkTagExists(tag) != nil {
253 // In development, if you edit dockerfileBase but don't release
254 // (as is reasonable for testing things!) the hash won't exist
255 // yet. In that case, we skip the sketch image and build it ourselves.
256 fmt.Printf("published container tag %s:%s missing; building locally\n", dockerImgName, tag)
257 tmpl = dockerfileBase + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -0700258 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 buf := new(bytes.Buffer)
David Crawshaw11129492025-04-25 20:41:53 -0700260 err = template.Must(template.New("dockerfile").Parse(tmpl)).Execute(buf, map[string]string{
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700261 "ExtraCmds": dockerfileExtraCmds,
262 "SubDir": subPathWorkingDir,
Earl Lee2e463fb2025-04-17 11:22:22 -0700263 })
264 if err != nil {
265 return "", fmt.Errorf("dockerfile template failed: %w", err)
266 }
267
268 return buf.String(), nil
269}
270
271// 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
272
273func readInitFiles(fsys fs.FS) (map[string]string, error) {
274 result := make(map[string]string)
275
276 err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
277 if err != nil {
278 return err
279 }
280 if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules") {
281 return fs.SkipDir
282 }
283 if !d.Type().IsRegular() {
284 return nil
285 }
286
287 // Case 1: Check for README files
288 // TODO: find README files between the .git root (where we start)
289 // and the dir that sketch was initialized. This needs more info
290 // plumbed to this function.
291 if strings.HasPrefix(strings.ToLower(path), "readme") {
292 content, err := fs.ReadFile(fsys, path)
293 if err != nil {
294 return err
295 }
296 result[path] = string(content)
297 return nil
298 }
299
300 // Case 2: Check for GitHub workflow files
301 if strings.HasPrefix(path, ".github/workflows/") {
302 content, err := fs.ReadFile(fsys, path)
303 if err != nil {
304 return err
305 }
306 result[path] = string(content)
307 return nil
308 }
309
310 return nil
311 })
312 if err != nil {
313 return nil, err
314 }
315 return result, nil
316}