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