|
| 1 | +package sync |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "io/ioutil" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "cdr.dev/coder-cli/coder-sdk" |
| 13 | + "cdr.dev/wsep" |
| 14 | + "golang.org/x/xerrors" |
| 15 | + "nhooyr.io/websocket" |
| 16 | +) |
| 17 | + |
| 18 | +// SingleFile copies the given file into the remote dir or remote path of the given coder.Environment. |
| 19 | +func SingleFile(ctx context.Context, local, remoteDir string, env *coder.Environment, client *coder.Client) error { |
| 20 | + conn, err := client.DialWsep(ctx, env) |
| 21 | + if err != nil { |
| 22 | + return xerrors.Errorf("dial remote execer: %w", err) |
| 23 | + } |
| 24 | + defer func() { _ = conn.Close(websocket.StatusNormalClosure, "normal closure") }() |
| 25 | + |
| 26 | + if strings.HasSuffix(remoteDir, string(filepath.Separator)) { |
| 27 | + remoteDir += filepath.Base(local) |
| 28 | + } |
| 29 | + |
| 30 | + execer := wsep.RemoteExecer(conn) |
| 31 | + cmd := fmt.Sprintf(`[ -d %s ] && cat > %s/%s || cat > %s`, remoteDir, remoteDir, filepath.Base(local), remoteDir) |
| 32 | + process, err := execer.Start(ctx, wsep.Command{ |
| 33 | + Command: "sh", |
| 34 | + Args: []string{"-c", cmd}, |
| 35 | + Stdin: true, |
| 36 | + }) |
| 37 | + if err != nil { |
| 38 | + return xerrors.Errorf("start sync command: %w", err) |
| 39 | + } |
| 40 | + |
| 41 | + sourceFile, err := os.Open(local) |
| 42 | + if err != nil { |
| 43 | + return xerrors.Errorf("open source file: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + go func() { _, _ = io.Copy(ioutil.Discard, process.Stdout()) }() |
| 47 | + go func() { _, _ = io.Copy(ioutil.Discard, process.Stderr()) }() |
| 48 | + go func() { |
| 49 | + stdin := process.Stdin() |
| 50 | + defer stdin.Close() |
| 51 | + _, _ = io.Copy(stdin, sourceFile) |
| 52 | + }() |
| 53 | + |
| 54 | + if err := process.Wait(); err != nil { |
| 55 | + return xerrors.Errorf("copy process: %w", err) |
| 56 | + } |
| 57 | + return nil |
| 58 | +} |
0 commit comments