blob: b47f7d95b879d23c3e8cfc3b06fd214313c6a68a [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
21 "time"
22
Sean McCulloughbaa2b592025-04-23 10:40:08 -070023 "sketch.dev/loop/server"
David Crawshaw8bff16a2025-04-18 01:16:49 -070024 "sketch.dev/loop/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070025 "sketch.dev/skribe"
26)
27
28// ContainerConfig holds all configuration for launching a container
29type ContainerConfig struct {
30 // SessionID is the unique identifier for this session
31 SessionID string
32
33 // LocalAddr is the initial address to use (though it may be overwritten later)
34 LocalAddr string
35
36 // SkabandAddr is the address of the skaband service if available
37 SkabandAddr string
38
39 // AntURL is the URL of the LLM service.
40 AntURL string
41
42 // AntAPIKey is the API key for LLM service.
43 AntAPIKey string
44
45 // Path is the local filesystem path to use
46 Path string
47
48 // GitUsername is the username to use for git operations
49 GitUsername string
50
51 // GitEmail is the email to use for git operations
52 GitEmail string
53
54 // OpenBrowser determines whether to open a browser automatically
55 OpenBrowser bool
56
57 // NoCleanup prevents container cleanup when set to true
58 NoCleanup bool
59
60 // ForceRebuild forces rebuilding of the Docker image even if it exists
61 ForceRebuild bool
62
63 // Host directory to copy container logs into, if not set to ""
64 ContainerLogDest string
65
66 // Path to pre-built linux sketch binary, or build a new one if set to ""
67 SketchBinaryLinux string
68
69 // Sketch client public key.
70 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000071
Sean McCulloughbaa2b592025-04-23 10:40:08 -070072 // Host port for the container's ssh server
73 SSHPort int
74
75 // Public keys authorized to connect to the container's ssh server
76 SSHAuthorizedKeys []byte
77
78 // Private key used to identify the container's ssh server
79 SSHServerIdentity []byte
80
Philip Zeyligerd1402952025-04-23 03:54:37 +000081 // Host information to pass to the container
82 HostHostname string
83 HostOS string
84 HostWorkingDir string
Earl Lee2e463fb2025-04-17 11:22:22 -070085}
86
87// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
88// It writes status to stdout.
89func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
90 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070091 if runtime.GOOS == "darwin" {
92 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
93 } else {
94 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
95 }
Earl Lee2e463fb2025-04-17 11:22:22 -070096 }
97
98 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
99 // `docker ps` provides a good error message here that can be
100 // easily chatgpt'ed by users, so send it to the user as-is:
101 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
102 return fmt.Errorf("docker ps: %s (%w)", out, err)
103 }
104
105 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
106 if err != nil {
107 return err
108 }
109
110 gitRoot, err := findGitRoot(ctx, config.Path)
111 if err != nil {
112 return err
113 }
114
115 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
116 if err != nil {
117 return err
118 }
119
120 linuxSketchBin := config.SketchBinaryLinux
121 if linuxSketchBin == "" {
122 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
123 if err != nil {
124 return err
125 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700126 defer os.Remove(linuxSketchBin) // in case of errors
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 }
128
129 cntrName := imgName + "-" + config.SessionID
130 defer func() {
131 if config.NoCleanup {
132 return
133 }
134 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
135 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
136 _ = out
137 }
138 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
139 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
140 _ = out
141 }
142 }()
143
144 // errCh receives errors from operations that this function calls in separate goroutines.
145 errCh := make(chan error)
146
147 // Start the git server
148 gitSrv, err := newGitServer(gitRoot)
149 if err != nil {
150 return fmt.Errorf("failed to start git server: %w", err)
151 }
152 defer gitSrv.shutdown(ctx)
153
154 go func() {
155 errCh <- gitSrv.serve(ctx)
156 }()
157
158 // Get the current host git commit
159 var commit string
160 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
161 return fmt.Errorf("git rev-parse HEAD: %w", err)
162 } else {
163 commit = strings.TrimSpace(string(out))
164 }
165 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
166 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
167 }
168
169 relPath, err := filepath.Rel(gitRoot, config.Path)
170 if err != nil {
171 return err
172 }
173
174 // Create the sketch container
175 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
176 return err
177 }
178
179 // Copy the sketch linux binary into the container
180 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
181 return fmt.Errorf("docker cp: %s, %w", out, err)
182 }
Josh Bleecher Snyder5544d142025-04-23 14:15:45 -0700183 os.Remove(linuxSketchBin) // in normal operations, the code below blocks, so actively delete now
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700184
185 // Make sure that the webui is built so we can copy the results to the container.
186 _, err = webui.Build()
187 if err != nil {
188 return fmt.Errorf("failed to build webui: %w", err)
189 }
190
David Crawshaw8bff16a2025-04-18 01:16:49 -0700191 webuiZipPath, err := webui.ZipPath()
192 if err != nil {
193 return err
194 }
195 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
196 return fmt.Errorf("docker cp: %s, %w", out, err)
197 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700198
199 fmt.Printf("starting container %s\ncommits made by the agent will be pushed to \033[1msketch/*\033[0m\n", cntrName)
200
201 // Start the sketch container
202 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
203 return fmt.Errorf("docker start: %s, %w", out, err)
204 }
205
206 // Copies structured logs from the container to the host.
207 copyLogs := func() {
208 if config.ContainerLogDest == "" {
209 return
210 }
211 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
212 if err != nil {
213 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
214 return
215 }
216 logLines := strings.Split(string(out), "\n")
217 for _, logLine := range logLines {
218 if !strings.HasPrefix(logLine, "structured logs:") {
219 continue
220 }
221 logFile := strings.TrimSpace(strings.TrimPrefix(logLine, "structured logs:"))
222 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
223 logFileName := filepath.Base(logFile)
224 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
225 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
226 if err != nil {
227 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
228 }
229 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
230 }
231 }
232
233 // NOTE: we want to see what the internal sketch binary prints
234 // regardless of the setting of the verbosity flag on the external
235 // binary, so reading "docker logs", which is the stdout/stderr of
236 // the internal binary is not conditional on the verbose flag.
237 appendInternalErr := func(err error) error {
238 if err == nil {
239 return nil
240 }
241 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000242 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700243 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
244 }
245 out = bytes.TrimSpace(out)
246 if len(out) > 0 {
247 return fmt.Errorf("docker logs: %s;\n%w", out, err)
248 }
249 return err
250 }
251
252 // Get the sketch server port from the container
253 localAddr, err := getContainerPort(ctx, cntrName)
254 if err != nil {
255 return appendInternalErr(err)
256 }
257
258 // Tell the sketch container which git server port and commit to initialize with.
259 go func() {
260 // TODO: Why is this called in a goroutine? I have found that when I pull this out
261 // of the goroutine and call it inline, then the terminal UI clears itself and all
262 // the scrollback (which is not good, but also not fatal). I can't see why it does this
263 // though, since none of the calls in postContainerInitConfig obviously write to stdout
264 // or stderr.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700265 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, config.SSHServerIdentity, config.SSHAuthorizedKeys); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700266 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
267 errCh <- appendInternalErr(err)
268 }
269 }()
270
271 if config.OpenBrowser {
272 OpenBrowser(ctx, "http://"+localAddr)
273 }
274
275 go func() {
276 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
277 cmd.Stdin = os.Stdin
278 cmd.Stdout = os.Stdout
279 cmd.Stderr = os.Stderr
280 errCh <- run(ctx, "docker attach", cmd)
281 }()
282
283 defer copyLogs()
284
285 for {
286 select {
287 case <-ctx.Done():
288 return ctx.Err()
289 case err := <-errCh:
290 if err != nil {
291 return appendInternalErr(fmt.Errorf("container process: %w", err))
292 }
293 return nil
294 }
295 }
296}
297
298func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
299 cmd := exec.CommandContext(ctx, cmdName, args...)
300 // Really only needed for the "go build" command for the linux sketch binary
301 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0")
302 start := time.Now()
303
304 out, err := cmd.CombinedOutput()
305 if err != nil {
306 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
307 } else {
308 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
309 }
310 return out, err
311}
312
313func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
314 start := time.Now()
315 err := cmd.Run()
316 if err != nil {
317 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
318 } else {
319 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
320 }
321 return err
322}
323
324type gitServer struct {
325 gitLn net.Listener
326 gitPort string
327 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700328 pass string
Earl Lee2e463fb2025-04-17 11:22:22 -0700329}
330
331func (gs *gitServer) shutdown(ctx context.Context) {
332 gs.srv.Shutdown(ctx)
333 gs.gitLn.Close()
334}
335
336// Serve a git remote from the host for the container to fetch from and push to.
337func (gs *gitServer) serve(ctx context.Context) error {
338 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
339 return gs.srv.Serve(gs.gitLn)
340}
341
342func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700343 ret := &gitServer{
344 pass: rand.Text(),
345 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700346
Earl Lee2e463fb2025-04-17 11:22:22 -0700347 gitLn, err := net.Listen("tcp4", ":0")
348 if err != nil {
349 return nil, fmt.Errorf("git listen: %w", err)
350 }
351 ret.gitLn = gitLn
352
353 srv := http.Server{
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700354 Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass)},
Earl Lee2e463fb2025-04-17 11:22:22 -0700355 }
356 ret.srv = &srv
357
358 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
359 if err != nil {
360 return nil, fmt.Errorf("git port: %w", err)
361 }
362 ret.gitPort = gitPort
363 return ret, nil
364}
365
366func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
367 //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr
368 // sessionID, gitUsername, gitEmail, skabandAddr string
David Crawshaw69c67312025-04-17 13:42:00 -0700369 cmdArgs := []string{
370 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700371 "-it",
372 "--name", cntrName,
373 "-p", hostPort + ":80", // forward container port 80 to a host port
374 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
375 }
376 if config.AntURL != "" {
377 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
378 }
379 if config.SketchPubKey != "" {
380 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
381 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700382 if config.SSHPort != 0 {
383 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:2022", config.SSHPort)) // forward container ssh port to host ssh port
384 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 if relPath != "." {
386 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
387 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700388 // colima does this by default, but Linux docker seems to need this set explicitly
389 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700390 cmdArgs = append(
391 cmdArgs,
392 imgName,
393 "/bin/sketch",
394 "-unsafe",
395 "-addr=:80",
396 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000397 "-git-username="+config.GitUsername,
398 "-git-email="+config.GitEmail,
399 "-host-hostname="+config.HostHostname,
400 "-host-os="+config.HostOS,
401 "-host-working-dir="+config.HostWorkingDir,
Earl Lee2e463fb2025-04-17 11:22:22 -0700402 )
403 if config.SkabandAddr != "" {
404 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
405 }
406 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
407 return fmt.Errorf("docker create: %s, %w", out, err)
408 }
409 return nil
410}
411
412func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700413 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700414 if err != nil {
415 return "", err
416 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700417 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
418 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
419 return "", err
420 }
421
422 verToInstall := "@latest"
423 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
424 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
425 } else {
426 if strings.TrimSpace(string(out)) == "sketch.dev" {
427 fmt.Printf("building linux agent from currently checked out module\n")
428 verToInstall = ""
429 }
430 }
David Crawshaw69c67312025-04-17 13:42:00 -0700431
Earl Lee2e463fb2025-04-17 11:22:22 -0700432 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700433 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700434 cmd.Env = append(
435 os.Environ(),
436 "GOOS=linux",
437 "CGO_ENABLED=0",
438 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700439 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700440 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700441 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700442
443 fmt.Printf("building linux agent binary...\n")
444 out, err := cmd.CombinedOutput()
445 if err != nil {
446 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
447 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
448 } else {
449 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
450 }
451
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700452 var src string
453 if runtime.GOOS != "linux" {
454 src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
455 } else {
456 // If we are already on Linux, there's no extra platform name in the path
457 src = filepath.Join(linuxGopath, "bin", "sketch")
458 }
459
David Crawshaw69c67312025-04-17 13:42:00 -0700460 dst := filepath.Join(path, "tmp-sketch-binary-linux")
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700461 if err := moveFile(src, dst); err != nil {
David Crawshaw69c67312025-04-17 13:42:00 -0700462 return "", err
463 }
464
Earl Lee2e463fb2025-04-17 11:22:22 -0700465 fmt.Printf("built linux agent binary in %s\n", time.Since(start).Round(100*time.Millisecond))
466
David Crawshaw69c67312025-04-17 13:42:00 -0700467 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700468}
469
470func getContainerPort(ctx context.Context, cntrName string) (string, error) {
471 localAddr := ""
472 if out, err := combinedOutput(ctx, "docker", "port", cntrName, "80"); err != nil {
473 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
474 } else {
475 v4, _, found := strings.Cut(string(out), "\n")
476 if !found {
477 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
478 }
479 localAddr = v4
480 if strings.HasPrefix(localAddr, "0.0.0.0") {
481 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
482 }
483 }
484 return localAddr, nil
485}
486
487// Contact the container and configure it.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700488func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700489 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700490
491 initMsg, err := json.Marshal(
492 server.InitRequest{
493 Commit: commit,
494 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
495 HostAddr: localAddr,
496 SSHAuthorizedKeys: sshAuthorizedKeys,
497 SSHServerIdentity: sshServerIdentity,
498 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700499 if err != nil {
500 return fmt.Errorf("init msg: %w", err)
501 }
502
503 slog.DebugContext(ctx, "/init POST", slog.String("initMsg", string(initMsg)))
504
505 // Note: this /init POST is handled in loop/server/loophttp.go:
506 initMsgByteReader := bytes.NewReader(initMsg)
507 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
508 if err != nil {
509 return err
510 }
511
512 var res *http.Response
513 for i := 0; ; i++ {
514 time.Sleep(100 * time.Millisecond)
515 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
516 initMsgByteReader.Reset(initMsg)
517 res, err = http.DefaultClient.Do(req)
518 if err != nil {
519 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
520 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
521 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
522 continue
523 }
524 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
525 }
526 break
527 }
528 resBytes, _ := io.ReadAll(res.Body)
529 if res.StatusCode != http.StatusOK {
530 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
531 }
532 return nil
533}
534
535func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
536 h := sha256.Sum256([]byte(gitRoot))
537 imgName = "sketch-" + hex.EncodeToString(h[:6])
538
539 var curImgInitFilesHash string
540 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
541 if strings.Contains(string(out), "No such object") {
542 // Image does not exist, continue and build it.
543 curImgInitFilesHash = ""
544 } else {
545 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
546 }
547 } else {
548 m := map[string]string{}
549 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
550 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
551 }
552 curImgInitFilesHash = m["sketch_context"]
553 }
554
555 candidates, err := findRepoDockerfiles(cwd, gitRoot)
556 if err != nil {
557 return "", fmt.Errorf("find dockerfile: %w", err)
558 }
559
560 var initFiles map[string]string
561 var dockerfilePath string
562
563 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
564 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
565 dockerfilePath = candidates[0]
566 contents, err := os.ReadFile(dockerfilePath)
567 if err != nil {
568 return "", err
569 }
570 fmt.Printf("using %s as dev env\n", candidates[0])
571 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
572 fmt.Printf("using existing docker image %s\n", imgName)
573 return imgName, nil
574 }
575 } else {
576 initFiles, err = readInitFiles(os.DirFS(gitRoot))
577 if err != nil {
578 return "", err
579 }
580 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
581 if err != nil {
582 return "", err
583 }
584 initFileHash := hashInitFiles(initFiles)
585 if curImgInitFilesHash == initFileHash && !forceRebuild {
586 fmt.Printf("using existing docker image %s\n", imgName)
587 return imgName, nil
588 }
589
590 start := time.Now()
591 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
592 if err != nil {
593 return "", fmt.Errorf("create dockerfile: %w", err)
594 }
595 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
596 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
597 return "", err
598 }
599 defer os.Remove(dockerfilePath)
600
601 fmt.Fprintf(stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(dockerfile, "\n", "\n\t", -1))
602 }
603
604 var gitUserEmail, gitUserName string
605 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
606 return "", fmt.Errorf("git config: %s: %v", out, err)
607 } else {
608 gitUserEmail = strings.TrimSpace(string(out))
609 }
610 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
611 return "", fmt.Errorf("git config: %s: %v", out, err)
612 } else {
613 gitUserName = strings.TrimSpace(string(out))
614 }
615
616 start := time.Now()
617 cmd := exec.CommandContext(ctx,
618 "docker", "build",
619 "-t", imgName,
620 "-f", dockerfilePath,
621 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
622 "--build-arg", "GIT_USER_NAME="+gitUserName,
623 ".",
624 )
625 cmd.Dir = gitRoot
626 cmd.Stdout = stdout
627 cmd.Stderr = stderr
628 fmt.Printf("building docker image %s...\n", imgName)
629
630 err = run(ctx, "docker build", cmd)
631 if err != nil {
632 return "", fmt.Errorf("docker build failed: %v", err)
633 }
634 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
635 return imgName, nil
636}
637
638func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
639 files, err := findDirDockerfiles(cwd)
640 if err != nil {
641 return nil, err
642 }
643 if len(files) > 0 {
644 return files, nil
645 }
646
647 path := cwd
648 for path != gitRoot {
649 path = filepath.Dir(path)
650 files, err := findDirDockerfiles(path)
651 if err != nil {
652 return nil, err
653 }
654 if len(files) > 0 {
655 return files, nil
656 }
657 }
658 return files, nil
659}
660
661// findDirDockerfiles finds all "Dockerfile*" files in a directory.
662func findDirDockerfiles(root string) (res []string, err error) {
663 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
664 if err != nil {
665 return err
666 }
667 if info.IsDir() && root != path {
668 return filepath.SkipDir
669 }
670 name := strings.ToLower(info.Name())
671 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
672 res = append(res, path)
673 }
674 return nil
675 })
676 if err != nil {
677 return nil, err
678 }
679 return res, nil
680}
681
682func findGitRoot(ctx context.Context, path string) (string, error) {
683 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
684 cmd.Dir = path
685 out, err := cmd.CombinedOutput()
686 if err != nil {
687 if strings.Contains(string(out), "not a git repository") {
688 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
689Consider one of the following options:
690 - cd to a different dir that is already part of a git repo first, or
691 - to create a new git repo from this directory (%s), run this command:
692
693 git init . && git commit --allow-empty -m "initial commit"
694
695and try running sketch again.
696`, path, path)
697 }
698 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
699 }
700 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
701 absGitDir := filepath.Join(path, gitDir)
702 return filepath.Dir(absGitDir), err
703}
704
705func OpenBrowser(ctx context.Context, url string) {
706 var cmd *exec.Cmd
707 switch runtime.GOOS {
708 case "darwin":
709 cmd = exec.CommandContext(ctx, "open", url)
710 case "windows":
711 cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url)
712 default: // Linux and other Unix-like systems
713 cmd = exec.CommandContext(ctx, "xdg-open", url)
714 }
715 if b, err := cmd.CombinedOutput(); err != nil {
716 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
717 }
718}
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700719
720// moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails,
721// copies and deletes
722func moveFile(src, dst string) error {
723 if err := os.Rename(src, dst); err == nil {
724 return nil
725 }
726
727 stat, err := os.Stat(src)
728 if err != nil {
729 return err
730 }
731
732 sourceFile, err := os.Open(src)
733 if err != nil {
734 return err
735 }
736 defer sourceFile.Close()
737
738 destFile, err := os.Create(dst)
739 if err != nil {
740 return err
741 }
742 defer destFile.Close()
743
744 _, err = io.Copy(destFile, sourceFile)
745 if err != nil {
746 return err
747 }
748
749 sourceFile.Close()
750 destFile.Close()
751
752 os.Chmod(dst, stat.Mode())
753
754 return os.Remove(src)
755}