Skip to content

Commit

Permalink
feat(windows): ensure output is utf16 wide chars when not a tty
Browse files Browse the repository at this point in the history
Otherwise, the output is gibberish invalid encoded utf16. When using
windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING, the output gets converted
automatically by Windows Console API. When output is not a terminal, we
need to do that ourselves.
  • Loading branch information
aymanbagabas committed Jul 18, 2024
1 parent 80b0d90 commit ca07f34
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/muesli/cancelreader v0.2.2
golang.org/x/sync v0.7.0
golang.org/x/sys v0.22.0
golang.org/x/text v0.6.0
)

require (
Expand All @@ -19,5 +20,4 @@ require (
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/text v0.3.8 // indirect
)
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
7 changes: 7 additions & 0 deletions tty_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (

"github.com/charmbracelet/x/term"
"golang.org/x/sys/windows"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)

func (p *Program) initInput() (err error) {
Expand Down Expand Up @@ -49,6 +51,11 @@ func (p *Program) initInput() (err error) {
if err := windows.SetConsoleMode(windows.Handle(p.ttyOutput.Fd()), mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil {
return fmt.Errorf("error setting console mode: %w", err)
}
} else {
// If we're not running in a terminal, we need to encode output as UTF-16
// to avoid issues with Windows' default wide character encoding.
encoder := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewEncoder()
p.output = transform.NewWriter(p.output, encoder)
}

return
Expand Down

0 comments on commit ca07f34

Please sign in to comment.