-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathprint.go
More file actions
230 lines (199 loc) · 6.2 KB
/
print.go
File metadata and controls
230 lines (199 loc) · 6.2 KB
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
package print
import (
"bufio"
"errors"
"fmt"
"syscall"
"log/slog"
"os"
"os/exec"
"strings"
"github.com/fatih/color"
"github.com/lmittmann/tint"
"github.com/mattn/go-colorable"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/term"
)
type Level string
const (
DebugLevel Level = "debug"
InfoLevel Level = "info"
WarningLevel Level = "warning"
ErrorLevel Level = "error"
// Needed to avoid import cycle
// Originally defined in "internal/pkg/config/config.go"
outputFormatKey = "output-format"
JSONOutputFormat = "json"
PrettyOutputFormat = "pretty"
NoneOutputFormat = "none"
YAMLOutputFormat = "yaml"
)
var (
errAborted = errors.New("operation aborted")
WhiteBold = color.New(color.FgHiWhite, color.Bold).SprintFunc()
RedBold = color.New(color.FgHiRed, color.Bold).SprintFunc()
YellowBold = color.New(color.FgHiYellow, color.Bold).SprintFunc()
)
type Printer struct {
Cmd *cobra.Command
Verbosity Level
}
// Creates a new printer, including setting up the default logger.
func NewPrinter() *Printer {
w := os.Stderr
logger := slog.New(
tint.NewHandler(colorable.NewColorable(w), &tint.Options{AddSource: false, Level: slog.LevelDebug}),
)
slog.SetDefault(logger)
return &Printer{}
}
// Print an output using Printf to the defined output (falling back to Stderr if not set).
// If output format is set to none, it does nothing
func (p *Printer) Outputf(msg string, args ...any) {
outputFormat := viper.GetString(outputFormatKey)
if outputFormat == NoneOutputFormat {
return
}
p.Cmd.Printf(msg, args...)
}
// Print an output using Println to the defined output (falling back to Stderr if not set).
// If output format is set to none, it does nothing
func (p *Printer) Outputln(msg string) {
outputFormat := viper.GetString(outputFormatKey)
if outputFormat == NoneOutputFormat {
return
}
p.Cmd.Println(msg)
}
// Print a Debug level log through the "slog" package.
// If the verbosity level is not Debug, it does nothing
func (p *Printer) Debug(level Level, msg string, args ...any) {
if !p.IsVerbosityDebug() {
return
}
msg = fmt.Sprintf(msg, args...)
switch level {
case DebugLevel:
slog.Debug(msg)
case InfoLevel:
slog.Info(msg)
case WarningLevel:
slog.Warn(msg)
case ErrorLevel:
slog.Error(msg)
}
}
// Print an Info level output to the defined Err output (falling back to Stderr if not set).
// If the verbosity level is not Debug or Info, it does nothing.
func (p *Printer) Info(msg string, args ...any) {
if !p.IsVerbosityDebug() && !p.IsVerbosityInfo() {
return
}
p.Cmd.PrintErrf(msg, args...)
}
// Print a Warn level output to the defined Err output (falling back to Stderr if not set).
// If the verbosity level is not Debug, Info, or Warn, it does nothing.
func (p *Printer) Warn(msg string, args ...any) {
if !p.IsVerbosityDebug() && !p.IsVerbosityInfo() && !p.IsVerbosityWarning() {
return
}
warning := fmt.Sprintf(msg, args...)
p.Cmd.PrintErrf("%s %s", YellowBold("Warning:"), warning)
}
// Print an Error level output to the defined Err output (falling back to Stderr if not set).
func (p *Printer) Error(msg string, args ...any) {
err := fmt.Sprintf(msg, args...)
p.Cmd.PrintErrln(RedBold(p.Cmd.ErrPrefix()), err)
}
// Prompts the user for confirmation.
//
// Returns nil only if the user (explicitly) answers positive.
// Returns ErrAborted if the user answers negative.
func (p *Printer) PromptForConfirmation(prompt string) error {
question := fmt.Sprintf("%s [y/N] ", prompt)
reader := bufio.NewReader(p.Cmd.InOrStdin())
for i := 0; i < 3; i++ {
p.Cmd.PrintErr(question)
answer, err := reader.ReadString('\n')
if err != nil {
continue
}
answer = strings.ToLower(strings.TrimSpace(answer))
if answer == "y" || answer == "yes" {
return nil
}
if answer == "" || answer == "n" || answer == "no" {
return errAborted
}
}
return fmt.Errorf("max number of wrong inputs")
}
// Prompts the user for confirmation by pressing Enter.
//
// Returns nil if the user presses Enter.
func (p *Printer) PromptForEnter(prompt string) error {
reader := bufio.NewReader(p.Cmd.InOrStdin())
p.Cmd.PrintErr(prompt)
_, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("read user response: %w", err)
}
return nil
}
// Prompts the user for a password.
//
// Returns the password that was given, otherwise returns error
func (p *Printer) PromptForPassword(prompt string) (string, error) {
p.Cmd.PrintErr(prompt)
defer p.Outputln("")
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", fmt.Errorf("read password: %w", err)
}
return string(bytePassword), nil
}
// Shows the content in the command's stdout using the "less" command
// If output format is set to none, it does nothing
func (p *Printer) PagerDisplay(content string) error {
outputFormat := viper.GetString(outputFormatKey)
if outputFormat == NoneOutputFormat {
return nil
}
// less arguments
// -F: exits if the entire file fits on the first screen
// -S: disables line wrapping
// -w: highlight the first line after moving one full page down
// -R: interprets ANSI color and style sequences
// -K: exits if an interrupt character is typed
pagerCmd := exec.Command("less", "-F", "-S", "-w", "-R", "-K")
pager, pagerExists := os.LookupEnv("PAGER")
if pagerExists && pager != "nil" && pager != "" {
pagerCmd = exec.Command(pager) // #nosec G204
}
pagerCmd.Stdin = strings.NewReader(content)
pagerCmd.Stdout = p.Cmd.OutOrStdout()
p.Debug(DebugLevel, "using pager: %s", pagerCmd.Args[0])
err := pagerCmd.Run()
if err != nil {
p.Debug(ErrorLevel, "run pager command: %v", err)
p.Outputln(content)
}
return nil
}
// Returns True if the verbosity level is set to Debug, False otherwise.
func (p *Printer) IsVerbosityDebug() bool {
return p.Verbosity == DebugLevel
}
// Returns True if the verbosity level is set to Info, False otherwise.
func (p *Printer) IsVerbosityInfo() bool {
return p.Verbosity == InfoLevel
}
// Returns True if the verbosity level is set to Warning, False otherwise.
func (p *Printer) IsVerbosityWarning() bool {
return p.Verbosity == WarningLevel
}
// Returns True if the verbosity level is set to Error, False otherwise.
func (p *Printer) IsVerbosityError() bool {
return p.Verbosity == ErrorLevel
}