blob: 4b50ae1dd49409c97e7663c7380ca0f1e20f298f [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
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000102 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
103 Mounts []string
104
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000105 // ExperimentFlag contains the experimental features to enable
106 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700107
108 // TermUI enables terminal UI
109 TermUI bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700110}
111
112// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
113// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700114func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700115 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700116 if runtime.GOOS == "darwin" {
117 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
118 } else {
119 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
120 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700121 }
122
123 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
124 // `docker ps` provides a good error message here that can be
125 // easily chatgpt'ed by users, so send it to the user as-is:
126 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
127 return fmt.Errorf("docker ps: %s (%w)", out, err)
128 }
129
130 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
131 if err != nil {
132 return err
133 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700134 gitRoot, err := findGitRoot(ctx, config.Path)
135 if err != nil {
136 return err
137 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700138 err = checkForEmptyGitRepo(ctx, config.Path)
139 if err != nil {
140 return err
141 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700142
David Crawshaw5a7b3692025-05-05 16:49:15 -0700143 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700144 if err != nil {
145 return err
146 }
147
148 linuxSketchBin := config.SketchBinaryLinux
149 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700150 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700151 if err != nil {
152 return err
153 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700154 }
155
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000156 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700157 defer func() {
158 if config.NoCleanup {
159 return
160 }
161 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
162 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
163 _ = out
164 }
165 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
166 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
167 _ = out
168 }
169 }()
170
171 // errCh receives errors from operations that this function calls in separate goroutines.
172 errCh := make(chan error)
173
174 // Start the git server
175 gitSrv, err := newGitServer(gitRoot)
176 if err != nil {
177 return fmt.Errorf("failed to start git server: %w", err)
178 }
179 defer gitSrv.shutdown(ctx)
180
181 go func() {
182 errCh <- gitSrv.serve(ctx)
183 }()
184
185 // Get the current host git commit
186 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000187 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
188 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700189 } else {
190 commit = strings.TrimSpace(string(out))
191 }
192 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
193 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
194 }
195
196 relPath, err := filepath.Rel(gitRoot, config.Path)
197 if err != nil {
198 return err
199 }
200
201 // Create the sketch container
202 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000203 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 }
205
206 // Copy the sketch linux binary into the container
207 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
208 return fmt.Errorf("docker cp: %s, %w", out, err)
209 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700210
211 // Make sure that the webui is built so we can copy the results to the container.
212 _, err = webui.Build()
213 if err != nil {
214 return fmt.Errorf("failed to build webui: %w", err)
215 }
216
David Crawshaw8bff16a2025-04-18 01:16:49 -0700217 webuiZipPath, err := webui.ZipPath()
218 if err != nil {
219 return err
220 }
221 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
222 return fmt.Errorf("docker cp: %s, %w", out, err)
223 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700224
David Crawshaw53786ef2025-04-24 12:52:51 -0700225 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700226
227 // Start the sketch container
228 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
229 return fmt.Errorf("docker start: %s, %w", out, err)
230 }
231
232 // Copies structured logs from the container to the host.
233 copyLogs := func() {
234 if config.ContainerLogDest == "" {
235 return
236 }
237 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
238 if err != nil {
239 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
240 return
241 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700242 prefix := []byte("structured logs:")
243 for line := range bytes.Lines(out) {
244 rest, ok := bytes.CutPrefix(line, prefix)
245 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700246 continue
247 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700248 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700249 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
250 logFileName := filepath.Base(logFile)
251 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
252 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
253 if err != nil {
254 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
255 }
256 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
257 }
258 }
259
260 // NOTE: we want to see what the internal sketch binary prints
261 // regardless of the setting of the verbosity flag on the external
262 // binary, so reading "docker logs", which is the stdout/stderr of
263 // the internal binary is not conditional on the verbose flag.
264 appendInternalErr := func(err error) error {
265 if err == nil {
266 return nil
267 }
268 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000269 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
271 }
272 out = bytes.TrimSpace(out)
273 if len(out) > 0 {
274 return fmt.Errorf("docker logs: %s;\n%w", out, err)
275 }
276 return err
277 }
278
279 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700280 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700281 if err != nil {
282 return appendInternalErr(err)
283 }
284
Philip Zeyliger00442412025-05-14 11:03:23 -0700285 if config.Verbose {
286 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
287 }
288
Sean McCulloughae3480f2025-04-23 15:28:20 -0700289 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
290 if err != nil {
291 return appendInternalErr(err)
292 }
293 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
294 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700295 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700296 }
Sean McCullough4854c652025-04-24 18:37:02 -0700297
Sean McCullough7013e9e2025-05-14 02:03:58 +0000298 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700299
Sean McCullough078e85a2025-05-08 17:28:34 -0700300 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
301 if err != nil {
302 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
303 }
304
305 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700306 sshAvailable := false
307 sshErrMsg := ""
308 if sshErr != nil {
309 fmt.Println(sshErr.Error())
310 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700311 // continue - ssh config is not required for the rest of sketch to function locally.
312 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700313 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700314 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
315 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700316 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700317🖥️ ssh %s
318🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700319🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700320`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700321 sshUserIdentity = cst.userIdentity
322 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000323
324 // Get the Container CA public key for mutual auth
325 if cst.containerCAPublicKey != nil {
326 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
327 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
328 }
329
330 // Get the host certificate for mutual auth
331 hostCertificate = cst.hostCertificate
332
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700333 defer func() {
334 if err := cst.Cleanup(); err != nil {
335 appendInternalErr(err)
336 }
337 }()
338 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700339
Earl Lee2e463fb2025-04-17 11:22:22 -0700340 // Tell the sketch container which git server port and commit to initialize with.
341 go func() {
342 // TODO: Why is this called in a goroutine? I have found that when I pull this out
343 // of the goroutine and call it inline, then the terminal UI clears itself and all
344 // the scrollback (which is not good, but also not fatal). I can't see why it does this
345 // though, since none of the calls in postContainerInitConfig obviously write to stdout
346 // or stderr.
Sean McCullough7013e9e2025-05-14 02:03:58 +0000347 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 -0700348 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
349 errCh <- appendInternalErr(err)
350 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700351
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700352 // 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 -0700353 ps1URL := "http://" + localAddr
354 if config.SkabandAddr != "" {
355 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700356 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700357 if config.OpenBrowser {
358 browser.Open(ps1URL)
359 }
360 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700361 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700362
363 go func() {
364 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
365 cmd.Stdin = os.Stdin
366 cmd.Stdout = os.Stdout
367 cmd.Stderr = os.Stderr
368 errCh <- run(ctx, "docker attach", cmd)
369 }()
370
371 defer copyLogs()
372
373 for {
374 select {
375 case <-ctx.Done():
376 return ctx.Err()
377 case err := <-errCh:
378 if err != nil {
379 return appendInternalErr(fmt.Errorf("container process: %w", err))
380 }
381 return nil
382 }
383 }
384}
385
386func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
387 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700388 start := time.Now()
389
390 out, err := cmd.CombinedOutput()
391 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700392 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 -0700393 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700394 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 -0700395 }
396 return out, err
397}
398
399func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
400 start := time.Now()
401 err := cmd.Run()
402 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700403 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 -0700404 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700405 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 -0700406 }
407 return err
408}
409
410type gitServer struct {
411 gitLn net.Listener
412 gitPort string
413 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700414 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700415 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700416}
417
418func (gs *gitServer) shutdown(ctx context.Context) {
419 gs.srv.Shutdown(ctx)
420 gs.gitLn.Close()
421}
422
423// Serve a git remote from the host for the container to fetch from and push to.
424func (gs *gitServer) serve(ctx context.Context) error {
425 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
426 return gs.srv.Serve(gs.gitLn)
427}
428
429func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700430 ret := &gitServer{
431 pass: rand.Text(),
432 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700433
Earl Lee2e463fb2025-04-17 11:22:22 -0700434 gitLn, err := net.Listen("tcp4", ":0")
435 if err != nil {
436 return nil, fmt.Errorf("git listen: %w", err)
437 }
438 ret.gitLn = gitLn
439
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700440 browserC := make(chan bool, 1) // channel of browser open requests
441
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000442 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700443 for range browserC {
444 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000445 }
446 }()
447
448 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700449 ret.srv = &srv
450
451 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
452 if err != nil {
453 return nil, fmt.Errorf("git port: %w", err)
454 }
455 ret.gitPort = gitPort
456 return ret, nil
457}
458
459func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700460 cmdArgs := []string{
461 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700462 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700463 "--name", cntrName,
464 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700465 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700466 }
David Crawshaw66cf74e2025-05-05 08:48:39 -0700467 if !config.OneShot {
468 cmdArgs = append(cmdArgs, "-t")
469 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000470
471 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
472 cmdArgs = append(cmdArgs, "-e", envVar)
473 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700474 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700475 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700476 }
477 if config.SketchPubKey != "" {
478 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
479 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700480 if config.SSHPort > 0 {
481 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
482 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700483 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700484 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700485 if relPath != "." {
486 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
487 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700488 // colima does this by default, but Linux docker seems to need this set explicitly
489 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000490
491 // Add volume mounts if specified
492 for _, mount := range config.Mounts {
493 if mount != "" {
494 cmdArgs = append(cmdArgs, "-v", mount)
495 }
496 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700497 cmdArgs = append(
498 cmdArgs,
499 imgName,
500 "/bin/sketch",
501 "-unsafe",
502 "-addr=:80",
503 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000504 "-git-username="+config.GitUsername,
505 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000506 "-outside-hostname="+config.OutsideHostname,
507 "-outside-os="+config.OutsideOS,
508 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700509 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700510 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700511 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000512 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700513 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700514 if config.Model != "" {
515 cmdArgs = append(cmdArgs, "-model="+config.Model)
516 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000517 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100518 if config.Prompt != "" {
519 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
520 }
521 if config.OneShot {
522 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700523 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000524 if config.ModelURL == "" {
525 // Forward ANTHROPIC_API_KEY for direct use.
526 // TODO: have outtie run an http proxy?
527 // TODO: select and forward the relevant API key based on the model
528 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
529 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000530
531 // Add additional docker arguments if provided
532 if config.DockerArgs != "" {
533 // Parse space-separated docker arguments with support for quotes and escaping
534 args := parseDockerArgs(config.DockerArgs)
535 // Insert arguments after "create" but before other arguments
536 for i := len(args) - 1; i >= 0; i-- {
537 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
538 }
539 }
540
Earl Lee2e463fb2025-04-17 11:22:22 -0700541 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
542 return fmt.Errorf("docker create: %s, %w", out, err)
543 }
544 return nil
545}
546
David Crawshawb5f6a002025-05-05 08:27:16 -0700547func buildLinuxSketchBin(ctx context.Context) (string, error) {
Pokey Rulea9a786b2025-05-12 10:52:34 +0100548 // Change to directory containing dockerimg.go for module detection
549 _, codeFile, _, _ := runtime.Caller(0)
550 codeDir := filepath.Dir(codeFile)
551 if currentDir, err := os.Getwd(); err != nil {
552 slog.WarnContext(ctx, "could not get current directory", "err", err)
553 } else {
554 if err := os.Chdir(codeDir); err != nil {
555 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
556 } else {
557 defer func() {
558 _ = os.Chdir(currentDir)
559 }()
560 }
561 }
562
David Crawshaw8a617cb2025-04-18 01:28:43 -0700563 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700564 if err != nil {
565 return "", err
566 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700567 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
568 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
569 return "", err
570 }
571
572 verToInstall := "@latest"
573 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
574 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
575 } else {
576 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700577 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700578 verToInstall = ""
579 }
580 }
David Crawshaw69c67312025-04-17 13:42:00 -0700581
Earl Lee2e463fb2025-04-17 11:22:22 -0700582 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700583 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700584 cmd.Env = append(
585 os.Environ(),
586 "GOOS=linux",
587 "CGO_ENABLED=0",
588 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700589 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700590 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700591 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700592
Earl Lee2e463fb2025-04-17 11:22:22 -0700593 out, err := cmd.CombinedOutput()
594 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700595 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 -0700596 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
597 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700598 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 -0700599 }
600
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700601 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700602 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700603 }
David Crawshawc7e77962025-05-03 13:20:18 -0700604 // If we are already on Linux, there's no extra platform name in the path
605 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700606}
607
Sean McCulloughae3480f2025-04-23 15:28:20 -0700608func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700609 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700610 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700611 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
612 } else {
613 v4, _, found := strings.Cut(string(out), "\n")
614 if !found {
615 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
616 }
617 localAddr = v4
618 if strings.HasPrefix(localAddr, "0.0.0.0") {
619 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
620 }
621 }
622 return localAddr, nil
623}
624
625// Contact the container and configure it.
Sean McCullough7013e9e2025-05-14 02:03:58 +0000626func 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 -0700627 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700628
629 initMsg, err := json.Marshal(
630 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000631 Commit: commit,
632 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
633 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
634 HostAddr: localAddr,
635 SSHAuthorizedKeys: sshAuthorizedKeys,
636 SSHServerIdentity: sshServerIdentity,
637 SSHContainerCAKey: sshContainerCAKey,
638 SSHHostCertificate: sshHostCertificate,
639 SSHAvailable: sshAvailable,
640 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700641 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700642 if err != nil {
643 return fmt.Errorf("init msg: %w", err)
644 }
645
Earl Lee2e463fb2025-04-17 11:22:22 -0700646 // Note: this /init POST is handled in loop/server/loophttp.go:
647 initMsgByteReader := bytes.NewReader(initMsg)
648 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
649 if err != nil {
650 return err
651 }
652
653 var res *http.Response
654 for i := 0; ; i++ {
655 time.Sleep(100 * time.Millisecond)
656 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
657 initMsgByteReader.Reset(initMsg)
658 res, err = http.DefaultClient.Do(req)
659 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700660 if i < 100 {
661 if i%10 == 0 {
662 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
663 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700664 continue
665 }
666 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
667 }
668 break
669 }
670 resBytes, _ := io.ReadAll(res.Body)
671 if res.StatusCode != http.StatusOK {
672 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
673 }
674 return nil
675}
676
David Crawshaw5a7b3692025-05-05 16:49:15 -0700677func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700678 h := sha256.Sum256([]byte(gitRoot))
679 imgName = "sketch-" + hex.EncodeToString(h[:6])
680
681 var curImgInitFilesHash string
682 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
683 if strings.Contains(string(out), "No such object") {
684 // Image does not exist, continue and build it.
685 curImgInitFilesHash = ""
686 } else {
687 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
688 }
689 } else {
690 m := map[string]string{}
691 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
692 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
693 }
694 curImgInitFilesHash = m["sketch_context"]
695 }
696
697 candidates, err := findRepoDockerfiles(cwd, gitRoot)
698 if err != nil {
699 return "", fmt.Errorf("find dockerfile: %w", err)
700 }
701
702 var initFiles map[string]string
703 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700704 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700705
706 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
707 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
708 dockerfilePath = candidates[0]
709 contents, err := os.ReadFile(dockerfilePath)
710 if err != nil {
711 return "", err
712 }
713 fmt.Printf("using %s as dev env\n", candidates[0])
714 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700715 return imgName, nil
716 }
717 } else {
718 initFiles, err = readInitFiles(os.DirFS(gitRoot))
719 if err != nil {
720 return "", err
721 }
722 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
723 if err != nil {
724 return "", err
725 }
726 initFileHash := hashInitFiles(initFiles)
727 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700728 return imgName, nil
729 }
730
David Crawshaw5a7b3692025-05-05 16:49:15 -0700731 if model == "gemini" {
732 if strings.HasSuffix(modelURL, "/gemmsgs") {
733 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700734 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700735 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
736 } else {
737 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
738 }
739 }
740
Earl Lee2e463fb2025-04-17 11:22:22 -0700741 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700742 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700743 URL: modelURL,
744 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700745 HTTPC: http.DefaultClient,
746 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000747 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700748 if err != nil {
749 return "", fmt.Errorf("create dockerfile: %w", err)
750 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000751 // Create a unique temporary directory for the Dockerfile
752 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
753 if err != nil {
754 return "", fmt.Errorf("failed to create temporary directory: %w", err)
755 }
756 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700757 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700758 return "", err
759 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000760 // Remove the temporary directory and all contents when done
761 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700762
David Crawshawb5f6a002025-05-05 08:27:16 -0700763 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700764 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 -0700765 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700766 }
767
768 var gitUserEmail, gitUserName string
769 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
770 return "", fmt.Errorf("git config: %s: %v", out, err)
771 } else {
772 gitUserEmail = strings.TrimSpace(string(out))
773 }
774 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
775 return "", fmt.Errorf("git config: %s: %v", out, err)
776 } else {
777 gitUserName = strings.TrimSpace(string(out))
778 }
779
780 start := time.Now()
781 cmd := exec.CommandContext(ctx,
782 "docker", "build",
783 "-t", imgName,
784 "-f", dockerfilePath,
785 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
786 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700787 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700788 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700789 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700790 // We print the docker build output whether or not the user
791 // has selected --verbose. Building an image takes a while
792 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700793 cmd.Stdout = os.Stdout
794 cmd.Stderr = os.Stderr
795 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700796
797 err = run(ctx, "docker build", cmd)
798 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700799 var msg string
800 if generatedDockerfile != "" {
801 if !verbose {
802 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
803 }
804 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
805 }
806 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700807 }
808 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
809 return imgName, nil
810}
811
812func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
813 files, err := findDirDockerfiles(cwd)
814 if err != nil {
815 return nil, err
816 }
817 if len(files) > 0 {
818 return files, nil
819 }
820
821 path := cwd
822 for path != gitRoot {
823 path = filepath.Dir(path)
824 files, err := findDirDockerfiles(path)
825 if err != nil {
826 return nil, err
827 }
828 if len(files) > 0 {
829 return files, nil
830 }
831 }
832 return files, nil
833}
834
835// findDirDockerfiles finds all "Dockerfile*" files in a directory.
836func findDirDockerfiles(root string) (res []string, err error) {
837 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
838 if err != nil {
839 return err
840 }
841 if info.IsDir() && root != path {
842 return filepath.SkipDir
843 }
844 name := strings.ToLower(info.Name())
845 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
846 res = append(res, path)
847 }
848 return nil
849 })
850 if err != nil {
851 return nil, err
852 }
853 return res, nil
854}
855
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700856func checkForEmptyGitRepo(ctx context.Context, path string) error {
857 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
858 cmd.Dir = path
859 _, err := cmd.CombinedOutput()
860 if err != nil {
861 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
862 "git commit --allow-empty -m 'initial commit'")
863 }
864 return nil
865}
866
Earl Lee2e463fb2025-04-17 11:22:22 -0700867func findGitRoot(ctx context.Context, path string) (string, error) {
868 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
869 cmd.Dir = path
870 out, err := cmd.CombinedOutput()
871 if err != nil {
872 if strings.Contains(string(out), "not a git repository") {
873 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
874Consider one of the following options:
875 - cd to a different dir that is already part of a git repo first, or
876 - to create a new git repo from this directory (%s), run this command:
877
878 git init . && git commit --allow-empty -m "initial commit"
879
880and try running sketch again.
881`, path, path)
882 }
883 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
884 }
885 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
886 absGitDir := filepath.Join(path, gitDir)
887 return filepath.Dir(absGitDir), err
888}
889
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000890// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
891// from git config using the sketch.envfwd multi-valued key.
892func getEnvForwardingFromGitConfig(ctx context.Context) []string {
893 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
894 out := string(outb)
895 if err != nil {
896 if strings.Contains(out, "key does not exist") {
897 return nil
898 }
899 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
900 return nil
901 }
902
903 var envVars []string
904 for envVar := range strings.Lines(out) {
905 envVar = strings.TrimSpace(envVar)
906 if envVar == "" {
907 continue
908 }
909 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
910 }
911 return envVars
912}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000913
914// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
915// It handles quoted arguments and escaped characters.
916//
917// Examples:
918//
919// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
920// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
921// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
922func parseDockerArgs(args string) []string {
923 if args = strings.TrimSpace(args); args == "" {
924 return []string{}
925 }
926
927 var result []string
928 var current strings.Builder
929 inQuotes := false
930 escapeNext := false
931 quoteChar := rune(0)
932
933 for _, char := range args {
934 if escapeNext {
935 current.WriteRune(char)
936 escapeNext = false
937 continue
938 }
939
940 if char == '\\' {
941 escapeNext = true
942 continue
943 }
944
945 if char == '"' || char == '\'' {
946 if !inQuotes {
947 inQuotes = true
948 quoteChar = char
949 continue
950 } else if char == quoteChar {
951 inQuotes = false
952 quoteChar = rune(0)
953 continue
954 }
955 // Non-matching quote character inside quotes
956 current.WriteRune(char)
957 continue
958 }
959
960 // Space outside of quotes is an argument separator
961 if char == ' ' && !inQuotes {
962 if current.Len() > 0 {
963 result = append(result, current.String())
964 current.Reset()
965 }
966 continue
967 }
968
969 current.WriteRune(char)
970 }
971
972 // Add the last argument if there is one
973 if current.Len() > 0 {
974 result = append(result, current.String())
975 }
976
977 return result
978}