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