Skip to content

Commit b3088b0

Browse files
committed
refac(printer) move AssumeYes logic into printer itself
1 parent 62b8c64 commit b3088b0

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

internal/cmd/root.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ func NewRootCmd(version, date string, p *print.Printer) *cobra.Command {
6262
DisableAutoGenTag: true,
6363
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
6464
p.Cmd = cmd
65-
p.Verbosity = print.Level(globalflags.Parse(p, cmd).Verbosity)
65+
globalFlags := globalflags.Parse(p, cmd)
66+
p.Verbosity = print.Level(globalFlags.Verbosity)
67+
p.AssumeYes = globalFlags.AssumeYes
6668

6769
argsString := print.BuildDebugStrFromSlice(os.Args)
6870
p.Debug(print.DebugLevel, "arguments: %s", argsString)
@@ -209,6 +211,7 @@ func Execute(version, date string) {
209211

210212
// We need to set the printer and verbosity here because the
211213
// PersistentPreRun is not called when the command is wrongly called
214+
// In this case Printer.AssumeYes isn't set either, but `false` as default is acceptable
212215
p.Cmd = cmd
213216
p.Verbosity = print.InfoLevel
214217

internal/pkg/print/print.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ var (
5151

5252
type Printer struct {
5353
Cmd *cobra.Command
54+
AssumeYes bool
5455
Verbosity Level
5556
}
5657

@@ -134,6 +135,10 @@ func (p *Printer) Error(msg string, args ...any) {
134135
// Returns nil only if the user (explicitly) answers positive.
135136
// Returns ErrAborted if the user answers negative.
136137
func (p *Printer) PromptForConfirmation(prompt string) error {
138+
if p.AssumeYes {
139+
p.Warn("Auto-confirming prompt: %q", prompt)
140+
return nil
141+
}
137142
question := fmt.Sprintf("%s [y/N] ", prompt)
138143
reader := bufio.NewReader(p.Cmd.InOrStdin())
139144
for i := 0; i < 3; i++ {
@@ -157,6 +162,10 @@ func (p *Printer) PromptForConfirmation(prompt string) error {
157162
//
158163
// Returns nil if the user presses Enter.
159164
func (p *Printer) PromptForEnter(prompt string) error {
165+
if p.AssumeYes {
166+
p.Warn("Auto-confirming prompt: %q", prompt)
167+
return nil
168+
}
160169
reader := bufio.NewReader(p.Cmd.InOrStdin())
161170
p.Cmd.PrintErr(prompt)
162171
_, err := reader.ReadString('\n')

0 commit comments

Comments
 (0)