| 47 | } |
| 48 | |
| 49 | func (cl *Client) run(ses *ssh.Session, sio *exec.StdIOState, start, output bool, cmd string, args ...string) (string, error) { |
| 50 | // todo: env is established on connection! |
| 51 | // for k, v := range cl.Env { |
| 52 | // ses.Env = append(ses.Env, k+"="+v) |
| 53 | // } |
| 54 | var err error |
| 55 | out := "" |
| 56 | ses.Stderr = sio.Err // note: no need to save previous b/c not retained |
| 57 | ses.Stdout = sio.Out |
| 58 | if cl.Echo != nil { |
| 59 | cl.PrintCmd(cmd+" "+strings.Join(args, " "), err) |
| 60 | } |
| 61 | if exec.IsPipe(sio.In) { |
| 62 | ses.Stdin = sio.In |
| 63 | } |
| 64 | |
| 65 | cdto := "" |
| 66 | cmds := cmd + " " + strings.Join(args, " ") |
| 67 | if cl.Dir != "" { |
| 68 | if cmd == "cd" { |
| 69 | if len(args) > 0 { |
| 70 | cdto = args[0] |
| 71 | } else { |
| 72 | cdto = cl.HomeDir |
| 73 | } |
| 74 | } |
| 75 | cmds = `cd '` + cl.Dir + `'; ` + cmds |
| 76 | } |
| 77 | |
| 78 | if !cl.PrintOnly { |
| 79 | switch { |
| 80 | case start: |
| 81 | err = ses.Start(cmds) |
| 82 | go func() { |
| 83 | ses.Wait() |
| 84 | sio.PopToStart() |
| 85 | }() |
| 86 | case output: |
| 87 | buf := &bytes.Buffer{} |
| 88 | ses.Stdout = buf |
| 89 | err = ses.Run(cmds) |
| 90 | if sio.Out != nil { |
| 91 | sio.Out.Write(buf.Bytes()) |
| 92 | } |
| 93 | out = strings.TrimSuffix(buf.String(), "\n") |
| 94 | default: |
| 95 | err = ses.Run(cmds) |
| 96 | } |
| 97 | |
| 98 | // we must call InitColor after calling a system command |
| 99 | // TODO(kai): maybe figure out a better solution to this |
| 100 | // or expand this list |
| 101 | if cmd == "cp" || cmd == "ls" || cmd == "mv" { |
| 102 | logx.InitColor() |
| 103 | } |
| 104 | |
| 105 | if cdto != "" { |
| 106 | if filepath.IsAbs(cdto) { |