blob: d824dd00f7544aee31558af8fa66f9b81feedbd0 [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 }
135
David Crawshaw5a7b3692025-05-05 16:49:15 -0700136 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700137 if err != nil {
138 return err
139 }
140
141 linuxSketchBin := config.SketchBinaryLinux
142 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700143 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700144 if err != nil {
145 return err
146 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700147 }
148
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000149 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700150 defer func() {
151 if config.NoCleanup {
152 return
153 }
154 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
155 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
156 _ = out
157 }
158 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
159 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
160 _ = out
161 }
162 }()
163
164 // errCh receives errors from operations that this function calls in separate goroutines.
165 errCh := make(chan error)
166
167 // Start the git server
168 gitSrv, err := newGitServer(gitRoot)
169 if err != nil {
170 return fmt.Errorf("failed to start git server: %w", err)
171 }
172 defer gitSrv.shutdown(ctx)
173
174 go func() {
175 errCh <- gitSrv.serve(ctx)
176 }()
177
178 // Get the current host git commit
179 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000180 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
181 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700182 } else {
183 commit = strings.TrimSpace(string(out))
184 }
185 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
186 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
187 }
188
189 relPath, err := filepath.Rel(gitRoot, config.Path)
190 if err != nil {
191 return err
192 }
193
194 // Create the sketch container
195 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000196 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700197 }
198
199 // Copy the sketch linux binary into the container
200 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
201 return fmt.Errorf("docker cp: %s, %w", out, err)
202 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700203
204 // Make sure that the webui is built so we can copy the results to the container.
205 _, err = webui.Build()
206 if err != nil {
207 return fmt.Errorf("failed to build webui: %w", err)
208 }
209
David Crawshaw8bff16a2025-04-18 01:16:49 -0700210 webuiZipPath, err := webui.ZipPath()
211 if err != nil {
212 return err
213 }
214 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
215 return fmt.Errorf("docker cp: %s, %w", out, err)
216 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700217
David Crawshaw53786ef2025-04-24 12:52:51 -0700218 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700219
220 // Start the sketch container
221 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
222 return fmt.Errorf("docker start: %s, %w", out, err)
223 }
224
225 // Copies structured logs from the container to the host.
226 copyLogs := func() {
227 if config.ContainerLogDest == "" {
228 return
229 }
230 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
231 if err != nil {
232 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
233 return
234 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700235 prefix := []byte("structured logs:")
236 for line := range bytes.Lines(out) {
237 rest, ok := bytes.CutPrefix(line, prefix)
238 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700239 continue
240 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700241 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700242 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
243 logFileName := filepath.Base(logFile)
244 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
245 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
246 if err != nil {
247 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
248 }
249 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
250 }
251 }
252
253 // NOTE: we want to see what the internal sketch binary prints
254 // regardless of the setting of the verbosity flag on the external
255 // binary, so reading "docker logs", which is the stdout/stderr of
256 // the internal binary is not conditional on the verbose flag.
257 appendInternalErr := func(err error) error {
258 if err == nil {
259 return nil
260 }
261 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000262 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700263 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
264 }
265 out = bytes.TrimSpace(out)
266 if len(out) > 0 {
267 return fmt.Errorf("docker logs: %s;\n%w", out, err)
268 }
269 return err
270 }
271
272 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700273 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700274 if err != nil {
275 return appendInternalErr(err)
276 }
277
Philip Zeyliger00442412025-05-14 11:03:23 -0700278 if config.Verbose {
279 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
280 }
281
Sean McCulloughae3480f2025-04-23 15:28:20 -0700282 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
283 if err != nil {
284 return appendInternalErr(err)
285 }
286 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
287 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700288 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700289 }
Sean McCullough4854c652025-04-24 18:37:02 -0700290
Sean McCullough7013e9e2025-05-14 02:03:58 +0000291 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700292
Sean McCullough078e85a2025-05-08 17:28:34 -0700293 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
294 if err != nil {
295 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
296 }
297
298 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700299 sshAvailable := false
300 sshErrMsg := ""
301 if sshErr != nil {
302 fmt.Println(sshErr.Error())
303 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700304 // continue - ssh config is not required for the rest of sketch to function locally.
305 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700306 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700307 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
308 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700309 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700310🖥️ ssh %s
311🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700312🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700313`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700314 sshUserIdentity = cst.userIdentity
315 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000316
317 // Get the Container CA public key for mutual auth
318 if cst.containerCAPublicKey != nil {
319 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
320 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
321 }
322
323 // Get the host certificate for mutual auth
324 hostCertificate = cst.hostCertificate
325
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700326 defer func() {
327 if err := cst.Cleanup(); err != nil {
328 appendInternalErr(err)
329 }
330 }()
331 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700332
Earl Lee2e463fb2025-04-17 11:22:22 -0700333 // Tell the sketch container which git server port and commit to initialize with.
334 go func() {
335 // TODO: Why is this called in a goroutine? I have found that when I pull this out
336 // of the goroutine and call it inline, then the terminal UI clears itself and all
337 // the scrollback (which is not good, but also not fatal). I can't see why it does this
338 // though, since none of the calls in postContainerInitConfig obviously write to stdout
339 // or stderr.
Sean McCullough7013e9e2025-05-14 02:03:58 +0000340 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 -0700341 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
342 errCh <- appendInternalErr(err)
343 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700344
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700345 // 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 -0700346 ps1URL := "http://" + localAddr
347 if config.SkabandAddr != "" {
348 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700349 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700350 if config.OpenBrowser {
351 browser.Open(ps1URL)
352 }
353 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700354 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700355
356 go func() {
357 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
358 cmd.Stdin = os.Stdin
359 cmd.Stdout = os.Stdout
360 cmd.Stderr = os.Stderr
361 errCh <- run(ctx, "docker attach", cmd)
362 }()
363
364 defer copyLogs()
365
366 for {
367 select {
368 case <-ctx.Done():
369 return ctx.Err()
370 case err := <-errCh:
371 if err != nil {
372 return appendInternalErr(fmt.Errorf("container process: %w", err))
373 }
374 return nil
375 }
376 }
377}
378
379func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
380 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700381 start := time.Now()
382
383 out, err := cmd.CombinedOutput()
384 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700385 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 -0700386 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700387 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 -0700388 }
389 return out, err
390}
391
392func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
393 start := time.Now()
394 err := cmd.Run()
395 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700396 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 -0700397 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700398 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 -0700399 }
400 return err
401}
402
403type gitServer struct {
404 gitLn net.Listener
405 gitPort string
406 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700407 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700408 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700409}
410
411func (gs *gitServer) shutdown(ctx context.Context) {
412 gs.srv.Shutdown(ctx)
413 gs.gitLn.Close()
414}
415
416// Serve a git remote from the host for the container to fetch from and push to.
417func (gs *gitServer) serve(ctx context.Context) error {
418 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
419 return gs.srv.Serve(gs.gitLn)
420}
421
422func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700423 ret := &gitServer{
424 pass: rand.Text(),
425 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700426
Earl Lee2e463fb2025-04-17 11:22:22 -0700427 gitLn, err := net.Listen("tcp4", ":0")
428 if err != nil {
429 return nil, fmt.Errorf("git listen: %w", err)
430 }
431 ret.gitLn = gitLn
432
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700433 browserC := make(chan bool, 1) // channel of browser open requests
434
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000435 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700436 for range browserC {
437 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000438 }
439 }()
440
441 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700442 ret.srv = &srv
443
444 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
445 if err != nil {
446 return nil, fmt.Errorf("git port: %w", err)
447 }
448 ret.gitPort = gitPort
449 return ret, nil
450}
451
452func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700453 cmdArgs := []string{
454 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700455 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700456 "--name", cntrName,
457 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700458 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700459 }
David Crawshaw66cf74e2025-05-05 08:48:39 -0700460 if !config.OneShot {
461 cmdArgs = append(cmdArgs, "-t")
462 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000463
464 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
465 cmdArgs = append(cmdArgs, "-e", envVar)
466 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700467 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700468 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700469 }
470 if config.SketchPubKey != "" {
471 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
472 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700473 if config.SSHPort > 0 {
474 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
475 } else {
476 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700477 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700478 if relPath != "." {
479 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
480 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700481 // colima does this by default, but Linux docker seems to need this set explicitly
482 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700483 cmdArgs = append(
484 cmdArgs,
485 imgName,
486 "/bin/sketch",
487 "-unsafe",
488 "-addr=:80",
489 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000490 "-git-username="+config.GitUsername,
491 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000492 "-outside-hostname="+config.OutsideHostname,
493 "-outside-os="+config.OutsideOS,
494 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700495 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700496 "-termui="+fmt.Sprintf("%t", config.TermUI),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000497 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700498 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700499 if config.Model != "" {
500 cmdArgs = append(cmdArgs, "-model="+config.Model)
501 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000502 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100503 if config.Prompt != "" {
504 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
505 }
506 if config.OneShot {
507 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700508 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000509 if config.ModelURL == "" {
510 // Forward ANTHROPIC_API_KEY for direct use.
511 // TODO: have outtie run an http proxy?
512 // TODO: select and forward the relevant API key based on the model
513 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
514 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000515
516 // Add additional docker arguments if provided
517 if config.DockerArgs != "" {
518 // Parse space-separated docker arguments with support for quotes and escaping
519 args := parseDockerArgs(config.DockerArgs)
520 // Insert arguments after "create" but before other arguments
521 for i := len(args) - 1; i >= 0; i-- {
522 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
523 }
524 }
525
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
527 return fmt.Errorf("docker create: %s, %w", out, err)
528 }
529 return nil
530}
531
David Crawshawb5f6a002025-05-05 08:27:16 -0700532func buildLinuxSketchBin(ctx context.Context) (string, error) {
Pokey Rulea9a786b2025-05-12 10:52:34 +0100533 // Change to directory containing dockerimg.go for module detection
534 _, codeFile, _, _ := runtime.Caller(0)
535 codeDir := filepath.Dir(codeFile)
536 if currentDir, err := os.Getwd(); err != nil {
537 slog.WarnContext(ctx, "could not get current directory", "err", err)
538 } else {
539 if err := os.Chdir(codeDir); err != nil {
540 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
541 } else {
542 defer func() {
543 _ = os.Chdir(currentDir)
544 }()
545 }
546 }
547
David Crawshaw8a617cb2025-04-18 01:28:43 -0700548 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700549 if err != nil {
550 return "", err
551 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700552 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
553 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
554 return "", err
555 }
556
557 verToInstall := "@latest"
558 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
559 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
560 } else {
561 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700562 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700563 verToInstall = ""
564 }
565 }
David Crawshaw69c67312025-04-17 13:42:00 -0700566
Earl Lee2e463fb2025-04-17 11:22:22 -0700567 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700568 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700569 cmd.Env = append(
570 os.Environ(),
571 "GOOS=linux",
572 "CGO_ENABLED=0",
573 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700574 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700575 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700576 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700577
Earl Lee2e463fb2025-04-17 11:22:22 -0700578 out, err := cmd.CombinedOutput()
579 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700580 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 -0700581 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
582 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700583 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 -0700584 }
585
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700586 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700587 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700588 }
David Crawshawc7e77962025-05-03 13:20:18 -0700589 // If we are already on Linux, there's no extra platform name in the path
590 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700591}
592
Sean McCulloughae3480f2025-04-23 15:28:20 -0700593func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700594 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700595 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700596 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
597 } else {
598 v4, _, found := strings.Cut(string(out), "\n")
599 if !found {
600 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
601 }
602 localAddr = v4
603 if strings.HasPrefix(localAddr, "0.0.0.0") {
604 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
605 }
606 }
607 return localAddr, nil
608}
609
610// Contact the container and configure it.
Sean McCullough7013e9e2025-05-14 02:03:58 +0000611func 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 -0700612 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700613
614 initMsg, err := json.Marshal(
615 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000616 Commit: commit,
617 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
618 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
619 HostAddr: localAddr,
620 SSHAuthorizedKeys: sshAuthorizedKeys,
621 SSHServerIdentity: sshServerIdentity,
622 SSHContainerCAKey: sshContainerCAKey,
623 SSHHostCertificate: sshHostCertificate,
624 SSHAvailable: sshAvailable,
625 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700626 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700627 if err != nil {
628 return fmt.Errorf("init msg: %w", err)
629 }
630
Earl Lee2e463fb2025-04-17 11:22:22 -0700631 // Note: this /init POST is handled in loop/server/loophttp.go:
632 initMsgByteReader := bytes.NewReader(initMsg)
633 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
634 if err != nil {
635 return err
636 }
637
638 var res *http.Response
639 for i := 0; ; i++ {
640 time.Sleep(100 * time.Millisecond)
641 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
642 initMsgByteReader.Reset(initMsg)
643 res, err = http.DefaultClient.Do(req)
644 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700645 if i < 100 {
646 if i%10 == 0 {
647 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
648 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700649 continue
650 }
651 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
652 }
653 break
654 }
655 resBytes, _ := io.ReadAll(res.Body)
656 if res.StatusCode != http.StatusOK {
657 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
658 }
659 return nil
660}
661
David Crawshaw5a7b3692025-05-05 16:49:15 -0700662func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700663 h := sha256.Sum256([]byte(gitRoot))
664 imgName = "sketch-" + hex.EncodeToString(h[:6])
665
666 var curImgInitFilesHash string
667 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
668 if strings.Contains(string(out), "No such object") {
669 // Image does not exist, continue and build it.
670 curImgInitFilesHash = ""
671 } else {
672 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
673 }
674 } else {
675 m := map[string]string{}
676 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
677 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
678 }
679 curImgInitFilesHash = m["sketch_context"]
680 }
681
682 candidates, err := findRepoDockerfiles(cwd, gitRoot)
683 if err != nil {
684 return "", fmt.Errorf("find dockerfile: %w", err)
685 }
686
687 var initFiles map[string]string
688 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700689 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700690
691 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
692 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
693 dockerfilePath = candidates[0]
694 contents, err := os.ReadFile(dockerfilePath)
695 if err != nil {
696 return "", err
697 }
698 fmt.Printf("using %s as dev env\n", candidates[0])
699 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700700 return imgName, nil
701 }
702 } else {
703 initFiles, err = readInitFiles(os.DirFS(gitRoot))
704 if err != nil {
705 return "", err
706 }
707 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
708 if err != nil {
709 return "", err
710 }
711 initFileHash := hashInitFiles(initFiles)
712 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700713 return imgName, nil
714 }
715
David Crawshaw5a7b3692025-05-05 16:49:15 -0700716 if model == "gemini" {
717 if strings.HasSuffix(modelURL, "/gemmsgs") {
718 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700719 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700720 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
721 } else {
722 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
723 }
724 }
725
Earl Lee2e463fb2025-04-17 11:22:22 -0700726 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700727 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700728 URL: modelURL,
729 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700730 HTTPC: http.DefaultClient,
731 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000732 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700733 if err != nil {
734 return "", fmt.Errorf("create dockerfile: %w", err)
735 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000736 // Create a unique temporary directory for the Dockerfile
737 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
738 if err != nil {
739 return "", fmt.Errorf("failed to create temporary directory: %w", err)
740 }
741 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700742 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700743 return "", err
744 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000745 // Remove the temporary directory and all contents when done
746 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700747
David Crawshawb5f6a002025-05-05 08:27:16 -0700748 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700749 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 -0700750 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700751 }
752
753 var gitUserEmail, gitUserName string
754 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
755 return "", fmt.Errorf("git config: %s: %v", out, err)
756 } else {
757 gitUserEmail = strings.TrimSpace(string(out))
758 }
759 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
760 return "", fmt.Errorf("git config: %s: %v", out, err)
761 } else {
762 gitUserName = strings.TrimSpace(string(out))
763 }
764
765 start := time.Now()
766 cmd := exec.CommandContext(ctx,
767 "docker", "build",
768 "-t", imgName,
769 "-f", dockerfilePath,
770 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
771 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700772 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700773 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700774 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700775 // We print the docker build output whether or not the user
776 // has selected --verbose. Building an image takes a while
777 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700778 cmd.Stdout = os.Stdout
779 cmd.Stderr = os.Stderr
780 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700781
782 err = run(ctx, "docker build", cmd)
783 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700784 var msg string
785 if generatedDockerfile != "" {
786 if !verbose {
787 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
788 }
789 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
790 }
791 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700792 }
793 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
794 return imgName, nil
795}
796
797func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
798 files, err := findDirDockerfiles(cwd)
799 if err != nil {
800 return nil, err
801 }
802 if len(files) > 0 {
803 return files, nil
804 }
805
806 path := cwd
807 for path != gitRoot {
808 path = filepath.Dir(path)
809 files, err := findDirDockerfiles(path)
810 if err != nil {
811 return nil, err
812 }
813 if len(files) > 0 {
814 return files, nil
815 }
816 }
817 return files, nil
818}
819
820// findDirDockerfiles finds all "Dockerfile*" files in a directory.
821func findDirDockerfiles(root string) (res []string, err error) {
822 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
823 if err != nil {
824 return err
825 }
826 if info.IsDir() && root != path {
827 return filepath.SkipDir
828 }
829 name := strings.ToLower(info.Name())
830 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
831 res = append(res, path)
832 }
833 return nil
834 })
835 if err != nil {
836 return nil, err
837 }
838 return res, nil
839}
840
841func findGitRoot(ctx context.Context, path string) (string, error) {
842 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
843 cmd.Dir = path
844 out, err := cmd.CombinedOutput()
845 if err != nil {
846 if strings.Contains(string(out), "not a git repository") {
847 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
848Consider one of the following options:
849 - cd to a different dir that is already part of a git repo first, or
850 - to create a new git repo from this directory (%s), run this command:
851
852 git init . && git commit --allow-empty -m "initial commit"
853
854and try running sketch again.
855`, path, path)
856 }
857 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
858 }
859 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
860 absGitDir := filepath.Join(path, gitDir)
861 return filepath.Dir(absGitDir), err
862}
863
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000864// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
865// from git config using the sketch.envfwd multi-valued key.
866func getEnvForwardingFromGitConfig(ctx context.Context) []string {
867 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
868 out := string(outb)
869 if err != nil {
870 if strings.Contains(out, "key does not exist") {
871 return nil
872 }
873 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
874 return nil
875 }
876
877 var envVars []string
878 for envVar := range strings.Lines(out) {
879 envVar = strings.TrimSpace(envVar)
880 if envVar == "" {
881 continue
882 }
883 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
884 }
885 return envVars
886}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000887
888// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
889// It handles quoted arguments and escaped characters.
890//
891// Examples:
892//
893// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
894// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
895// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
896func parseDockerArgs(args string) []string {
897 if args = strings.TrimSpace(args); args == "" {
898 return []string{}
899 }
900
901 var result []string
902 var current strings.Builder
903 inQuotes := false
904 escapeNext := false
905 quoteChar := rune(0)
906
907 for _, char := range args {
908 if escapeNext {
909 current.WriteRune(char)
910 escapeNext = false
911 continue
912 }
913
914 if char == '\\' {
915 escapeNext = true
916 continue
917 }
918
919 if char == '"' || char == '\'' {
920 if !inQuotes {
921 inQuotes = true
922 quoteChar = char
923 continue
924 } else if char == quoteChar {
925 inQuotes = false
926 quoteChar = rune(0)
927 continue
928 }
929 // Non-matching quote character inside quotes
930 current.WriteRune(char)
931 continue
932 }
933
934 // Space outside of quotes is an argument separator
935 if char == ' ' && !inQuotes {
936 if current.Len() > 0 {
937 result = append(result, current.String())
938 current.Reset()
939 }
940 continue
941 }
942
943 current.WriteRune(char)
944 }
945
946 // Add the last argument if there is one
947 if current.Len() > 0 {
948 result = append(result, current.String())
949 }
950
951 return result
952}