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