-
Notifications
You must be signed in to change notification settings - Fork 64
/
iostreams.go
507 lines (420 loc) · 11 KB
/
iostreams.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2019 GitHub Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package iostreams
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"time"
"github.com/briandowns/spinner"
ghTerm "github.com/cli/go-gh/pkg/term"
"github.com/cli/safeexec"
"github.com/google/shlex"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
)
const DefaultWidth = 80
// ErrClosedPagerPipe is the error returned when writing to a pager that has been closed.
type ErrClosedPagerPipe struct {
error
}
type fileWriter interface {
io.Writer
Fd() uintptr
}
type fileReader interface {
io.ReadCloser
Fd() uintptr
}
type Terminal interface {
IsTerminalOutput() bool
IsColorEnabled() bool
Is256ColorSupported() bool
IsTrueColorSupported() bool
Theme() string
Size() (int, int, error)
}
type IOStreams struct {
term Terminal
In fileReader
Out fileWriter
ErrOut io.Writer
terminalTheme string
progressIndicatorEnabled bool
progressIndicator *spinner.Spinner
progressIndicatorMu sync.Mutex
alternateScreenBufferEnabled bool
alternateScreenBufferActive bool
alternateScreenBufferMu sync.Mutex
stdinTTYOverride bool
stdinIsTTY bool
stdoutTTYOverride bool
stdoutIsTTY bool
stderrTTYOverride bool
stderrIsTTY bool
colorOverride bool
colorEnabled bool
pagerCommand string
pagerProcess *os.Process
neverPrompt bool
TempFileOverride *os.File
}
func (s *IOStreams) ColorEnabled() bool {
if s.colorOverride {
return s.colorEnabled
}
return s.term.IsColorEnabled()
}
func (s *IOStreams) ColorSupport256() bool {
if s.colorOverride {
return s.colorEnabled
}
return s.term.Is256ColorSupported()
}
func (s *IOStreams) HasTrueColor() bool {
if s.colorOverride {
return s.colorEnabled
}
return s.term.IsTrueColorSupported()
}
// DetectTerminalTheme is a utility to call before starting the output pager so that the terminal background
// can be reliably detected.
func (s *IOStreams) DetectTerminalTheme() {
if !s.ColorEnabled() || s.pagerProcess != nil {
s.terminalTheme = "none"
return
}
style := os.Getenv("GLAMOUR_STYLE")
if style != "" && style != "auto" {
// ensure GLAMOUR_STYLE takes precedence over "light" and "dark" themes
s.terminalTheme = "none"
return
}
s.terminalTheme = s.term.Theme()
}
// TerminalTheme returns "light", "dark", or "none" depending on the background color of the terminal.
func (s *IOStreams) TerminalTheme() string {
if s.terminalTheme == "" {
s.DetectTerminalTheme()
}
return s.terminalTheme
}
func (s *IOStreams) SetColorEnabled(colorEnabled bool) {
s.colorOverride = true
s.colorEnabled = colorEnabled
}
func (s *IOStreams) SetOut(out fileWriter) {
s.Out = out
}
func (s *IOStreams) SetIn(in fileReader) {
s.In = in
}
func (s *IOStreams) SetStdinTTY(isTTY bool) {
s.stdinTTYOverride = true
s.stdinIsTTY = isTTY
}
func (s *IOStreams) IsStdinTTY() bool {
if s.stdinTTYOverride {
return s.stdinIsTTY
}
if stdin, ok := s.In.(*os.File); ok {
return isTerminal(stdin)
}
return false
}
func (s *IOStreams) SetStdoutTTY(isTTY bool) {
s.stdoutTTYOverride = true
s.stdoutIsTTY = isTTY
}
func (s *IOStreams) IsStdoutTTY() bool {
if s.stdoutTTYOverride {
return s.stdoutIsTTY
}
// support KRAFTKIT_FORCE_TTY
if s.term.IsTerminalOutput() {
return true
}
stdout, ok := s.Out.(*os.File)
return ok && isCygwinTerminal(stdout.Fd())
}
func (s *IOStreams) SetStderrTTY(isTTY bool) {
s.stderrTTYOverride = true
s.stderrIsTTY = isTTY
}
func (s *IOStreams) IsStderrTTY() bool {
if s.stderrTTYOverride {
return s.stderrIsTTY
}
if stderr, ok := s.ErrOut.(*os.File); ok {
return isTerminal(stderr)
}
return false
}
func (s *IOStreams) SetPager(cmd string) {
s.pagerCommand = cmd
}
func (s *IOStreams) GetPager() string {
return s.pagerCommand
}
func (s *IOStreams) StartPager() error {
if s.pagerCommand == "" || s.pagerCommand == "cat" || !s.IsStdoutTTY() {
return nil
}
pagerArgs, err := shlex.Split(s.pagerCommand)
if err != nil {
return err
}
pagerEnv := os.Environ()
for i := len(pagerEnv) - 1; i >= 0; i-- {
if strings.HasPrefix(pagerEnv[i], "PAGER=") {
pagerEnv = append(pagerEnv[0:i], pagerEnv[i+1:]...)
}
}
if _, ok := os.LookupEnv("LESS"); !ok {
pagerEnv = append(pagerEnv, "LESS=FRX")
}
if _, ok := os.LookupEnv("LV"); !ok {
pagerEnv = append(pagerEnv, "LV=-c")
}
pagerExe, err := safeexec.LookPath(pagerArgs[0])
if err != nil {
return err
}
pagerCmd := exec.Command(pagerExe, pagerArgs[1:]...)
pagerCmd.Env = pagerEnv
pagerCmd.Stdout = s.Out
pagerCmd.Stderr = s.ErrOut
pagedOut, err := pagerCmd.StdinPipe()
if err != nil {
return err
}
s.Out = &fdWriteCloser{
fd: s.Out.Fd(),
WriteCloser: &pagerWriter{pagedOut},
}
err = pagerCmd.Start()
if err != nil {
return err
}
s.pagerProcess = pagerCmd.Process
return nil
}
func (s *IOStreams) StopPager() {
if s.pagerProcess == nil {
return
}
// if a pager was started, we're guaranteed to have a WriteCloser
_ = s.Out.(io.WriteCloser).Close()
_, _ = s.pagerProcess.Wait()
s.pagerProcess = nil
}
func (s *IOStreams) CanPrompt() bool {
if s.neverPrompt {
return false
}
return s.IsStdinTTY() && s.IsStdoutTTY()
}
func (s *IOStreams) GetNeverPrompt() bool {
return s.neverPrompt
}
func (s *IOStreams) SetNeverPrompt(v bool) {
s.neverPrompt = v
}
func (s *IOStreams) StartProgressIndicator() {
s.StartProgressIndicatorWithLabel("")
}
func (s *IOStreams) StartProgressIndicatorWithLabel(label string) {
if !s.progressIndicatorEnabled {
return
}
s.progressIndicatorMu.Lock()
defer s.progressIndicatorMu.Unlock()
if s.progressIndicator != nil {
if label == "" {
s.progressIndicator.Prefix = ""
} else {
s.progressIndicator.Prefix = label + " "
}
return
}
// https://github.com/briandowns/spinner#available-character-sets
dotStyle := spinner.CharSets[11]
sp := spinner.New(dotStyle, 120*time.Millisecond, spinner.WithWriter(s.ErrOut), spinner.WithColor("fgCyan"))
if label != "" {
sp.Prefix = label + " "
}
sp.Start()
s.progressIndicator = sp
}
func (s *IOStreams) StopProgressIndicator() {
s.progressIndicatorMu.Lock()
defer s.progressIndicatorMu.Unlock()
if s.progressIndicator == nil {
return
}
s.progressIndicator.Stop()
s.progressIndicator = nil
}
func (s *IOStreams) StartAlternateScreenBuffer() {
if s.alternateScreenBufferEnabled {
s.alternateScreenBufferMu.Lock()
defer s.alternateScreenBufferMu.Unlock()
if _, err := fmt.Fprint(s.Out, "\x1b[?1049h"); err == nil {
s.alternateScreenBufferActive = true
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
<-ch
s.StopAlternateScreenBuffer()
os.Exit(1)
}()
}
}
}
func (s *IOStreams) StopAlternateScreenBuffer() {
s.alternateScreenBufferMu.Lock()
defer s.alternateScreenBufferMu.Unlock()
if s.alternateScreenBufferActive {
fmt.Fprint(s.Out, "\x1b[?1049l")
s.alternateScreenBufferActive = false
}
}
func (s *IOStreams) SetAlternateScreenBufferEnabled(enabled bool) {
s.alternateScreenBufferEnabled = enabled
}
func (s *IOStreams) RefreshScreen() {
if s.IsStdoutTTY() {
// Move cursor to 0,0
fmt.Fprint(s.Out, "\x1b[0;0H")
// Clear from cursor to bottom of screen
fmt.Fprint(s.Out, "\x1b[J")
}
}
// TerminalWidth returns the width of the terminal that controls the process
func (s *IOStreams) TerminalWidth() int {
w, _, err := s.term.Size()
if err == nil && w > 0 {
return w
}
return DefaultWidth
}
func (s *IOStreams) ColorScheme() *ColorScheme {
return NewColorScheme(s.ColorEnabled(), s.ColorSupport256(), s.HasTrueColor())
}
func (s *IOStreams) ReadUserFile(fn string) ([]byte, error) {
var r io.ReadCloser
if fn == "-" {
r = s.In
} else {
var err error
r, err = os.Open(fn)
if err != nil {
return nil, err
}
}
defer r.Close()
return io.ReadAll(r)
}
func (s *IOStreams) TempFile(dir, pattern string) (*os.File, error) {
if s.TempFileOverride != nil {
return s.TempFileOverride, nil
}
return os.CreateTemp(dir, pattern)
}
func System() *IOStreams {
terminal := ghTerm.FromEnv()
var stdout fileWriter = os.Stdout
// On Windows with no virtual terminal processing support, translate ANSI escape
// sequences to console syscalls
if colorableStdout := colorable.NewColorable(os.Stdout); colorableStdout != os.Stdout {
// ensure that the file descriptor of the original stdout is preserved
stdout = &fdWriter{
fd: os.Stdout.Fd(),
Writer: colorableStdout,
}
}
io := &IOStreams{
In: os.Stdin,
Out: stdout,
ErrOut: colorable.NewColorable(os.Stderr),
pagerCommand: os.Getenv("PAGER"),
term: &terminal,
}
stdoutIsTTY := io.IsStdoutTTY()
stderrIsTTY := io.IsStderrTTY()
if stdoutIsTTY && stderrIsTTY {
io.progressIndicatorEnabled = true
}
return io
}
func isTerminal(f *os.File) bool {
return ghTerm.IsTerminal(f) || isCygwinTerminal(f.Fd())
}
func isCygwinTerminal(fd uintptr) bool {
return isatty.IsCygwinTerminal(fd)
}
// pagerWriter implements a WriteCloser that wraps all EPIPE errors in an ErrClosedPagerPipe type.
type pagerWriter struct {
io.WriteCloser
}
func (w *pagerWriter) Write(d []byte) (int, error) {
n, err := w.WriteCloser.Write(d)
if err != nil && (errors.Is(err, io.ErrClosedPipe) || isEpipeError(err)) {
return n, &ErrClosedPagerPipe{err}
}
return n, err
}
// fdWriter represents a wrapped stdout Writer that preserves the original file descriptor
type fdWriter struct {
io.Writer
fd uintptr
}
func (w *fdWriter) Fd() uintptr {
return w.fd
}
// fdWriteCloser represents a wrapped stdout Writer that preserves the original file descriptor
type fdWriteCloser struct {
io.WriteCloser
fd uintptr
}
func (w *fdWriteCloser) Fd() uintptr {
return w.fd
}
// fdWriter represents a wrapped stdin ReadCloser that preserves the original file descriptor
type fdReader struct {
io.ReadCloser
fd uintptr
}
func (r *fdReader) Fd() uintptr {
return r.fd
}
func NewNoTTYWriter(w io.WriteCloser) *fdWriter {
return &fdWriter{w, 0}
}
func NewNoTTYReader(r io.ReadCloser) *fdReader {
return &fdReader{r, 0}
}