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