blob: 856303b2bd195be5156d7ebd74875a988472ba5e [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 Crawshaw5228b582025-05-01 11:18:12 -070048# attempt to keep package installs lean
49RUN printf '%s\n' \
50 'path-exclude=/usr/share/man/*' \
51 'path-exclude=/usr/share/doc/*' \
52 'path-exclude=/usr/share/doc-base/*' \
53 'path-exclude=/usr/share/info/*' \
54 'path-exclude=/usr/share/locale/*' \
55 'path-exclude=/usr/share/groff/*' \
56 'path-exclude=/usr/share/lintian/*' \
57 'path-exclude=/usr/share/zoneinfo/*' \
58 > /etc/dpkg/dpkg.cfg.d/01_nodoc
59
60RUN --mount=type=cache,target=/var/cache/apt \
61 set -eux; \
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070062 apt-get update; \
63 apt-get install -y --no-install-recommends \
64 git jq sqlite3 npm nodejs gh ripgrep fzf python3 curl vim
David Crawshawbe10fa92025-04-18 01:16:00 -070065
David Crawshaw5228b582025-05-01 11:18:12 -070066# Strip out docs from debian.
67RUN rm -rf /usr/share/{doc,doc-base,info,lintian,man,groff,locale,zoneinfo}/*
68
David Crawshawbe10fa92025-04-18 01:16:00 -070069ENV PATH="$GOPATH/bin:$PATH"
70
David Crawshaw5228b582025-05-01 11:18:12 -070071# While these binaries install generally useful supporting packages,
72# the specific versions are rarely what a user wants so there is no
73# point polluting the base image module with them.
74
75RUN --mount=type=cache,target=/go/pkg/mod \
76 --mount=type=cache,target=/root/.cache/go-build \
77 set -eux; \
78 go install golang.org/x/tools/cmd/goimports@latest; \
79 go install golang.org/x/tools/gopls@latest; \
80 go install mvdan.cc/gofumpt@latest; \
81 go clean -cache -testcache
David Crawshawbe10fa92025-04-18 01:16:00 -070082
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070083ENV GOTOOLCHAIN=auto
David Crawshaw5228b582025-05-01 11:18:12 -070084ENV SKETCH=1
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070085
David Crawshawbe10fa92025-04-18 01:16:00 -070086RUN mkdir -p /root/.cache/sketch/webui
David Crawshaw11129492025-04-25 20:41:53 -070087`
David Crawshawbe10fa92025-04-18 01:16:00 -070088
David Crawshaw11129492025-04-25 20:41:53 -070089const dockerfileFragment = `
David Crawshawbe10fa92025-04-18 01:16:00 -070090ARG GIT_USER_EMAIL
91ARG GIT_USER_NAME
92
93RUN git config --global user.email "$GIT_USER_EMAIL" && \
94 git config --global user.name "$GIT_USER_NAME"
95
Josh Bleecher Snyderc76a3922025-05-01 01:18:56 +000096LABEL sketch_context="{{.InitFilesHash}}"
David Crawshawbe10fa92025-04-18 01:16:00 -070097COPY . /app
98
99WORKDIR /app{{.SubDir}}
100RUN if [ -f go.mod ]; then go mod download; fi
101
David Crawshaw11129492025-04-25 20:41:53 -0700102{{.ExtraCmds}}
103
104CMD ["/bin/sketch"]
105`
106
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700107var dockerfileDefaultTmpl = "FROM " + dockerImgName + ":" + dockerfileBaseHash() + "\n" + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -0700108
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700109func readPublishedTags() ([]string, error) {
110 req, err := http.NewRequest("GET", "https://ghcr.io/token?service=ghcr.io&scope=repository:"+dockerImgRepo+":pull", nil)
111 if err != nil {
112 return nil, fmt.Errorf("token: %w", err)
113 }
114 res, err := http.DefaultClient.Do(req)
115 if err != nil {
116 return nil, fmt.Errorf("token: %w", err)
117 }
118 body, err := io.ReadAll(res.Body)
119 res.Body.Close()
120 if err != nil || res.StatusCode != 200 {
121 return nil, fmt.Errorf("token: %d: %s: %w", res.StatusCode, body, err)
122 }
123 var tokenBody struct {
124 Token string `json:"token"`
125 }
126 if err := json.Unmarshal(body, &tokenBody); err != nil {
127 return nil, fmt.Errorf("token: %w: %s", err, body)
128 }
129
130 req, err = http.NewRequest("GET", "https://ghcr.io/v2/"+dockerImgRepo+"/tags/list", nil)
131 if err != nil {
132 return nil, fmt.Errorf("tags: %w", err)
133 }
134 req.Header.Set("Authorization", "Bearer "+tokenBody.Token)
135 res, err = http.DefaultClient.Do(req)
136 if err != nil {
137 return nil, fmt.Errorf("tags: %w", err)
138 }
139 body, err = io.ReadAll(res.Body)
140 res.Body.Close()
141 if err != nil || res.StatusCode != 200 {
142 return nil, fmt.Errorf("tags: %d: %s: %w", res.StatusCode, body, err)
143 }
144 var tags struct {
145 Tags []string `json:"tags"`
146 }
147 if err := json.Unmarshal(body, &tags); err != nil {
148 return nil, fmt.Errorf("tags: %w: %s", err, body)
149 }
150 return tags.Tags, nil
151}
152
153func checkTagExists(tag string) error {
154 tags, err := readPublishedTags()
155 if err != nil {
156 return fmt.Errorf("check tag exists: %w", err)
157 }
158 for _, t := range tags {
159 if t == tag {
160 return nil // found it
161 }
162 }
163 return fmt.Errorf("check tag exists: %q not found in %v", tag, tags)
164}
David Crawshawbe10fa92025-04-18 01:16:00 -0700165
Earl Lee2e463fb2025-04-17 11:22:22 -0700166// createDockerfile creates a Dockerfile for a git repo.
167// It expects the relevant initFiles to have been provided.
168// If the sketch binary is being executed in a sub-directory of the repository,
169// the relative path is provided on subPathWorkingDir.
170func createDockerfile(ctx context.Context, httpc *http.Client, antURL, antAPIKey string, initFiles map[string]string, subPathWorkingDir string) (string, error) {
171 if subPathWorkingDir == "." {
172 subPathWorkingDir = ""
173 } else if subPathWorkingDir != "" && subPathWorkingDir[0] != '/' {
174 subPathWorkingDir = "/" + subPathWorkingDir
175 }
176 toolCalled := false
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700177 var dockerfileExtraCmds string
Earl Lee2e463fb2025-04-17 11:22:22 -0700178 runDockerfile := func(ctx context.Context, input json.RawMessage) (string, error) {
179 // TODO: unmarshal straight into a struct
180 var m map[string]any
181 if err := json.Unmarshal(input, &m); err != nil {
182 return "", fmt.Errorf(`input=%[1]v (%[1]T), wanted a map[string]any, got: %w`, input, err)
183 }
184 var ok bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700185 dockerfileExtraCmds, ok = m["extra_cmds"].(string)
186 if !ok {
187 return "", fmt.Errorf(`input["extra_cmds"]=%[1]v (%[1]T), wanted a string`, m["path"])
188 }
189 toolCalled = true
190 return "OK", nil
191 }
192 convo := ant.NewConvo(ctx, antAPIKey)
193 if httpc != nil {
194 convo.HTTPC = httpc
195 }
196 if antURL != "" {
197 convo.URL = antURL
198 }
199 convo.Tools = []*ant.Tool{{
200 Name: "dockerfile",
201 Description: "Helps define a Dockerfile that sets up a dev environment for this project.",
202 Run: runDockerfile,
203 InputSchema: ant.MustSchema(`{
204 "type": "object",
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700205 "required": ["extra_cmds"],
Earl Lee2e463fb2025-04-17 11:22:22 -0700206 "properties": {
Earl Lee2e463fb2025-04-17 11:22:22 -0700207 "extra_cmds": {
208 "type": "string",
209 "description": "Extra commands to add to the dockerfile."
210 }
211 }
212}`),
213 }}
214
Earl Lee2e463fb2025-04-17 11:22:22 -0700215 // TODO: it's basically impossible to one-shot a python env. We need an agent loop for that.
216 // Right now the prompt contains a set of half-baked workarounds.
217
218 // If you want to edit the model prompt, run:
219 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700220 // go test ./dockerimg -httprecord ".*" -rewritewant
Earl Lee2e463fb2025-04-17 11:22:22 -0700221 //
222 // Then look at the changes with:
223 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700224 // git diff dockerimg/testdata/*.dockerfile
Earl Lee2e463fb2025-04-17 11:22:22 -0700225 //
226 // If the dockerfile changes are a strict improvement, commit all the changes.
227 msg := ant.Message{
228 Role: ant.MessageRoleUser,
229 Content: []ant.Content{{
230 Type: ant.ContentTypeText,
231 Text: `
232Call the dockerfile tool to create a Dockerfile.
233The parameters to dockerfile fill out the From and ExtraCmds
234template variables in the following Go template:
235
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700236` + "```\n" + dockerfileBase + dockerfileFragment + "\n```" + `
Earl Lee2e463fb2025-04-17 11:22:22 -0700237
238In particular:
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700239- Assume it is primarily a Go project.
Earl Lee2e463fb2025-04-17 11:22:22 -0700240- 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.
241- Include any tools particular to this repository that can be inferred from the given context.
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700242- Append || true to any apt-get install commands in case the package does not exist.
243- MINIMIZE the number of extra_cmds generated. Straightforward environments do not need any.
David Crawshaw11129492025-04-25 20:41:53 -0700244- Do NOT expose any ports.
245- Do NOT generate any CMD or ENTRYPOINT extra commands.
Earl Lee2e463fb2025-04-17 11:22:22 -0700246`,
247 }},
248 }
249 if len(initFiles) > 0 {
250 msg.Content[0].Text += "Here is the content of several files from the repository that may be relevant:\n\n"
251 }
252
253 for _, name := range slices.Sorted(maps.Keys(initFiles)) {
Josh Bleecher Snydera3dcd862025-04-30 19:47:16 +0000254 msg.Content = append(msg.Content, ant.StringContent(fmt.Sprintf("Here is the contents %s:\n<file>\n%s\n</file>\n\n", name, initFiles[name])))
Earl Lee2e463fb2025-04-17 11:22:22 -0700255 }
Josh Bleecher Snydera3dcd862025-04-30 19:47:16 +0000256 msg.Content = append(msg.Content, ant.StringContent("Now call the dockerfile tool."))
Earl Lee2e463fb2025-04-17 11:22:22 -0700257 res, err := convo.SendMessage(msg)
258 if err != nil {
259 return "", err
260 }
261 if res.StopReason != ant.StopReasonToolUse {
262 return "", fmt.Errorf("expected stop reason %q, got %q", ant.StopReasonToolUse, res.StopReason)
263 }
264 if _, err := convo.ToolResultContents(context.TODO(), res); err != nil {
265 return "", err
266 }
267 if !toolCalled {
268 return "", fmt.Errorf("no dockerfile returned")
269 }
270
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700271 tmpl := dockerfileDefaultTmpl
272 if tag := dockerfileBaseHash(); checkTagExists(tag) != nil {
273 // In development, if you edit dockerfileBase but don't release
274 // (as is reasonable for testing things!) the hash won't exist
275 // yet. In that case, we skip the sketch image and build it ourselves.
276 fmt.Printf("published container tag %s:%s missing; building locally\n", dockerImgName, tag)
277 tmpl = dockerfileBase + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -0700278 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700279 buf := new(bytes.Buffer)
David Crawshaw11129492025-04-25 20:41:53 -0700280 err = template.Must(template.New("dockerfile").Parse(tmpl)).Execute(buf, map[string]string{
Josh Bleecher Snyderc76a3922025-05-01 01:18:56 +0000281 "ExtraCmds": dockerfileExtraCmds,
282 "SubDir": subPathWorkingDir,
283 "InitFilesHash": hashInitFiles(initFiles),
Earl Lee2e463fb2025-04-17 11:22:22 -0700284 })
285 if err != nil {
286 return "", fmt.Errorf("dockerfile template failed: %w", err)
287 }
288
289 return buf.String(), nil
290}
291
292// 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
293
294func readInitFiles(fsys fs.FS) (map[string]string, error) {
295 result := make(map[string]string)
296
297 err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
298 if err != nil {
299 return err
300 }
301 if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules") {
302 return fs.SkipDir
303 }
304 if !d.Type().IsRegular() {
305 return nil
306 }
307
308 // Case 1: Check for README files
309 // TODO: find README files between the .git root (where we start)
310 // and the dir that sketch was initialized. This needs more info
311 // plumbed to this function.
312 if strings.HasPrefix(strings.ToLower(path), "readme") {
313 content, err := fs.ReadFile(fsys, path)
314 if err != nil {
315 return err
316 }
317 result[path] = string(content)
318 return nil
319 }
320
321 // Case 2: Check for GitHub workflow files
322 if strings.HasPrefix(path, ".github/workflows/") {
323 content, err := fs.ReadFile(fsys, path)
324 if err != nil {
325 return err
326 }
327 result[path] = string(content)
328 return nil
329 }
330
331 return nil
332 })
333 if err != nil {
334 return nil, err
335 }
336 return result, nil
337}