| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 1 | // Package dockerimg |
| 2 | package dockerimg |
| 3 | |
| 4 | import ( |
| 5 | "bytes" |
| 6 | "context" |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 7 | "crypto/rand" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 8 | "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" |
| 21 | "time" |
| 22 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 23 | "sketch.dev/loop/server" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 24 | "sketch.dev/skribe" |
| Philip Zeyliger | 5d6af87 | 2025-04-23 19:48:34 -0700 | [diff] [blame] | 25 | "sketch.dev/webui" |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 26 | ) |
| 27 | |
| 28 | // ContainerConfig holds all configuration for launching a container |
| 29 | type ContainerConfig struct { |
| 30 | // SessionID is the unique identifier for this session |
| 31 | SessionID string |
| 32 | |
| 33 | // LocalAddr is the initial address to use (though it may be overwritten later) |
| 34 | LocalAddr string |
| 35 | |
| 36 | // SkabandAddr is the address of the skaband service if available |
| 37 | SkabandAddr string |
| 38 | |
| 39 | // AntURL is the URL of the LLM service. |
| 40 | AntURL string |
| 41 | |
| 42 | // AntAPIKey is the API key for LLM service. |
| 43 | AntAPIKey string |
| 44 | |
| 45 | // Path is the local filesystem path to use |
| 46 | Path string |
| 47 | |
| 48 | // GitUsername is the username to use for git operations |
| 49 | GitUsername string |
| 50 | |
| 51 | // GitEmail is the email to use for git operations |
| 52 | GitEmail string |
| 53 | |
| 54 | // OpenBrowser determines whether to open a browser automatically |
| 55 | OpenBrowser bool |
| 56 | |
| 57 | // NoCleanup prevents container cleanup when set to true |
| 58 | NoCleanup bool |
| 59 | |
| 60 | // ForceRebuild forces rebuilding of the Docker image even if it exists |
| 61 | ForceRebuild bool |
| 62 | |
| 63 | // Host directory to copy container logs into, if not set to "" |
| 64 | ContainerLogDest string |
| 65 | |
| 66 | // Path to pre-built linux sketch binary, or build a new one if set to "" |
| 67 | SketchBinaryLinux string |
| 68 | |
| 69 | // Sketch client public key. |
| 70 | SketchPubKey string |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 71 | |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 72 | // Host port for the container's ssh server |
| 73 | SSHPort int |
| 74 | |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 75 | // Outside information to pass to the container |
| 76 | OutsideHostname string |
| 77 | OutsideOS string |
| 78 | OutsideWorkingDir string |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 79 | |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 80 | // If true, exit after the first turn |
| 81 | OneShot bool |
| 82 | |
| 83 | // Initial prompt |
| 84 | Prompt string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 85 | } |
| 86 | |
| 87 | // LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it. |
| 88 | // It writes status to stdout. |
| 89 | func LaunchContainer(ctx context.Context, stdout, stderr io.Writer, config ContainerConfig) error { |
| 90 | if _, err := exec.LookPath("docker"); err != nil { |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 91 | if runtime.GOOS == "darwin" { |
| 92 | return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start") |
| 93 | } else { |
| 94 | return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)") |
| 95 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 96 | } |
| 97 | |
| 98 | if out, err := combinedOutput(ctx, "docker", "ps"); err != nil { |
| 99 | // `docker ps` provides a good error message here that can be |
| 100 | // easily chatgpt'ed by users, so send it to the user as-is: |
| 101 | // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? |
| 102 | return fmt.Errorf("docker ps: %s (%w)", out, err) |
| 103 | } |
| 104 | |
| 105 | _, hostPort, err := net.SplitHostPort(config.LocalAddr) |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | |
| 110 | gitRoot, err := findGitRoot(ctx, config.Path) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | |
| 115 | imgName, err := findOrBuildDockerImage(ctx, stdout, stderr, config.Path, gitRoot, config.AntURL, config.AntAPIKey, config.ForceRebuild) |
| 116 | if err != nil { |
| 117 | return err |
| 118 | } |
| 119 | |
| 120 | linuxSketchBin := config.SketchBinaryLinux |
| 121 | if linuxSketchBin == "" { |
| 122 | linuxSketchBin, err = buildLinuxSketchBin(ctx, config.Path) |
| 123 | if err != nil { |
| 124 | return err |
| 125 | } |
| Josh Bleecher Snyder | 5544d14 | 2025-04-23 14:15:45 -0700 | [diff] [blame] | 126 | defer os.Remove(linuxSketchBin) // in case of errors |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 127 | } |
| 128 | |
| 129 | cntrName := imgName + "-" + config.SessionID |
| 130 | defer func() { |
| 131 | if config.NoCleanup { |
| 132 | return |
| 133 | } |
| 134 | if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil { |
| 135 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 136 | _ = out |
| 137 | } |
| 138 | if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil { |
| 139 | // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err) |
| 140 | _ = out |
| 141 | } |
| 142 | }() |
| 143 | |
| 144 | // errCh receives errors from operations that this function calls in separate goroutines. |
| 145 | errCh := make(chan error) |
| 146 | |
| 147 | // Start the git server |
| 148 | gitSrv, err := newGitServer(gitRoot) |
| 149 | if err != nil { |
| 150 | return fmt.Errorf("failed to start git server: %w", err) |
| 151 | } |
| 152 | defer gitSrv.shutdown(ctx) |
| 153 | |
| 154 | go func() { |
| 155 | errCh <- gitSrv.serve(ctx) |
| 156 | }() |
| 157 | |
| 158 | // Get the current host git commit |
| 159 | var commit string |
| 160 | if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil { |
| 161 | return fmt.Errorf("git rev-parse HEAD: %w", err) |
| 162 | } else { |
| 163 | commit = strings.TrimSpace(string(out)) |
| 164 | } |
| 165 | if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil { |
| 166 | return fmt.Errorf("git config http.receivepack true: %s: %w", out, err) |
| 167 | } |
| 168 | |
| 169 | relPath, err := filepath.Rel(gitRoot, config.Path) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |
| 173 | |
| 174 | // Create the sketch container |
| 175 | if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | |
| 179 | // Copy the sketch linux binary into the container |
| 180 | if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil { |
| 181 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 182 | } |
| Josh Bleecher Snyder | 5544d14 | 2025-04-23 14:15:45 -0700 | [diff] [blame] | 183 | os.Remove(linuxSketchBin) // in normal operations, the code below blocks, so actively delete now |
| Sean McCullough | f5bb3d3 | 2025-04-18 10:47:59 -0700 | [diff] [blame] | 184 | |
| 185 | // Make sure that the webui is built so we can copy the results to the container. |
| 186 | _, err = webui.Build() |
| 187 | if err != nil { |
| 188 | return fmt.Errorf("failed to build webui: %w", err) |
| 189 | } |
| 190 | |
| David Crawshaw | 8bff16a | 2025-04-18 01:16:49 -0700 | [diff] [blame] | 191 | webuiZipPath, err := webui.ZipPath() |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil { |
| 196 | return fmt.Errorf("docker cp: %s, %w", out, err) |
| 197 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 198 | |
| David Crawshaw | 53786ef | 2025-04-24 12:52:51 -0700 | [diff] [blame] | 199 | fmt.Printf("📦 running in container %s\n", cntrName) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 200 | |
| 201 | // Start the sketch container |
| 202 | if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil { |
| 203 | return fmt.Errorf("docker start: %s, %w", out, err) |
| 204 | } |
| 205 | |
| 206 | // Copies structured logs from the container to the host. |
| 207 | copyLogs := func() { |
| 208 | if config.ContainerLogDest == "" { |
| 209 | return |
| 210 | } |
| 211 | out, err := combinedOutput(ctx, "docker", "logs", cntrName) |
| 212 | if err != nil { |
| 213 | fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err) |
| 214 | return |
| 215 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 216 | prefix := []byte("structured logs:") |
| 217 | for line := range bytes.Lines(out) { |
| 218 | rest, ok := bytes.CutPrefix(line, prefix) |
| 219 | if !ok { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 220 | continue |
| 221 | } |
| Josh Bleecher Snyder | 7660e4e | 2025-04-24 10:34:17 -0700 | [diff] [blame] | 222 | logFile := string(bytes.TrimSpace(rest)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 223 | srcPath := fmt.Sprintf("%s:%s", cntrName, logFile) |
| 224 | logFileName := filepath.Base(logFile) |
| 225 | dstPath := filepath.Join(config.ContainerLogDest, logFileName) |
| 226 | _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath) |
| 227 | if err != nil { |
| 228 | fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err) |
| 229 | } |
| 230 | fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // NOTE: we want to see what the internal sketch binary prints |
| 235 | // regardless of the setting of the verbosity flag on the external |
| 236 | // binary, so reading "docker logs", which is the stdout/stderr of |
| 237 | // the internal binary is not conditional on the verbose flag. |
| 238 | appendInternalErr := func(err error) error { |
| 239 | if err == nil { |
| 240 | return nil |
| 241 | } |
| 242 | out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName) |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 243 | if logsErr != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 244 | return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr) |
| 245 | } |
| 246 | out = bytes.TrimSpace(out) |
| 247 | if len(out) > 0 { |
| 248 | return fmt.Errorf("docker logs: %s;\n%w", out, err) |
| 249 | } |
| 250 | return err |
| 251 | } |
| 252 | |
| 253 | // Get the sketch server port from the container |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 254 | localAddr, err := getContainerPort(ctx, cntrName, "80") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 255 | if err != nil { |
| 256 | return appendInternalErr(err) |
| 257 | } |
| 258 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 259 | localSSHAddr, err := getContainerPort(ctx, cntrName, "22") |
| 260 | if err != nil { |
| 261 | return appendInternalErr(err) |
| 262 | } |
| 263 | sshHost, sshPort, err := net.SplitHostPort(localSSHAddr) |
| 264 | if err != nil { |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 265 | return appendInternalErr(fmt.Errorf("Error splitting ssh host and port: %w", err)) |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 266 | } |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 267 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 268 | var sshServerIdentity, sshUserIdentity []byte |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 269 | |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 270 | if err := CheckForInclude(); err != nil { |
| 271 | fmt.Println(err.Error()) |
| 272 | // continue - ssh config is not required for the rest of sketch to function locally. |
| 273 | } else { |
| 274 | cst, err := NewSSHTheather(cntrName, sshHost, sshPort) |
| 275 | if err != nil { |
| 276 | return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err)) |
| 277 | } |
| 278 | |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 279 | // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find: |
| 280 | // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878 |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 281 | fmt.Printf(`Connect to this container via any of these methods: |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 282 | 🖥️ ssh %s |
| 283 | 🖥️ code --remote ssh-remote+root@%s /app -n |
| Sean McCullough | ea3fc20 | 2025-04-28 12:53:37 -0700 | [diff] [blame] | 284 | 🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank |
| Sean McCullough | 4854c65 | 2025-04-24 18:37:02 -0700 | [diff] [blame] | 285 | `, cntrName, cntrName, cntrName) |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 286 | sshUserIdentity = cst.userIdentity |
| 287 | sshServerIdentity = cst.serverIdentity |
| 288 | defer func() { |
| 289 | if err := cst.Cleanup(); err != nil { |
| 290 | appendInternalErr(err) |
| 291 | } |
| 292 | }() |
| 293 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 294 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 295 | // Tell the sketch container which git server port and commit to initialize with. |
| 296 | go func() { |
| 297 | // TODO: Why is this called in a goroutine? I have found that when I pull this out |
| 298 | // of the goroutine and call it inline, then the terminal UI clears itself and all |
| 299 | // the scrollback (which is not good, but also not fatal). I can't see why it does this |
| 300 | // though, since none of the calls in postContainerInitConfig obviously write to stdout |
| 301 | // or stderr. |
| Sean McCullough | f5e28f6 | 2025-04-25 10:48:00 -0700 | [diff] [blame] | 302 | if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshServerIdentity, sshUserIdentity); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 303 | slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error())) |
| 304 | errCh <- appendInternalErr(err) |
| 305 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 306 | |
| Philip Zeyliger | 6ed6adb | 2025-04-23 19:56:38 -0700 | [diff] [blame] | 307 | // We open the browser after the init config because the above waits for the web server to be serving. |
| 308 | if config.OpenBrowser { |
| 309 | if config.SkabandAddr != "" { |
| 310 | OpenBrowser(ctx, fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)) |
| 311 | } else { |
| 312 | OpenBrowser(ctx, "http://"+localAddr) |
| 313 | } |
| 314 | } |
| 315 | }() |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 316 | |
| 317 | go func() { |
| 318 | cmd := exec.CommandContext(ctx, "docker", "attach", cntrName) |
| 319 | cmd.Stdin = os.Stdin |
| 320 | cmd.Stdout = os.Stdout |
| 321 | cmd.Stderr = os.Stderr |
| 322 | errCh <- run(ctx, "docker attach", cmd) |
| 323 | }() |
| 324 | |
| 325 | defer copyLogs() |
| 326 | |
| 327 | for { |
| 328 | select { |
| 329 | case <-ctx.Done(): |
| 330 | return ctx.Err() |
| 331 | case err := <-errCh: |
| 332 | if err != nil { |
| 333 | return appendInternalErr(fmt.Errorf("container process: %w", err)) |
| 334 | } |
| 335 | return nil |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) { |
| 341 | cmd := exec.CommandContext(ctx, cmdName, args...) |
| 342 | // Really only needed for the "go build" command for the linux sketch binary |
| 343 | cmd.Env = append(os.Environ(), "GOOS=linux", "CGO_ENABLED=0") |
| 344 | start := time.Now() |
| 345 | |
| 346 | out, err := cmd.CombinedOutput() |
| 347 | if err != nil { |
| 348 | slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 349 | } else { |
| 350 | slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 351 | } |
| 352 | return out, err |
| 353 | } |
| 354 | |
| 355 | func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error { |
| 356 | start := time.Now() |
| 357 | err := cmd.Run() |
| 358 | if err != nil { |
| 359 | slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 360 | } else { |
| 361 | slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 362 | } |
| 363 | return err |
| 364 | } |
| 365 | |
| 366 | type gitServer struct { |
| 367 | gitLn net.Listener |
| 368 | gitPort string |
| 369 | srv *http.Server |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 370 | pass string |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 371 | } |
| 372 | |
| 373 | func (gs *gitServer) shutdown(ctx context.Context) { |
| 374 | gs.srv.Shutdown(ctx) |
| 375 | gs.gitLn.Close() |
| 376 | } |
| 377 | |
| 378 | // Serve a git remote from the host for the container to fetch from and push to. |
| 379 | func (gs *gitServer) serve(ctx context.Context) error { |
| 380 | slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git")) |
| 381 | return gs.srv.Serve(gs.gitLn) |
| 382 | } |
| 383 | |
| 384 | func newGitServer(gitRoot string) (*gitServer, error) { |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 385 | ret := &gitServer{ |
| 386 | pass: rand.Text(), |
| 387 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 388 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 389 | gitLn, err := net.Listen("tcp4", ":0") |
| 390 | if err != nil { |
| 391 | return nil, fmt.Errorf("git listen: %w", err) |
| 392 | } |
| 393 | ret.gitLn = gitLn |
| 394 | |
| 395 | srv := http.Server{ |
| Josh Bleecher Snyder | 9f6a998 | 2025-04-22 17:34:15 -0700 | [diff] [blame] | 396 | Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass)}, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 397 | } |
| 398 | ret.srv = &srv |
| 399 | |
| 400 | _, gitPort, err := net.SplitHostPort(gitLn.Addr().String()) |
| 401 | if err != nil { |
| 402 | return nil, fmt.Errorf("git port: %w", err) |
| 403 | } |
| 404 | ret.gitPort = gitPort |
| 405 | return ret, nil |
| 406 | } |
| 407 | |
| 408 | func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error { |
| 409 | //, config.SessionID, config.GitUsername, config.GitEmail, config.SkabandAddr |
| 410 | // sessionID, gitUsername, gitEmail, skabandAddr string |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 411 | cmdArgs := []string{ |
| 412 | "create", |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 413 | "-it", |
| 414 | "--name", cntrName, |
| 415 | "-p", hostPort + ":80", // forward container port 80 to a host port |
| 416 | "-e", "ANTHROPIC_API_KEY=" + config.AntAPIKey, |
| 417 | } |
| 418 | if config.AntURL != "" { |
| 419 | cmdArgs = append(cmdArgs, "-e", "ANT_URL="+config.AntURL) |
| 420 | } |
| 421 | if config.SketchPubKey != "" { |
| 422 | cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey) |
| 423 | } |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 424 | if config.SSHPort > 0 { |
| 425 | cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port |
| 426 | } else { |
| 427 | cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh. |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 428 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 429 | if relPath != "." { |
| 430 | cmdArgs = append(cmdArgs, "-w", "/app/"+relPath) |
| 431 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 432 | // colima does this by default, but Linux docker seems to need this set explicitly |
| 433 | cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway") |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 434 | cmdArgs = append( |
| 435 | cmdArgs, |
| 436 | imgName, |
| 437 | "/bin/sketch", |
| 438 | "-unsafe", |
| 439 | "-addr=:80", |
| 440 | "-session-id="+config.SessionID, |
| Philip Zeyliger | d140295 | 2025-04-23 03:54:37 +0000 | [diff] [blame] | 441 | "-git-username="+config.GitUsername, |
| 442 | "-git-email="+config.GitEmail, |
| Philip Zeyliger | 18532b2 | 2025-04-23 21:11:46 +0000 | [diff] [blame] | 443 | "-outside-hostname="+config.OutsideHostname, |
| 444 | "-outside-os="+config.OutsideOS, |
| 445 | "-outside-working-dir="+config.OutsideWorkingDir, |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 446 | ) |
| 447 | if config.SkabandAddr != "" { |
| 448 | cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr) |
| 449 | } |
| Pokey Rule | 0dcebe1 | 2025-04-28 14:51:04 +0100 | [diff] [blame] | 450 | if config.Prompt != "" { |
| 451 | cmdArgs = append(cmdArgs, "-prompt", config.Prompt) |
| 452 | } |
| 453 | if config.OneShot { |
| 454 | cmdArgs = append(cmdArgs, "-one-shot") |
| Philip Zeyliger | b74c4f6 | 2025-04-25 19:18:49 -0700 | [diff] [blame] | 455 | } |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 456 | if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil { |
| 457 | return fmt.Errorf("docker create: %s, %w", out, err) |
| 458 | } |
| 459 | return nil |
| 460 | } |
| 461 | |
| 462 | func buildLinuxSketchBin(ctx context.Context, path string) (string, error) { |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 463 | homeDir, err := os.UserHomeDir() |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 464 | if err != nil { |
| 465 | return "", err |
| 466 | } |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 467 | linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo") |
| 468 | if err := os.MkdirAll(linuxGopath, 0o777); err != nil { |
| 469 | return "", err |
| 470 | } |
| 471 | |
| 472 | verToInstall := "@latest" |
| 473 | if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil { |
| 474 | return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err) |
| 475 | } else { |
| 476 | if strings.TrimSpace(string(out)) == "sketch.dev" { |
| David Crawshaw | 094e4d2 | 2025-04-24 11:35:14 -0700 | [diff] [blame] | 477 | slog.DebugContext(ctx, "built linux agent from currently checked out module") |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 478 | verToInstall = "" |
| 479 | } |
| 480 | } |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 481 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 482 | start := time.Now() |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 483 | cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall) |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 484 | cmd.Env = append( |
| 485 | os.Environ(), |
| 486 | "GOOS=linux", |
| 487 | "CGO_ENABLED=0", |
| 488 | "GOTOOLCHAIN=auto", |
| David Crawshaw | 8a617cb | 2025-04-18 01:28:43 -0700 | [diff] [blame] | 489 | "GOPATH="+linuxGopath, |
| Josh Bleecher Snyder | fae1757 | 2025-04-21 11:48:05 -0700 | [diff] [blame] | 490 | "GOBIN=", |
| David Crawshaw | b9eaef5 | 2025-04-17 15:23:18 -0700 | [diff] [blame] | 491 | ) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 492 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 493 | out, err := cmd.CombinedOutput() |
| 494 | if err != nil { |
| 495 | slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 496 | return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err) |
| 497 | } else { |
| 498 | slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Now().Sub(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args)))) |
| 499 | } |
| 500 | |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 501 | var src string |
| 502 | if runtime.GOOS != "linux" { |
| 503 | src = filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch") |
| 504 | } else { |
| 505 | // If we are already on Linux, there's no extra platform name in the path |
| 506 | src = filepath.Join(linuxGopath, "bin", "sketch") |
| 507 | } |
| 508 | |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 509 | dst := filepath.Join(path, "tmp-sketch-binary-linux") |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 510 | if err := moveFile(src, dst); err != nil { |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 511 | return "", err |
| 512 | } |
| 513 | |
| David Crawshaw | 69c6731 | 2025-04-17 13:42:00 -0700 | [diff] [blame] | 514 | return dst, nil |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 515 | } |
| 516 | |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 517 | func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 518 | localAddr := "" |
| Sean McCullough | ae3480f | 2025-04-23 15:28:20 -0700 | [diff] [blame] | 519 | if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 520 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 521 | } else { |
| 522 | v4, _, found := strings.Cut(string(out), "\n") |
| 523 | if !found { |
| 524 | return "", fmt.Errorf("failed to find container port: %s: %v", out, err) |
| 525 | } |
| 526 | localAddr = v4 |
| 527 | if strings.HasPrefix(localAddr, "0.0.0.0") { |
| 528 | localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0") |
| 529 | } |
| 530 | } |
| 531 | return localAddr, nil |
| 532 | } |
| 533 | |
| 534 | // Contact the container and configure it. |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 535 | func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshServerIdentity, sshAuthorizedKeys []byte) error { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 536 | localURL := "http://" + localAddr |
| Sean McCullough | baa2b59 | 2025-04-23 10:40:08 -0700 | [diff] [blame] | 537 | |
| 538 | initMsg, err := json.Marshal( |
| 539 | server.InitRequest{ |
| 540 | Commit: commit, |
| 541 | GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort), |
| 542 | HostAddr: localAddr, |
| 543 | SSHAuthorizedKeys: sshAuthorizedKeys, |
| 544 | SSHServerIdentity: sshServerIdentity, |
| 545 | }) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 546 | if err != nil { |
| 547 | return fmt.Errorf("init msg: %w", err) |
| 548 | } |
| 549 | |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 550 | // Note: this /init POST is handled in loop/server/loophttp.go: |
| 551 | initMsgByteReader := bytes.NewReader(initMsg) |
| 552 | req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader) |
| 553 | if err != nil { |
| 554 | return err |
| 555 | } |
| 556 | |
| 557 | var res *http.Response |
| 558 | for i := 0; ; i++ { |
| 559 | time.Sleep(100 * time.Millisecond) |
| 560 | // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes. |
| 561 | initMsgByteReader.Reset(initMsg) |
| 562 | res, err = http.DefaultClient.Do(req) |
| 563 | if err != nil { |
| 564 | // In addition to "connection refused", we also occasionally see "EOF" errors that can succeed on retries. |
| 565 | if i < 100 && (strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "EOF")) { |
| 566 | slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error())) |
| 567 | continue |
| 568 | } |
| 569 | return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err) |
| 570 | } |
| 571 | break |
| 572 | } |
| 573 | resBytes, _ := io.ReadAll(res.Body) |
| 574 | if res.StatusCode != http.StatusOK { |
| 575 | return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes) |
| 576 | } |
| 577 | return nil |
| 578 | } |
| 579 | |
| 580 | func findOrBuildDockerImage(ctx context.Context, stdout, stderr io.Writer, cwd, gitRoot, antURL, antAPIKey string, forceRebuild bool) (imgName string, err error) { |
| 581 | h := sha256.Sum256([]byte(gitRoot)) |
| 582 | imgName = "sketch-" + hex.EncodeToString(h[:6]) |
| 583 | |
| 584 | var curImgInitFilesHash string |
| 585 | if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil { |
| 586 | if strings.Contains(string(out), "No such object") { |
| 587 | // Image does not exist, continue and build it. |
| 588 | curImgInitFilesHash = "" |
| 589 | } else { |
| 590 | return "", fmt.Errorf("docker inspect failed: %s, %v", out, err) |
| 591 | } |
| 592 | } else { |
| 593 | m := map[string]string{} |
| 594 | if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil { |
| 595 | return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err) |
| 596 | } |
| 597 | curImgInitFilesHash = m["sketch_context"] |
| 598 | } |
| 599 | |
| 600 | candidates, err := findRepoDockerfiles(cwd, gitRoot) |
| 601 | if err != nil { |
| 602 | return "", fmt.Errorf("find dockerfile: %w", err) |
| 603 | } |
| 604 | |
| 605 | var initFiles map[string]string |
| 606 | var dockerfilePath string |
| 607 | |
| 608 | // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool. |
| 609 | if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" { |
| 610 | dockerfilePath = candidates[0] |
| 611 | contents, err := os.ReadFile(dockerfilePath) |
| 612 | if err != nil { |
| 613 | return "", err |
| 614 | } |
| 615 | fmt.Printf("using %s as dev env\n", candidates[0]) |
| 616 | if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 617 | return imgName, nil |
| 618 | } |
| 619 | } else { |
| 620 | initFiles, err = readInitFiles(os.DirFS(gitRoot)) |
| 621 | if err != nil { |
| 622 | return "", err |
| 623 | } |
| 624 | subPathWorkingDir, err := filepath.Rel(gitRoot, cwd) |
| 625 | if err != nil { |
| 626 | return "", err |
| 627 | } |
| 628 | initFileHash := hashInitFiles(initFiles) |
| 629 | if curImgInitFilesHash == initFileHash && !forceRebuild { |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 630 | return imgName, nil |
| 631 | } |
| 632 | |
| 633 | start := time.Now() |
| 634 | dockerfile, err := createDockerfile(ctx, http.DefaultClient, antURL, antAPIKey, initFiles, subPathWorkingDir) |
| 635 | if err != nil { |
| 636 | return "", fmt.Errorf("create dockerfile: %w", err) |
| 637 | } |
| 638 | dockerfilePath = filepath.Join(cwd, "tmp-sketch-dockerfile") |
| 639 | if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil { |
| 640 | return "", err |
| 641 | } |
| 642 | defer os.Remove(dockerfilePath) |
| 643 | |
| 644 | fmt.Fprintf(stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(dockerfile, "\n", "\n\t", -1)) |
| 645 | } |
| 646 | |
| 647 | var gitUserEmail, gitUserName string |
| 648 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil { |
| 649 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 650 | } else { |
| 651 | gitUserEmail = strings.TrimSpace(string(out)) |
| 652 | } |
| 653 | if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil { |
| 654 | return "", fmt.Errorf("git config: %s: %v", out, err) |
| 655 | } else { |
| 656 | gitUserName = strings.TrimSpace(string(out)) |
| 657 | } |
| 658 | |
| 659 | start := time.Now() |
| 660 | cmd := exec.CommandContext(ctx, |
| 661 | "docker", "build", |
| 662 | "-t", imgName, |
| 663 | "-f", dockerfilePath, |
| 664 | "--build-arg", "GIT_USER_EMAIL="+gitUserEmail, |
| 665 | "--build-arg", "GIT_USER_NAME="+gitUserName, |
| 666 | ".", |
| 667 | ) |
| 668 | cmd.Dir = gitRoot |
| 669 | cmd.Stdout = stdout |
| 670 | cmd.Stderr = stderr |
| Josh Bleecher Snyder | df2d3dc | 2025-04-25 12:31:35 -0700 | [diff] [blame] | 671 | fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName) |
| Philip Zeyliger | e4fa0e3 | 2025-04-23 14:15:55 -0700 | [diff] [blame] | 672 | dockerfileContent, err := os.ReadFile(dockerfilePath) |
| 673 | if err != nil { |
| 674 | return "", fmt.Errorf("failed to read Dockerfile: %w", err) |
| 675 | } |
| Philip Zeyliger | 5d6af87 | 2025-04-23 19:48:34 -0700 | [diff] [blame] | 676 | fmt.Fprintf(stdout, "Dockerfile:\n%s\n", string(dockerfileContent)) |
| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame] | 677 | |
| 678 | err = run(ctx, "docker build", cmd) |
| 679 | if err != nil { |
| 680 | return "", fmt.Errorf("docker build failed: %v", err) |
| 681 | } |
| 682 | fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond)) |
| 683 | return imgName, nil |
| 684 | } |
| 685 | |
| 686 | func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) { |
| 687 | files, err := findDirDockerfiles(cwd) |
| 688 | if err != nil { |
| 689 | return nil, err |
| 690 | } |
| 691 | if len(files) > 0 { |
| 692 | return files, nil |
| 693 | } |
| 694 | |
| 695 | path := cwd |
| 696 | for path != gitRoot { |
| 697 | path = filepath.Dir(path) |
| 698 | files, err := findDirDockerfiles(path) |
| 699 | if err != nil { |
| 700 | return nil, err |
| 701 | } |
| 702 | if len(files) > 0 { |
| 703 | return files, nil |
| 704 | } |
| 705 | } |
| 706 | return files, nil |
| 707 | } |
| 708 | |
| 709 | // findDirDockerfiles finds all "Dockerfile*" files in a directory. |
| 710 | func findDirDockerfiles(root string) (res []string, err error) { |
| 711 | err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { |
| 712 | if err != nil { |
| 713 | return err |
| 714 | } |
| 715 | if info.IsDir() && root != path { |
| 716 | return filepath.SkipDir |
| 717 | } |
| 718 | name := strings.ToLower(info.Name()) |
| 719 | if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") { |
| 720 | res = append(res, path) |
| 721 | } |
| 722 | return nil |
| 723 | }) |
| 724 | if err != nil { |
| 725 | return nil, err |
| 726 | } |
| 727 | return res, nil |
| 728 | } |
| 729 | |
| 730 | func findGitRoot(ctx context.Context, path string) (string, error) { |
| 731 | cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir") |
| 732 | cmd.Dir = path |
| 733 | out, err := cmd.CombinedOutput() |
| 734 | if err != nil { |
| 735 | if strings.Contains(string(out), "not a git repository") { |
| 736 | return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo. |
| 737 | Consider one of the following options: |
| 738 | - cd to a different dir that is already part of a git repo first, or |
| 739 | - to create a new git repo from this directory (%s), run this command: |
| 740 | |
| 741 | git init . && git commit --allow-empty -m "initial commit" |
| 742 | |
| 743 | and try running sketch again. |
| 744 | `, path, path) |
| 745 | } |
| 746 | return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err) |
| 747 | } |
| 748 | gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path |
| 749 | absGitDir := filepath.Join(path, gitDir) |
| 750 | return filepath.Dir(absGitDir), err |
| 751 | } |
| 752 | |
| 753 | func OpenBrowser(ctx context.Context, url string) { |
| 754 | var cmd *exec.Cmd |
| 755 | switch runtime.GOOS { |
| 756 | case "darwin": |
| 757 | cmd = exec.CommandContext(ctx, "open", url) |
| 758 | case "windows": |
| 759 | cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url) |
| 760 | default: // Linux and other Unix-like systems |
| 761 | cmd = exec.CommandContext(ctx, "xdg-open", url) |
| 762 | } |
| 763 | if b, err := cmd.CombinedOutput(); err != nil { |
| 764 | fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b) |
| 765 | } |
| 766 | } |
| Philip Zeyliger | 5e227dd | 2025-04-21 15:55:29 -0700 | [diff] [blame] | 767 | |
| 768 | // moveFile is like Python's shutil.move, in that it tries a rename, and, if that fails, |
| 769 | // copies and deletes |
| 770 | func moveFile(src, dst string) error { |
| 771 | if err := os.Rename(src, dst); err == nil { |
| 772 | return nil |
| 773 | } |
| 774 | |
| 775 | stat, err := os.Stat(src) |
| 776 | if err != nil { |
| 777 | return err |
| 778 | } |
| 779 | |
| 780 | sourceFile, err := os.Open(src) |
| 781 | if err != nil { |
| 782 | return err |
| 783 | } |
| 784 | defer sourceFile.Close() |
| 785 | |
| 786 | destFile, err := os.Create(dst) |
| 787 | if err != nil { |
| 788 | return err |
| 789 | } |
| 790 | defer destFile.Close() |
| 791 | |
| 792 | _, err = io.Copy(destFile, sourceFile) |
| 793 | if err != nil { |
| 794 | return err |
| 795 | } |
| 796 | |
| 797 | sourceFile.Close() |
| 798 | destFile.Close() |
| 799 | |
| 800 | os.Chmod(dst, stat.Mode()) |
| 801 | |
| 802 | return os.Remove(src) |
| 803 | } |