blob: a6d012eba2137bfcc1ad35ba61bed4046535daaa [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Sean McCullough7013e9e2025-05-14 02:03:58 +000024 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000025 "sketch.dev/browser"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070026 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070027 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070028 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070029 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070030)
31
32// ContainerConfig holds all configuration for launching a container
33type ContainerConfig struct {
34 // SessionID is the unique identifier for this session
35 SessionID string
36
37 // LocalAddr is the initial address to use (though it may be overwritten later)
38 LocalAddr string
39
40 // SkabandAddr is the address of the skaband service if available
41 SkabandAddr string
42
David Crawshaw5a7b3692025-05-05 16:49:15 -070043 // Model is the name of the LLM model to use.
44 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070045
David Crawshaw5a7b3692025-05-05 16:49:15 -070046 // ModelURL is the URL of the LLM service.
47 ModelURL string
48
49 // ModelAPIKey is the API key for LLM service.
50 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070051
52 // Path is the local filesystem path to use
53 Path string
54
55 // GitUsername is the username to use for git operations
56 GitUsername string
57
58 // GitEmail is the email to use for git operations
59 GitEmail string
60
61 // OpenBrowser determines whether to open a browser automatically
62 OpenBrowser bool
63
64 // NoCleanup prevents container cleanup when set to true
65 NoCleanup bool
66
67 // ForceRebuild forces rebuilding of the Docker image even if it exists
68 ForceRebuild bool
69
70 // Host directory to copy container logs into, if not set to ""
71 ContainerLogDest string
72
73 // Path to pre-built linux sketch binary, or build a new one if set to ""
74 SketchBinaryLinux string
75
76 // Sketch client public key.
77 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000078
Sean McCulloughbaa2b592025-04-23 10:40:08 -070079 // Host port for the container's ssh server
80 SSHPort int
81
Philip Zeyliger18532b22025-04-23 21:11:46 +000082 // Outside information to pass to the container
83 OutsideHostname string
84 OutsideOS string
85 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070086
Pokey Rule0dcebe12025-04-28 14:51:04 +010087 // If true, exit after the first turn
88 OneShot bool
89
90 // Initial prompt
91 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000092
93 // Initial commit to use as starting point
94 InitialCommit string
David Crawshawb5f6a002025-05-05 08:27:16 -070095
96 // Verbose enables verbose output
97 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000098
99 // DockerArgs are additional arguments to pass to the docker create command
100 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000101
102 // ExperimentFlag contains the experimental features to enable
103 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700104
105 // TermUI enables terminal UI
106 TermUI bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700107}
108
109// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
110// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700111func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700112 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700113 if runtime.GOOS == "darwin" {
114 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
115 } else {
116 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
117 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700118 }
119
120 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
121 // `docker ps` provides a good error message here that can be
122 // easily chatgpt'ed by users, so send it to the user as-is:
123 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
124 return fmt.Errorf("docker ps: %s (%w)", out, err)
125 }
126
127 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
128 if err != nil {
129 return err
130 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700131 gitRoot, err := findGitRoot(ctx, config.Path)
132 if err != nil {
133 return err
134 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700135 err = checkForEmptyGitRepo(ctx, config.Path)
136 if err != nil {
137 return err
138 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700139
David Crawshaw5a7b3692025-05-05 16:49:15 -0700140 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 if err != nil {
142 return err
143 }
144
145 linuxSketchBin := config.SketchBinaryLinux
146 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700147 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700148 if err != nil {
149 return err
150 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700151 }
152
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000153 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700154 defer func() {
155 if config.NoCleanup {
156 return
157 }
158 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
159 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
160 _ = out
161 }
162 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
163 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
164 _ = out
165 }
166 }()
167
168 // errCh receives errors from operations that this function calls in separate goroutines.
169 errCh := make(chan error)
170
171 // Start the git server
172 gitSrv, err := newGitServer(gitRoot)
173 if err != nil {
174 return fmt.Errorf("failed to start git server: %w", err)
175 }
176 defer gitSrv.shutdown(ctx)
177
178 go func() {
179 errCh <- gitSrv.serve(ctx)
180 }()
181
182 // Get the current host git commit
183 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000184 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
185 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700186 } else {
187 commit = strings.TrimSpace(string(out))
188 }
189 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
190 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
191 }
192
193 relPath, err := filepath.Rel(gitRoot, config.Path)
194 if err != nil {
195 return err
196 }
197
198 // Create the sketch container
199 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000200 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700201 }
202
203 // Copy the sketch linux binary into the container
204 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
205 return fmt.Errorf("docker cp: %s, %w", out, err)
206 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700207
208 // Make sure that the webui is built so we can copy the results to the container.
209 _, err = webui.Build()
210 if err != nil {
211 return fmt.Errorf("failed to build webui: %w", err)
212 }
213
David Crawshaw8bff16a2025-04-18 01:16:49 -0700214 webuiZipPath, err := webui.ZipPath()
215 if err != nil {
216 return err
217 }
218 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
219 return fmt.Errorf("docker cp: %s, %w", out, err)
220 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700221
David Crawshaw53786ef2025-04-24 12:52:51 -0700222 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700223
224 // Start the sketch container
225 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
226 return fmt.Errorf("docker start: %s, %w", out, err)
227 }
228
229 // Copies structured logs from the container to the host.
230 copyLogs := func() {
231 if config.ContainerLogDest == "" {
232 return
233 }
234 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
235 if err != nil {
236 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
237 return
238 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700239 prefix := []byte("structured logs:")
240 for line := range bytes.Lines(out) {
241 rest, ok := bytes.CutPrefix(line, prefix)
242 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700243 continue
244 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700245 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700246 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
247 logFileName := filepath.Base(logFile)
248 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
249 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
250 if err != nil {
251 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
252 }
253 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
254 }
255 }
256
257 // NOTE: we want to see what the internal sketch binary prints
258 // regardless of the setting of the verbosity flag on the external
259 // binary, so reading "docker logs", which is the stdout/stderr of
260 // the internal binary is not conditional on the verbose flag.
261 appendInternalErr := func(err error) error {
262 if err == nil {
263 return nil
264 }
265 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000266 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700267 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
268 }
269 out = bytes.TrimSpace(out)
270 if len(out) > 0 {
271 return fmt.Errorf("docker logs: %s;\n%w", out, err)
272 }
273 return err
274 }
275
276 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700277 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700278 if err != nil {
279 return appendInternalErr(err)
280 }
281
Philip Zeyliger00442412025-05-14 11:03:23 -0700282 if config.Verbose {
283 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
284 }
285
Sean McCulloughae3480f2025-04-23 15:28:20 -0700286 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
287 if err != nil {
288 return appendInternalErr(err)
289 }
290 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
291 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700292 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700293 }
Sean McCullough4854c652025-04-24 18:37:02 -0700294
Sean McCullough7013e9e2025-05-14 02:03:58 +0000295 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700296
Sean McCullough078e85a2025-05-08 17:28:34 -0700297 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
298 if err != nil {
299 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
300 }
301
302 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700303 sshAvailable := false
304 sshErrMsg := ""
305 if sshErr != nil {
306 fmt.Println(sshErr.Error())
307 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700308 // continue - ssh config is not required for the rest of sketch to function locally.
309 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700310 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700311 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
312 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700313 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700314🖥️ ssh %s
315🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700316🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700317`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700318 sshUserIdentity = cst.userIdentity
319 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000320
321 // Get the Container CA public key for mutual auth
322 if cst.containerCAPublicKey != nil {
323 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
324 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
325 }
326
327 // Get the host certificate for mutual auth
328 hostCertificate = cst.hostCertificate
329
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700330 defer func() {
331 if err := cst.Cleanup(); err != nil {
332 appendInternalErr(err)
333 }
334 }()
335 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700336
Earl Lee2e463fb2025-04-17 11:22:22 -0700337 // Tell the sketch container which git server port and commit to initialize with.
338 go func() {
339 // TODO: Why is this called in a goroutine? I have found that when I pull this out
340 // of the goroutine and call it inline, then the terminal UI clears itself and all
341 // the scrollback (which is not good, but also not fatal). I can't see why it does this
342 // though, since none of the calls in postContainerInitConfig obviously write to stdout
343 // or stderr.
Sean McCullough7013e9e2025-05-14 02:03:58 +0000344 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700345 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
346 errCh <- appendInternalErr(err)
347 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700348
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700349 // We open the browser after the init config because the above waits for the web server to be serving.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700350 ps1URL := "http://" + localAddr
351 if config.SkabandAddr != "" {
352 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700353 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700354 if config.OpenBrowser {
355 browser.Open(ps1URL)
356 }
357 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700358 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700359
360 go func() {
361 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
362 cmd.Stdin = os.Stdin
363 cmd.Stdout = os.Stdout
364 cmd.Stderr = os.Stderr
365 errCh <- run(ctx, "docker attach", cmd)
366 }()
367
368 defer copyLogs()
369
370 for {
371 select {
372 case <-ctx.Done():
373 return ctx.Err()
374 case err := <-errCh:
375 if err != nil {
376 return appendInternalErr(fmt.Errorf("container process: %w", err))
377 }
378 return nil
379 }
380 }
381}
382
383func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
384 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 start := time.Now()
386
387 out, err := cmd.CombinedOutput()
388 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700389 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700390 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700391 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700392 }
393 return out, err
394}
395
396func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
397 start := time.Now()
398 err := cmd.Run()
399 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700400 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700401 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700402 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700403 }
404 return err
405}
406
407type gitServer struct {
408 gitLn net.Listener
409 gitPort string
410 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700411 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700412 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700413}
414
415func (gs *gitServer) shutdown(ctx context.Context) {
416 gs.srv.Shutdown(ctx)
417 gs.gitLn.Close()
418}
419
420// Serve a git remote from the host for the container to fetch from and push to.
421func (gs *gitServer) serve(ctx context.Context) error {
422 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
423 return gs.srv.Serve(gs.gitLn)
424}
425
426func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700427 ret := &gitServer{
428 pass: rand.Text(),
429 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700430
Earl Lee2e463fb2025-04-17 11:22:22 -0700431 gitLn, err := net.Listen("tcp4", ":0")
432 if err != nil {
433 return nil, fmt.Errorf("git listen: %w", err)
434 }
435 ret.gitLn = gitLn
436
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700437 browserC := make(chan bool, 1) // channel of browser open requests
438
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000439 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700440 for range browserC {
441 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000442 }
443 }()
444
445 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700446 ret.srv = &srv
447
448 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
449 if err != nil {
450 return nil, fmt.Errorf("git port: %w", err)
451 }
452 ret.gitPort = gitPort
453 return ret, nil
454}
455
456func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700457 cmdArgs := []string{
458 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700459 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700460 "--name", cntrName,
461 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700462 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700463 }
David Crawshaw66cf74e2025-05-05 08:48:39 -0700464 if !config.OneShot {
465 cmdArgs = append(cmdArgs, "-t")
466 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000467
468 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
469 cmdArgs = append(cmdArgs, "-e", envVar)
470 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700471 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700472 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700473 }
474 if config.SketchPubKey != "" {
475 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
476 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700477 if config.SSHPort > 0 {
478 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
479 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700480 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700481 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700482 if relPath != "." {
483 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
484 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700485 // colima does this by default, but Linux docker seems to need this set explicitly
486 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700487 cmdArgs = append(
488 cmdArgs,
489 imgName,
490 "/bin/sketch",
491 "-unsafe",
492 "-addr=:80",
493 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000494 "-git-username="+config.GitUsername,
495 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000496 "-outside-hostname="+config.OutsideHostname,
497 "-outside-os="+config.OutsideOS,
498 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700499 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700500 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700501 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000502 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700503 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700504 if config.Model != "" {
505 cmdArgs = append(cmdArgs, "-model="+config.Model)
506 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000507 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100508 if config.Prompt != "" {
509 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
510 }
511 if config.OneShot {
512 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700513 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000514 if config.ModelURL == "" {
515 // Forward ANTHROPIC_API_KEY for direct use.
516 // TODO: have outtie run an http proxy?
517 // TODO: select and forward the relevant API key based on the model
518 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
519 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000520
521 // Add additional docker arguments if provided
522 if config.DockerArgs != "" {
523 // Parse space-separated docker arguments with support for quotes and escaping
524 args := parseDockerArgs(config.DockerArgs)
525 // Insert arguments after "create" but before other arguments
526 for i := len(args) - 1; i >= 0; i-- {
527 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
528 }
529 }
530
Earl Lee2e463fb2025-04-17 11:22:22 -0700531 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
532 return fmt.Errorf("docker create: %s, %w", out, err)
533 }
534 return nil
535}
536
David Crawshawb5f6a002025-05-05 08:27:16 -0700537func buildLinuxSketchBin(ctx context.Context) (string, error) {
Pokey Rulea9a786b2025-05-12 10:52:34 +0100538 // Change to directory containing dockerimg.go for module detection
539 _, codeFile, _, _ := runtime.Caller(0)
540 codeDir := filepath.Dir(codeFile)
541 if currentDir, err := os.Getwd(); err != nil {
542 slog.WarnContext(ctx, "could not get current directory", "err", err)
543 } else {
544 if err := os.Chdir(codeDir); err != nil {
545 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
546 } else {
547 defer func() {
548 _ = os.Chdir(currentDir)
549 }()
550 }
551 }
552
David Crawshaw8a617cb2025-04-18 01:28:43 -0700553 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700554 if err != nil {
555 return "", err
556 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700557 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
558 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
559 return "", err
560 }
561
562 verToInstall := "@latest"
563 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
564 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
565 } else {
566 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700567 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700568 verToInstall = ""
569 }
570 }
David Crawshaw69c67312025-04-17 13:42:00 -0700571
Earl Lee2e463fb2025-04-17 11:22:22 -0700572 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700573 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700574 cmd.Env = append(
575 os.Environ(),
576 "GOOS=linux",
577 "CGO_ENABLED=0",
578 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700579 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700580 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700581 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700582
Earl Lee2e463fb2025-04-17 11:22:22 -0700583 out, err := cmd.CombinedOutput()
584 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700585 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700586 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
587 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700588 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700589 }
590
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700591 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700592 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700593 }
David Crawshawc7e77962025-05-03 13:20:18 -0700594 // If we are already on Linux, there's no extra platform name in the path
595 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700596}
597
Sean McCulloughae3480f2025-04-23 15:28:20 -0700598func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700599 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700600 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700601 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
602 } else {
603 v4, _, found := strings.Cut(string(out), "\n")
604 if !found {
605 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
606 }
607 localAddr = v4
608 if strings.HasPrefix(localAddr, "0.0.0.0") {
609 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
610 }
611 }
612 return localAddr, nil
613}
614
615// Contact the container and configure it.
Sean McCullough7013e9e2025-05-14 02:03:58 +0000616func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700617 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700618
619 initMsg, err := json.Marshal(
620 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000621 Commit: commit,
622 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
623 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
624 HostAddr: localAddr,
625 SSHAuthorizedKeys: sshAuthorizedKeys,
626 SSHServerIdentity: sshServerIdentity,
627 SSHContainerCAKey: sshContainerCAKey,
628 SSHHostCertificate: sshHostCertificate,
629 SSHAvailable: sshAvailable,
630 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700631 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700632 if err != nil {
633 return fmt.Errorf("init msg: %w", err)
634 }
635
Earl Lee2e463fb2025-04-17 11:22:22 -0700636 // Note: this /init POST is handled in loop/server/loophttp.go:
637 initMsgByteReader := bytes.NewReader(initMsg)
638 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
639 if err != nil {
640 return err
641 }
642
643 var res *http.Response
644 for i := 0; ; i++ {
645 time.Sleep(100 * time.Millisecond)
646 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
647 initMsgByteReader.Reset(initMsg)
648 res, err = http.DefaultClient.Do(req)
649 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700650 if i < 100 {
651 if i%10 == 0 {
652 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
653 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700654 continue
655 }
656 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
657 }
658 break
659 }
660 resBytes, _ := io.ReadAll(res.Body)
661 if res.StatusCode != http.StatusOK {
662 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
663 }
664 return nil
665}
666
David Crawshaw5a7b3692025-05-05 16:49:15 -0700667func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700668 h := sha256.Sum256([]byte(gitRoot))
669 imgName = "sketch-" + hex.EncodeToString(h[:6])
670
671 var curImgInitFilesHash string
672 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
673 if strings.Contains(string(out), "No such object") {
674 // Image does not exist, continue and build it.
675 curImgInitFilesHash = ""
676 } else {
677 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
678 }
679 } else {
680 m := map[string]string{}
681 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
682 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
683 }
684 curImgInitFilesHash = m["sketch_context"]
685 }
686
687 candidates, err := findRepoDockerfiles(cwd, gitRoot)
688 if err != nil {
689 return "", fmt.Errorf("find dockerfile: %w", err)
690 }
691
692 var initFiles map[string]string
693 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700694 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700695
696 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
697 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
698 dockerfilePath = candidates[0]
699 contents, err := os.ReadFile(dockerfilePath)
700 if err != nil {
701 return "", err
702 }
703 fmt.Printf("using %s as dev env\n", candidates[0])
704 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700705 return imgName, nil
706 }
707 } else {
708 initFiles, err = readInitFiles(os.DirFS(gitRoot))
709 if err != nil {
710 return "", err
711 }
712 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
713 if err != nil {
714 return "", err
715 }
716 initFileHash := hashInitFiles(initFiles)
717 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700718 return imgName, nil
719 }
720
David Crawshaw5a7b3692025-05-05 16:49:15 -0700721 if model == "gemini" {
722 if strings.HasSuffix(modelURL, "/gemmsgs") {
723 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700724 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700725 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
726 } else {
727 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
728 }
729 }
730
Earl Lee2e463fb2025-04-17 11:22:22 -0700731 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700732 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700733 URL: modelURL,
734 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700735 HTTPC: http.DefaultClient,
736 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000737 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700738 if err != nil {
739 return "", fmt.Errorf("create dockerfile: %w", err)
740 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000741 // Create a unique temporary directory for the Dockerfile
742 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
743 if err != nil {
744 return "", fmt.Errorf("failed to create temporary directory: %w", err)
745 }
746 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700747 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700748 return "", err
749 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000750 // Remove the temporary directory and all contents when done
751 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700752
David Crawshawb5f6a002025-05-05 08:27:16 -0700753 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700754 fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
David Crawshawb5f6a002025-05-05 08:27:16 -0700755 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700756 }
757
758 var gitUserEmail, gitUserName string
759 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
760 return "", fmt.Errorf("git config: %s: %v", out, err)
761 } else {
762 gitUserEmail = strings.TrimSpace(string(out))
763 }
764 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
765 return "", fmt.Errorf("git config: %s: %v", out, err)
766 } else {
767 gitUserName = strings.TrimSpace(string(out))
768 }
769
770 start := time.Now()
771 cmd := exec.CommandContext(ctx,
772 "docker", "build",
773 "-t", imgName,
774 "-f", dockerfilePath,
775 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
776 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700777 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700778 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700779 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700780 // We print the docker build output whether or not the user
781 // has selected --verbose. Building an image takes a while
782 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700783 cmd.Stdout = os.Stdout
784 cmd.Stderr = os.Stderr
785 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700786
787 err = run(ctx, "docker build", cmd)
788 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700789 var msg string
790 if generatedDockerfile != "" {
791 if !verbose {
792 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
793 }
794 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
795 }
796 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700797 }
798 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
799 return imgName, nil
800}
801
802func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
803 files, err := findDirDockerfiles(cwd)
804 if err != nil {
805 return nil, err
806 }
807 if len(files) > 0 {
808 return files, nil
809 }
810
811 path := cwd
812 for path != gitRoot {
813 path = filepath.Dir(path)
814 files, err := findDirDockerfiles(path)
815 if err != nil {
816 return nil, err
817 }
818 if len(files) > 0 {
819 return files, nil
820 }
821 }
822 return files, nil
823}
824
825// findDirDockerfiles finds all "Dockerfile*" files in a directory.
826func findDirDockerfiles(root string) (res []string, err error) {
827 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
828 if err != nil {
829 return err
830 }
831 if info.IsDir() && root != path {
832 return filepath.SkipDir
833 }
834 name := strings.ToLower(info.Name())
835 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
836 res = append(res, path)
837 }
838 return nil
839 })
840 if err != nil {
841 return nil, err
842 }
843 return res, nil
844}
845
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700846func checkForEmptyGitRepo(ctx context.Context, path string) error {
847 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
848 cmd.Dir = path
849 _, err := cmd.CombinedOutput()
850 if err != nil {
851 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
852 "git commit --allow-empty -m 'initial commit'")
853 }
854 return nil
855}
856
Earl Lee2e463fb2025-04-17 11:22:22 -0700857func findGitRoot(ctx context.Context, path string) (string, error) {
858 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
859 cmd.Dir = path
860 out, err := cmd.CombinedOutput()
861 if err != nil {
862 if strings.Contains(string(out), "not a git repository") {
863 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
864Consider one of the following options:
865 - cd to a different dir that is already part of a git repo first, or
866 - to create a new git repo from this directory (%s), run this command:
867
868 git init . && git commit --allow-empty -m "initial commit"
869
870and try running sketch again.
871`, path, path)
872 }
873 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
874 }
875 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
876 absGitDir := filepath.Join(path, gitDir)
877 return filepath.Dir(absGitDir), err
878}
879
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000880// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
881// from git config using the sketch.envfwd multi-valued key.
882func getEnvForwardingFromGitConfig(ctx context.Context) []string {
883 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
884 out := string(outb)
885 if err != nil {
886 if strings.Contains(out, "key does not exist") {
887 return nil
888 }
889 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
890 return nil
891 }
892
893 var envVars []string
894 for envVar := range strings.Lines(out) {
895 envVar = strings.TrimSpace(envVar)
896 if envVar == "" {
897 continue
898 }
899 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
900 }
901 return envVars
902}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000903
904// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
905// It handles quoted arguments and escaped characters.
906//
907// Examples:
908//
909// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
910// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
911// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
912func parseDockerArgs(args string) []string {
913 if args = strings.TrimSpace(args); args == "" {
914 return []string{}
915 }
916
917 var result []string
918 var current strings.Builder
919 inQuotes := false
920 escapeNext := false
921 quoteChar := rune(0)
922
923 for _, char := range args {
924 if escapeNext {
925 current.WriteRune(char)
926 escapeNext = false
927 continue
928 }
929
930 if char == '\\' {
931 escapeNext = true
932 continue
933 }
934
935 if char == '"' || char == '\'' {
936 if !inQuotes {
937 inQuotes = true
938 quoteChar = char
939 continue
940 } else if char == quoteChar {
941 inQuotes = false
942 quoteChar = rune(0)
943 continue
944 }
945 // Non-matching quote character inside quotes
946 current.WriteRune(char)
947 continue
948 }
949
950 // Space outside of quotes is an argument separator
951 if char == ' ' && !inQuotes {
952 if current.Len() > 0 {
953 result = append(result, current.String())
954 current.Reset()
955 }
956 continue
957 }
958
959 current.WriteRune(char)
960 }
961
962 // Add the last argument if there is one
963 if current.Len() > 0 {
964 result = append(result, current.String())
965 }
966
967 return result
968}