blob: 0e612aaffe41d56dbef41d448882d00c0152508a [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 }
David Crawshaw993a3fc2025-04-17 13:51:45 -0700368 defer os.RemoveAll(tmpGopath)
David Crawshaw69c67312025-04-17 13:42:00 -0700369
Earl Lee2e463fb2025-04-17 11:22:22 -0700370 start := time.Now()
David Crawshaw69c67312025-04-17 13:42:00 -0700371 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch@latest")
372 cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0", "GOPATH="+tmpGopath)
Earl Lee2e463fb2025-04-17 11:22:22 -0700373
374 fmt.Printf("building linux agent binary...\n")
375 out, err := cmd.CombinedOutput()
376 if err != nil {
377 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))))
378 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
379 } else {
380 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))))
381 }
382
David Crawshaw69c67312025-04-17 13:42:00 -0700383 src := filepath.Join(tmpGopath, "bin", "linux_"+runtime.GOARCH, "sketch")
384 dst := filepath.Join(path, "tmp-sketch-binary-linux")
385 if err := os.Rename(src, dst); err != nil {
386 return "", err
387 }
388
Earl Lee2e463fb2025-04-17 11:22:22 -0700389 fmt.Printf("built linux agent binary in %s\n", time.Since(start).Round(100*time.Millisecond))
390
David Crawshaw69c67312025-04-17 13:42:00 -0700391 return dst, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700392}
393
394func getContainerPort(ctx context.Context, cntrName string) (string, error) {
395 localAddr := ""
396 if out, err := combinedOutput(ctx, "docker", "port", cntrName, "80"); err != nil {
397 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
398 } else {
399 v4, _, found := strings.Cut(string(out), "\n")
400 if !found {
401 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
402 }
403 localAddr = v4
404 if strings.HasPrefix(localAddr, "0.0.0.0") {
405 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
406 }
407 }
408 return localAddr, nil
409}
410
411// Contact the container and configure it.
412func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort string) error {
413 localURL := "http://" + localAddr
414 initMsg, err := json.Marshal(map[string]string{
415 "commit": commit,
416 "git_remote_addr": "http://host.docker.internal:" + gitPort + "/.git",
417 "host_addr": localAddr,
418 })
419 if err != nil {
420 return fmt.Errorf("init msg: %w", err)
421 }
422
423 slog.DebugContext(ctx, "/init POST", slog.String("initMsg", string(initMsg)))
424
425 // Note: this /init POST is handled in loop/server/loophttp.go:
426 initMsgByteReader := bytes.NewReader(initMsg)
427 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
428 if err != nil {
429 return err
430 }
431
432 var res *http.Response
433 for i := 0; ; i++ {
434 time.Sleep(100 * time.Millisecond)
435 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
436 initMsgByteReader.Reset(initMsg)
437 res, err = http.DefaultClient.Do(req)
438 if err != nil {
439 // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries.
440 if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) {
441 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
442 continue
443 }
444 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
445 }
446 break
447 }
448 resBytes, _ := io.ReadAll(res.Body)
449 if res.StatusCode != http.StatusOK {
450 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
451 }
452 return nil
453}
454
455func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) {
456 h := sha256.Sum256([]byte(gitRoot))
457 imgName = "sketch-" + hex.EncodeToString(h[:6])
458
459 var curImgInitFilesHash string
460 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
461 if strings.Contains(string(out), "No such object") {
462 // Image does not exist, continue and build it.
463 curImgInitFilesHash = ""
464 } else {
465 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
466 }
467 } else {
468 m := map[string]string{}
469 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
470 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
471 }
472 curImgInitFilesHash = m["sketch_context"]
473 }
474
475 candidates, err := findRepoDockerfiles(cwd, gitRoot)
476 if err != nil {
477 return "", fmt.Errorf("find dockerfile: %w", err)
478 }
479
480 var initFiles map[string]string
481 var dockerfilePath string
482
483 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
484 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
485 dockerfilePath = candidates[0]
486 contents, err := os.ReadFile(dockerfilePath)
487 if err != nil {
488 return "", err
489 }
490 fmt.Printf("using %s as dev env\n", candidates[0])
491 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
492 fmt.Printf("using existing docker image %s\n", imgName)
493 return imgName, nil
494 }
495 } else {
496 initFiles, err = readInitFiles(os.DirFS(gitRoot))
497 if err != nil {
498 return "", err
499 }
500 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
501 if err != nil {
502 return "", err
503 }
504 initFileHash := hashInitFiles(initFiles)
505 if curImgInitFilesHash == initFileHash && !forceRebuild {
506 fmt.Printf("using existing docker image %s\n", imgName)
507 return imgName, nil
508 }
509
510 start := time.Now()
511 dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir)
512 if err != nil {
513 return "", fmt.Errorf("create dockerfile: %w", err)
514 }
515 dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile")
516 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
517 return "", err
518 }
519 defer os.Remove(dockerfilePath)
520
521 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))
522 }
523
524 var gitUserEmail, gitUserName string
525 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
526 return "", fmt.Errorf("git config: %s: %v", out, err)
527 } else {
528 gitUserEmail = strings.TrimSpace(string(out))
529 }
530 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
531 return "", fmt.Errorf("git config: %s: %v", out, err)
532 } else {
533 gitUserName = strings.TrimSpace(string(out))
534 }
535
536 start := time.Now()
537 cmd := exec.CommandContext(ctx,
538 "docker", "build",
539 "-t", imgName,
540 "-f", dockerfilePath,
541 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
542 "--build-arg", "GIT_USER_NAME="+gitUserName,
543 ".",
544 )
545 cmd.Dir = gitRoot
546 cmd.Stdout = stdout
547 cmd.Stderr = stderr
548 fmt.Printf("building docker image %s...\n", imgName)
549
550 err = run(ctx, "docker build", cmd)
551 if err != nil {
552 return "", fmt.Errorf("docker build failed: %v", err)
553 }
554 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
555 return imgName, nil
556}
557
558func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
559 files, err := findDirDockerfiles(cwd)
560 if err != nil {
561 return nil, err
562 }
563 if len(files) > 0 {
564 return files, nil
565 }
566
567 path := cwd
568 for path != gitRoot {
569 path = filepath.Dir(path)
570 files, err := findDirDockerfiles(path)
571 if err != nil {
572 return nil, err
573 }
574 if len(files) > 0 {
575 return files, nil
576 }
577 }
578 return files, nil
579}
580
581// findDirDockerfiles finds all "Dockerfile*" files in a directory.
582func findDirDockerfiles(root string) (res []string, err error) {
583 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
584 if err != nil {
585 return err
586 }
587 if info.IsDir() && root != path {
588 return filepath.SkipDir
589 }
590 name := strings.ToLower(info.Name())
591 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
592 res = append(res, path)
593 }
594 return nil
595 })
596 if err != nil {
597 return nil, err
598 }
599 return res, nil
600}
601
602func findGitRoot(ctx context.Context, path string) (string, error) {
603 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
604 cmd.Dir = path
605 out, err := cmd.CombinedOutput()
606 if err != nil {
607 if strings.Contains(string(out), "not a git repository") {
608 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
609Consider one of the following options:
610 - cd to a different dir that is already part of a git repo first, or
611 - to create a new git repo from this directory (%s), run this command:
612
613 git init . && git commit --allow-empty -m "initial commit"
614
615and try running sketch again.
616`, path, path)
617 }
618 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
619 }
620 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
621 absGitDir := filepath.Join(path, gitDir)
622 return filepath.Dir(absGitDir), err
623}
624
625func OpenBrowser(ctx context.Context, url string) {
626 var cmd *exec.Cmd
627 switch runtime.GOOS {
628 case "darwin":
629 cmd = exec.CommandContext(ctx, "open", url)
630 case "windows":
631 cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url)
632 default: // Linux and other Unix-like systems
633 cmd = exec.CommandContext(ctx, "xdg-open", url)
634 }
635 if b, err := cmd.CombinedOutput(); err != nil {
636 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
637 }
638}