blob: 90121fae2b88ba53e05f9e6feb60c26aac3bc9d1 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "fmt"
11 "io"
12 "log/slog"
13 "net"
14 "net/http"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "runtime"
19 "strings"
20 "time"
21
David Crawshaw8bff16a2025-04-18 01:16:49 -070022 "sketch.dev/loop/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070023 "sketch.dev/skribe"
24)
25
26// ContainerConfig holds all configuration for launching a container
27type ContainerConfig struct {
28 // SessionID is the unique identifier for this session
29 SessionID string
30
31 // LocalAddr is the initial address to use (though it may be overwritten later)
32 LocalAddr string
33
34 // SkabandAddr is the address of the skaband service if available
35 SkabandAddr string
36
37 // AntURL is the URL of the LLM service.
38 AntURL string
39
40 // AntAPIKey is the API key for LLM service.
41 AntAPIKey string
42
43 // Path is the local filesystem path to use
44 Path string
45
46 // GitUsername is the username to use for git operations
47 GitUsername string
48
49 // GitEmail is the email to use for git operations
50 GitEmail string
51
52 // OpenBrowser determines whether to open a browser automatically
53 OpenBrowser bool
54
55 // NoCleanup prevents container cleanup when set to true
56 NoCleanup bool
57
58 // ForceRebuild forces rebuilding of the Docker image even if it exists
59 ForceRebuild bool
60
61 // Host directory to copy container logs into, if not set to ""
62 ContainerLogDest string
63
64 // Path to pre-built linux sketch binary, or build a new one if set to ""
65 SketchBinaryLinux string
66
67 // Sketch client public key.
68 SketchPubKey string
69}
70
71// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
72// It writes status to stdout.
73func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error {
74 if _, err := exec.LookPath("docker"); err != nil {
75 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
76 }
77
78 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
79 // `docker ps` provides a good error message here that can be
80 // easily chatgpt'ed by users, so send it to the user as-is:
81 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
82 return fmt.Errorf("docker ps: %s (%w)", out, err)
83 }
84
85 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
86 if err != nil {
87 return err
88 }
89
90 gitRoot, err := findGitRoot(ctx, config.Path)
91 if err != nil {
92 return err
93 }
94
95 imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild)
96 if err != nil {
97 return err
98 }
99
100 linuxSketchBin := config.SketchBinaryLinux
101 if linuxSketchBin == "" {
102 linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path)
103 if err != nil {
104 return err
105 }
106 defer os.Remove(linuxSketchBin)
107 }
108
109 cntrName := imgName + "-" + config.SessionID
110 defer func() {
111 if config.NoCleanup {
112 return
113 }
114 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
115 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
116 _ = out
117 }
118 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
119 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
120 _ = out
121 }
122 }()
123
124 // errCh receives errors from operations that this function calls in separate goroutines.
125 errCh := make(chan error)
126
127 // Start the git server
128 gitSrv, err := newGitServer(gitRoot)
129 if err != nil {
130 return fmt.Errorf("failed to start git server: %w", err)
131 }
132 defer gitSrv.shutdown(ctx)
133
134 go func() {
135 errCh <- gitSrv.serve(ctx)
136 }()
137
138 // Get the current host git commit
139 var commit string
140 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
141 return fmt.Errorf("git rev-parse HEAD: %w", err)
142 } else {
143 commit = strings.TrimSpace(string(out))
144 }
145 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
146 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
147 }
148
149 relPath, err := filepath.Rel(gitRoot, config.Path)
150 if err != nil {
151 return err
152 }
153
154 // Create the sketch container
155 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
156 return err
157 }
158
159 // Copy the sketch linux binary into the container
160 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
161 return fmt.Errorf("docker cp: %s, %w", out, err)
162 }
David Crawshaw8bff16a2025-04-18 01:16:49 -0700163 webuiZipPath, err := webui.ZipPath()
164 if err != nil {
165 return err
166 }
167 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
168 return fmt.Errorf("docker cp: %s, %w", out, err)
169 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700170
171 fmt.Printf("starting container %s\ncommits made by the agent will be pushed to \033[1msketch/*\033[0m\n", cntrName)
172
173 // Start the sketch container
174 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
175 return fmt.Errorf("docker start: %s, %w", out, err)
176 }
177
178 // Copies structured logs from the container to the host.
179 copyLogs := func() {
180 if config.ContainerLogDest == "" {
181 return
182 }
183 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
184 if err != nil {
185 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
186 return
187 }
188 logLines := strings.Split(string(out), "\n")
189 for _, logLine := range logLines {
190 if !strings.HasPrefix(logLine, "structured logs:") {
191 continue
192 }
193 logFile := strings.TrimSpace(strings.TrimPrefix(logLine, "structured logs:"))
194 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
195 logFileName := filepath.Base(logFile)
196 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
197 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
198 if err != nil {
199 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
200 }
201 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
202 }
203 }
204
205 // NOTE: we want to see what the internal sketch binary prints
206 // regardless of the setting of the verbosity flag on the external
207 // binary, so reading "docker logs", which is the stdout/stderr of
208 // the internal binary is not conditional on the verbose flag.
209 appendInternalErr := func(err error) error {
210 if err == nil {
211 return nil
212 }
213 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
214 if err != nil {
215 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
216 }
217 out = bytes.TrimSpace(out)
218 if len(out) > 0 {
219 return fmt.Errorf("docker logs: %s;\n%w", out, err)
220 }
221 return err
222 }
223
224 // Get the sketch server port from the container
225 localAddr, err := getContainerPort(ctx, cntrName)
226 if err != nil {
227 return appendInternalErr(err)
228 }
229
230 // Tell the sketch container which git server port and commit to initialize with.
231 go func() {
232 // TODO: Why is this called in a goroutine? I have found that when I pull this out
233 // of the goroutine and call it inline, then the terminal UI clears itself and all
234 // the scrollback (which is not good, but also not fatal). I can't see why it does this
235 // though, since none of the calls in postContainerInitConfig obviously write to stdout
236 // or stderr.
237 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort); err != nil {
238 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
239 errCh <- appendInternalErr(err)
240 }
241 }()
242
243 if config.OpenBrowser {
244 OpenBrowser(ctx, "http://"+localAddr)
245 }
246
247 go func() {
248 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
249 cmd.Stdin = os.Stdin
250 cmd.Stdout = os.Stdout
251 cmd.Stderr = os.Stderr
252 errCh <- run(ctx, "docker attach", cmd)
253 }()
254
255 defer copyLogs()
256
257 for {
258 select {
259 case <-ctx.Done():
260 return ctx.Err()
261 case err := <-errCh:
262 if err != nil {
263 return appendInternalErr(fmt.Errorf("container process: %w", err))
264 }
265 return nil
266 }
267 }
268}
269
270func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
271 cmd := exec.CommandContext(ctx, cmdName, args...)
272 // Really only needed for the "go build" command for the linux sketch binary
273 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0")
274 start := time.Now()
275
276 out, err := cmd.CombinedOutput()
277 if err != nil {
278 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))))
279 } else {
280 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))))
281 }
282 return out, err
283}
284
285func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
286 start := time.Now()
287 err := cmd.Run()
288 if err != nil {
289 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))))
290 } else {
291 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))))
292 }
293 return err
294}
295
296type gitServer struct {
297 gitLn net.Listener
298 gitPort string
299 srv *http.Server
300}
301
302func (gs *gitServer) shutdown(ctx context.Context) {
303 gs.srv.Shutdown(ctx)
304 gs.gitLn.Close()
305}
306
307// Serve a git remote from the host for the container to fetch from and push to.
308func (gs *gitServer) serve(ctx context.Context) error {
309 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
310 return gs.srv.Serve(gs.gitLn)
311}
312
313func newGitServer(gitRoot string) (*gitServer, error) {
314 ret := &gitServer{}
315 gitLn, err := net.Listen("tcp4", ":0")
316 if err != nil {
317 return nil, fmt.Errorf("git listen: %w", err)
318 }
319 ret.gitLn = gitLn
320
321 srv := http.Server{
322 Handler: &gitHTTP{gitRepoRoot: gitRoot},
323 }
324 ret.srv = &srv
325
326 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
327 if err != nil {
328 return nil, fmt.Errorf("git port: %w", err)
329 }
330 ret.gitPort = gitPort
331 return ret, nil
332}
333
334func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
335 //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr
336 // sessionID, gitUsername, gitEmail, skabandAddr string
David Crawshaw69c67312025-04-17 13:42:00 -0700337 cmdArgs := []string{
338 "create",
Earl Lee2e463fb2025-04-17 11:22:22 -0700339 "-it",
340 "--name", cntrName,
341 "-p", hostPort + ":80", // forward container port 80 to a host port
342 "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey,
343 }
344 if config.AntURL != "" {
345 cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL)
346 }
347 if config.SketchPubKey != "" {
348 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
349 }
350 if relPath != "." {
351 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
352 }
353 cmdArgs = append(
354 cmdArgs,
355 imgName,
356 "/bin/sketch",
357 "-unsafe",
358 "-addr=:80",
359 "-session-id="+config.SessionID,
360 "-git-username="+config.GitUsername, "-git-email="+config.GitEmail,
361 )
362 if config.SkabandAddr != "" {
363 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
364 }
365 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
366 return fmt.Errorf("docker create: %s, %w", out, err)
367 }
368 return nil
369}
370
371func buildLinuxSketchBin(ctx context.Context, path string) (string, error) {
David Crawshaw69c67312025-04-17 13:42:00 -0700372 tmpGopath, err := os.MkdirTemp("", "sketch-linux-build")
373 if err != nil {
374 return "", err
375 }
David Crawshaw993a3fc2025-04-17 13:51:45 -0700376 defer os.RemoveAll(tmpGopath)
David Crawshaw69c67312025-04-17 13:42:00 -0700377
Earl Lee2e463fb2025-04-17 11:22:22 -0700378 start := time.Now()
David Crawshaw69c67312025-04-17 13:42:00 -0700379 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch@latest")
David Crawshawb9eaef52025-04-17 15:23:18 -0700380 cmd.Env = append(
381 os.Environ(),
382 "GOOS=linux",
383 "CGO_ENABLED=0",
384 "GOTOOLCHAIN=auto",
385 "GOPATH="+tmpGopath,
386 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700387
388 fmt.Printf("building linux agent binary...\n")
389 out, err := cmd.CombinedOutput()
390 if err != nil {
391 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))))
392 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
393 } else {
394 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))))
395 }
396
David Crawshaw69c67312025-04-17 13:42:00 -0700397 src := filepath.Join(tmpGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
398 dst := filepath.Join(path, "tmp-sketch-binary-linux")
399 if err := os.Rename(src, dst); err != nil {
400 return "", err
401 }
402
Earl Lee2e463fb2025-04-17 11:22:22 -0700403 fmt.Printf("built linux agent binary in %s\n", time.Since(start).Round(100*time.Millisecond))
404
David Crawshaw69c67312025-04-17 13:42:00 -0700405 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700406}
407
408func getContainerPort(ctx context.Context, cntrName string) (string, error) {
409 localAddr := ""
410 if out, err := combinedOutput(ctx, "docker", "port", cntrName, "80"); err != nil {
411 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
412 } else {
413 v4, _, found := strings.Cut(string(out), "\n")
414 if !found {
415 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
416 }
417 localAddr = v4
418 if strings.HasPrefix(localAddr, "0.0.0.0") {
419 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
420 }
421 }
422 return localAddr, nil
423}
424
425// Contact the container and configure it.
426func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort string) error {
427 localURL := "http://" + localAddr
428 initMsg, err := json.Marshal(map[string]string{
429 "commit": commit,
430 "git_remote_addr": "http://host.docker.internal:" + gitPort + "/.git",
431 "host_addr": localAddr,
432 })
433 if err != nil {
434 return fmt.Errorf("init msg: %w", err)
435 }
436
437 slog.DebugContext(ctx, "/init POST", slog.String("initMsg", string(initMsg)))
438
439 // Note: this /init POST is handled in loop/server/loophttp.go:
440 initMsgByteReader := bytes.NewReader(initMsg)
441 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
442 if err != nil {
443 return err
444 }
445
446 var res *http.Response
447 for i := 0; ; i++ {
448 time.Sleep(100 * time.Millisecond)
449 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
450 initMsgByteReader.Reset(initMsg)
451 res, err = http.DefaultClient.Do(req)
452 if err != nil {
453 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
454 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
455 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
456 continue
457 }
458 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
459 }
460 break
461 }
462 resBytes, _ := io.ReadAll(res.Body)
463 if res.StatusCode != http.StatusOK {
464 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
465 }
466 return nil
467}
468
469func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
470 h := sha256.Sum256([]byte(gitRoot))
471 imgName = "sketch-" + hex.EncodeToString(h[:6])
472
473 var curImgInitFilesHash string
474 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
475 if strings.Contains(string(out), "No such object") {
476 // Image does not exist, continue and build it.
477 curImgInitFilesHash = ""
478 } else {
479 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
480 }
481 } else {
482 m := map[string]string{}
483 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
484 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
485 }
486 curImgInitFilesHash = m["sketch_context"]
487 }
488
489 candidates, err := findRepoDockerfiles(cwd, gitRoot)
490 if err != nil {
491 return "", fmt.Errorf("find dockerfile: %w", err)
492 }
493
494 var initFiles map[string]string
495 var dockerfilePath string
496
497 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
498 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
499 dockerfilePath = candidates[0]
500 contents, err := os.ReadFile(dockerfilePath)
501 if err != nil {
502 return "", err
503 }
504 fmt.Printf("using %s as dev env\n", candidates[0])
505 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
506 fmt.Printf("using existing docker image %s\n", imgName)
507 return imgName, nil
508 }
509 } else {
510 initFiles, err = readInitFiles(os.DirFS(gitRoot))
511 if err != nil {
512 return "", err
513 }
514 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
515 if err != nil {
516 return "", err
517 }
518 initFileHash := hashInitFiles(initFiles)
519 if curImgInitFilesHash == initFileHash && !forceRebuild {
520 fmt.Printf("using existing docker image %s\n", imgName)
521 return imgName, nil
522 }
523
524 start := time.Now()
525 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
526 if err != nil {
527 return "", fmt.Errorf("create dockerfile: %w", err)
528 }
529 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
530 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
531 return "", err
532 }
533 defer os.Remove(dockerfilePath)
534
535 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))
536 }
537
538 var gitUserEmail, gitUserName string
539 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
540 return "", fmt.Errorf("git config: %s: %v", out, err)
541 } else {
542 gitUserEmail = strings.TrimSpace(string(out))
543 }
544 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
545 return "", fmt.Errorf("git config: %s: %v", out, err)
546 } else {
547 gitUserName = strings.TrimSpace(string(out))
548 }
549
550 start := time.Now()
551 cmd := exec.CommandContext(ctx,
552 "docker", "build",
553 "-t", imgName,
554 "-f", dockerfilePath,
555 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
556 "--build-arg", "GIT_USER_NAME="+gitUserName,
557 ".",
558 )
559 cmd.Dir = gitRoot
560 cmd.Stdout = stdout
561 cmd.Stderr = stderr
562 fmt.Printf("building docker image %s...\n", imgName)
563
564 err = run(ctx, "docker build", cmd)
565 if err != nil {
566 return "", fmt.Errorf("docker build failed: %v", err)
567 }
568 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
569 return imgName, nil
570}
571
572func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
573 files, err := findDirDockerfiles(cwd)
574 if err != nil {
575 return nil, err
576 }
577 if len(files) > 0 {
578 return files, nil
579 }
580
581 path := cwd
582 for path != gitRoot {
583 path = filepath.Dir(path)
584 files, err := findDirDockerfiles(path)
585 if err != nil {
586 return nil, err
587 }
588 if len(files) > 0 {
589 return files, nil
590 }
591 }
592 return files, nil
593}
594
595// findDirDockerfiles finds all "Dockerfile*" files in a directory.
596func findDirDockerfiles(root string) (res []string, err error) {
597 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
598 if err != nil {
599 return err
600 }
601 if info.IsDir() && root != path {
602 return filepath.SkipDir
603 }
604 name := strings.ToLower(info.Name())
605 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
606 res = append(res, path)
607 }
608 return nil
609 })
610 if err != nil {
611 return nil, err
612 }
613 return res, nil
614}
615
616func findGitRoot(ctx context.Context, path string) (string, error) {
617 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
618 cmd.Dir = path
619 out, err := cmd.CombinedOutput()
620 if err != nil {
621 if strings.Contains(string(out), "not a git repository") {
622 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
623Consider one of the following options:
624 - cd to a different dir that is already part of a git repo first, or
625 - to create a new git repo from this directory (%s), run this command:
626
627 git init . && git commit --allow-empty -m "initial commit"
628
629and try running sketch again.
630`, path, path)
631 }
632 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
633 }
634 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
635 absGitDir := filepath.Join(path, gitDir)
636 return filepath.Dir(absGitDir), err
637}
638
639func OpenBrowser(ctx context.Context, url string) {
640 var cmd *exec.Cmd
641 switch runtime.GOOS {
642 case "darwin":
643 cmd = exec.CommandContext(ctx, "open", url)
644 case "windows":
645 cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url)
646 default: // Linux and other Unix-like systems
647 cmd = exec.CommandContext(ctx, "xdg-open", url)
648 }
649 if b, err := cmd.CombinedOutput(); err != nil {
650 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
651 }
652}