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