Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Commit d29f7f2

Browse files
committed
Restore term state on exit
1 parent 209ec24 commit d29f7f2

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

cmd/coder/shell.go

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@ import (
88
"time"
99

1010
"github.com/spf13/pflag"
11-
"go.coder.com/cli"
12-
"go.coder.com/flog"
1311
"golang.org/x/crypto/ssh/terminal"
1412
"golang.org/x/sys/unix"
1513
"golang.org/x/time/rate"
1614

15+
"go.coder.com/cli"
16+
"go.coder.com/flog"
17+
1718
client "cdr.dev/coder-cli/internal/entclient"
1819
"cdr.dev/coder-cli/wush"
1920
)
@@ -30,14 +31,20 @@ func (cmd *shellCmd) Spec() cli.CommandSpec {
3031
}
3132
}
3233

33-
func enableTerminal(fd int) {
34-
_, err := terminal.MakeRaw(fd)
34+
func enableTerminal(fd int) (restore func()) {
35+
state, err := terminal.MakeRaw(fd)
3536
if err != nil {
3637
flog.Fatal("make raw term: %v", err)
3738
}
39+
return func() {
40+
err := terminal.Restore(fd, state)
41+
if err != nil {
42+
flog.Fatal("restore term state: %v", err)
43+
}
44+
}
3845
}
3946

40-
func (cmd *shellCmd) sendResizeEvents(termfd int, client *wush.Client) {
47+
func sendResizeEvents(termfd int, client *wush.Client) {
4148
sigs := make(chan os.Signal, 16)
4249
signal.Notify(sigs, unix.SIGWINCH)
4350

@@ -83,6 +90,11 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
8390
args = []string{"-c", "exec $(getent passwd $(whoami) | awk -F: '{ print $7 }')"}
8491
}
8592

93+
exitCode := runCommand(envName, command, args)
94+
os.Exit(exitCode)
95+
}
96+
97+
func runCommand(envName string, command string, args []string) int {
8698
var (
8799
entClient = requireAuth()
88100
env = findEnv(entClient, envName)
@@ -92,7 +104,8 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
92104

93105
tty := terminal.IsTerminal(termfd)
94106
if tty {
95-
enableTerminal(termfd)
107+
restore := enableTerminal(termfd)
108+
defer restore()
96109
}
97110

98111
conn, err := entClient.DialWush(
@@ -108,10 +121,10 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
108121

109122
wc := wush.NewClient(ctx, conn)
110123
if tty {
111-
go cmd.sendResizeEvents(termfd, wc)
124+
go sendResizeEvents(termfd, wc)
112125
}
113126

114-
go func(){
127+
go func() {
115128
defer wc.Stdin.Close()
116129
io.Copy(wc.Stdin, os.Stdin)
117130
}()
@@ -122,5 +135,6 @@ func (cmd *shellCmd) Run(fl *pflag.FlagSet) {
122135
if err != nil {
123136
flog.Fatal("wush error: %v", err)
124137
}
125-
os.Exit(int(exitCode))
138+
139+
return int(exitCode)
126140
}

0 commit comments

Comments
 (0)