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