-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathprint.go
More file actions
317 lines (280 loc) · 8.39 KB
/
print.go
File metadata and controls
317 lines (280 loc) · 8.39 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
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
package print
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math"
"os"
"os/exec"
"strings"
"github.com/fatih/color"
"github.com/goccy/go-yaml"
"github.com/lmittmann/tint"
"github.com/mattn/go-colorable"
"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 {
AssumeYes bool
Verbosity Level
StdIn io.Reader
StdOut io.Writer
StdErr io.Writer
ErrPrefix string
}
// NewPrinter creates a new printer, including setting up the default logger.
func NewPrinter(stdIn io.Reader, stdOut, stdErr io.Writer) *Printer {
logW := stdErr
if f, ok := stdErr.(*os.File); ok {
logW = colorable.NewColorable(f)
}
logger := slog.New(
tint.NewHandler(logW, &tint.Options{AddSource: false, Level: slog.LevelDebug}),
)
slog.SetDefault(logger)
return &Printer{
StdIn: stdIn,
StdOut: stdOut,
StdErr: stdErr,
ErrPrefix: "Error:",
Verbosity: InfoLevel,
}
}
// 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
}
mustPrint(fmt.Fprintf(p.StdOut, 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
}
mustPrint(fmt.Fprintln(p.StdOut, 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
}
mustPrint(fmt.Fprintf(p.StdErr, 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...)
mustPrint(fmt.Fprintf(p.StdErr, "%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...)
mustPrint(fmt.Fprintln(p.StdErr, RedBold(p.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 {
if p.AssumeYes {
p.Warn("Auto-confirming prompt: %q\n", prompt)
return nil
}
question := fmt.Sprintf("%s [y/N] ", prompt)
reader := bufio.NewReader(p.StdIn)
for i := 0; i < 3; i++ {
mustPrint(fmt.Fprint(p.StdErr, 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 {
if p.AssumeYes {
p.Warn("Auto-confirming prompt: %q", prompt)
return nil
}
reader := bufio.NewReader(p.StdIn)
mustPrint(fmt.Fprint(p.StdErr, 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) {
mustPrint(fmt.Fprint(p.StdErr, prompt))
defer p.Outputln("")
if f, ok := p.StdIn.(*os.File); ok {
uint_fd := f.Fd()
if uint_fd > math.MaxInt {
return "", fmt.Errorf("uint_fd is too large")
}
fd := int(uint_fd)
if term.IsTerminal(fd) {
bytePassword, err := term.ReadPassword(fd)
if err != nil {
return "", fmt.Errorf("read password: %w", err)
}
return string(bytePassword), nil
}
}
// Fallback for non-terminal environments
reader := bufio.NewReader(p.StdIn)
pw, err := reader.ReadString('\n')
if err != nil {
return "", fmt.Errorf("read password from non-terminal: %w", err)
}
return pw[:len(pw)-1], nil // remove trailing newline
}
// 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.StdOut
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
}
// DebugInputModel prints the given input model in case verbosity level is set to Debug, does nothing otherwise
func (p *Printer) DebugInputModel(model any) {
if p.IsVerbosityDebug() {
modelStr, err := buildDebugStrFromInputModel(model)
if err != nil {
p.Debug(ErrorLevel, "convert model to string for debugging: %v", err)
} else {
p.Debug(DebugLevel, "parsed input values: %s", modelStr)
}
}
}
func (p *Printer) OutputResult(outputFormat string, output any, prettyOutputFunc func() error) error {
switch outputFormat {
case JSONOutputFormat:
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
err := encoder.Encode(output)
if err != nil {
return fmt.Errorf("marshal json: %w", err)
}
details := buffer.Bytes()
p.Outputln(string(details))
return nil
case YAMLOutputFormat:
details, err := yaml.MarshalWithOptions(output, yaml.IndentSequence(true), yaml.UseJSONMarshaler())
if err != nil {
return fmt.Errorf("marshal yaml: %w", err)
}
p.Outputln(string(details))
return nil
default:
return prettyOutputFunc()
}
}
func mustPrint(_ int, err error) {
if err != nil {
panic(err)
}
}