...
Source file src/cmd/pprof/readlineui.go
1
2
3
4
5
6
7
8
9
10
11
12 package main
13
14 import (
15 "fmt"
16 "io"
17 "os"
18 "strings"
19
20 "github.com/google/pprof/driver"
21 "golang.org/x/crypto/ssh/terminal"
22 )
23
24 func init() {
25 newUI = newReadlineUI
26 }
27
28
29
30
31
32 type readlineUI struct {
33 term *terminal.Terminal
34 }
35
36 func newReadlineUI() driver.UI {
37
38 if v := strings.ToLower(os.Getenv("TERM")); v == "" || v == "dumb" {
39 return nil
40 }
41
42
43 oldState, err := terminal.MakeRaw(0)
44 if err != nil {
45 return nil
46 }
47 terminal.Restore(0, oldState)
48
49 rw := struct {
50 io.Reader
51 io.Writer
52 }{os.Stdin, os.Stderr}
53 return &readlineUI{term: terminal.NewTerminal(rw, "")}
54 }
55
56
57
58 func (r *readlineUI) ReadLine(prompt string) (string, error) {
59 r.term.SetPrompt(prompt)
60
61
62
63 oldState, _ := terminal.MakeRaw(0)
64 defer terminal.Restore(0, oldState)
65
66 s, err := r.term.ReadLine()
67 return s, err
68 }
69
70
71
72
73
74 func (r *readlineUI) Print(args ...interface{}) {
75 r.print(false, args...)
76 }
77
78
79
80
81 func (r *readlineUI) PrintErr(args ...interface{}) {
82 r.print(true, args...)
83 }
84
85 func (r *readlineUI) print(withColor bool, args ...interface{}) {
86 text := fmt.Sprint(args...)
87 if !strings.HasSuffix(text, "\n") {
88 text += "\n"
89 }
90 if withColor {
91 text = colorize(text)
92 }
93 fmt.Fprint(r.term, text)
94 }
95
96
97 func colorize(msg string) string {
98 const red = 31
99 var colorEscape = fmt.Sprintf("\033[0;%dm", red)
100 var colorResetEscape = "\033[0m"
101 return colorEscape + msg + colorResetEscape
102 }
103
104
105
106 func (r *readlineUI) IsTerminal() bool {
107 const stdout = 1
108 return terminal.IsTerminal(stdout)
109 }
110
111
112 func (r *readlineUI) WantBrowser() bool {
113 return r.IsTerminal()
114 }
115
116
117
118 func (r *readlineUI) SetAutoComplete(complete func(string) string) {
119
120 }
121
View as plain text