@@ -8,11 +8,13 @@ import (
8
8
"time"
9
9
10
10
"github.com/spf13/pflag"
11
- "go.coder.com/cli"
12
- "go.coder.com/flog"
13
11
"golang.org/x/crypto/ssh/terminal"
14
12
"golang.org/x/sys/unix"
15
13
"golang.org/x/time/rate"
14
+ "golang.org/x/xerrors"
15
+
16
+ "go.coder.com/cli"
17
+ "go.coder.com/flog"
16
18
17
19
client "cdr.dev/coder-cli/internal/entclient"
18
20
"cdr.dev/coder-cli/wush"
@@ -30,14 +32,20 @@ func (cmd *shellCmd) Spec() cli.CommandSpec {
30
32
}
31
33
}
32
34
33
- func enableTerminal (fd int ) {
34
- _ , err := terminal .MakeRaw (fd )
35
+ func enableTerminal (fd int ) ( restore func (), err error ) {
36
+ state , err := terminal .MakeRaw (fd )
35
37
if err != nil {
36
- flog . Fatal ("make raw term: %v " , err )
38
+ return restore , xerrors . Errorf ("make raw term: %w " , err )
37
39
}
40
+ return func () {
41
+ err := terminal .Restore (fd , state )
42
+ if err != nil {
43
+ flog .Error ("restore term state: %v" , err )
44
+ }
45
+ }, nil
38
46
}
39
47
40
- func ( cmd * shellCmd ) sendResizeEvents (termfd int , client * wush.Client ) {
48
+ func sendResizeEvents (termfd int , client * wush.Client ) {
41
49
sigs := make (chan os.Signal , 16 )
42
50
signal .Notify (sigs , unix .SIGWINCH )
43
51
@@ -83,6 +91,14 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
83
91
args = []string {"-c" , "exec $(getent passwd $(whoami) | awk -F: '{ print $7 }')" }
84
92
}
85
93
94
+ exitCode , err := runCommand (envName , command , args )
95
+ if err != nil {
96
+ flog .Fatal ("run command: %v" , err )
97
+ }
98
+ os .Exit (exitCode )
99
+ }
100
+
101
+ func runCommand (envName string , command string , args []string ) (int , error ) {
86
102
var (
87
103
entClient = requireAuth ()
88
104
env = findEnv (entClient , envName )
@@ -92,7 +108,11 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
92
108
93
109
tty := terminal .IsTerminal (termfd )
94
110
if tty {
95
- enableTerminal (termfd )
111
+ restore , err := enableTerminal (termfd )
112
+ if err != nil {
113
+ return - 1 , err
114
+ }
115
+ defer restore ()
96
116
}
97
117
98
118
conn , err := entClient .DialWush (
@@ -102,16 +122,16 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
102
122
Stdin : true ,
103
123
}, command , args ... )
104
124
if err != nil {
105
- flog . Fatal ( "dial wush: %v" , err )
125
+ return - 1 , err
106
126
}
107
127
ctx := context .Background ()
108
128
109
129
wc := wush .NewClient (ctx , conn )
110
130
if tty {
111
- go cmd . sendResizeEvents (termfd , wc )
131
+ go sendResizeEvents (termfd , wc )
112
132
}
113
133
114
- go func (){
134
+ go func () {
115
135
defer wc .Stdin .Close ()
116
136
io .Copy (wc .Stdin , os .Stdin )
117
137
}()
@@ -120,7 +140,8 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
120
140
121
141
exitCode , err := wc .Wait ()
122
142
if err != nil {
123
- flog . Fatal ( "wush error: %v" , err )
143
+ return - 1 , err
124
144
}
125
- os .Exit (int (exitCode ))
145
+
146
+ return int (exitCode ), nil
126
147
}
0 commit comments