gum/confirm/command.go

52 lines
1.2 KiB
Go
Raw Normal View History

2022-07-26 21:43:26 +02:00
package confirm
import (
2022-08-05 00:45:19 +02:00
"fmt"
2022-07-26 21:43:26 +02:00
"os"
2022-08-03 18:28:02 +02:00
"github.com/alecthomas/kong"
2022-07-26 21:43:26 +02:00
tea "github.com/charmbracelet/bubbletea"
2022-08-05 00:45:19 +02:00
2022-08-03 18:28:02 +02:00
"github.com/charmbracelet/gum/style"
2022-07-26 21:43:26 +02:00
)
// Aborted is the exit code when the user aborts the confirmation.
const Aborted = 130
2022-07-26 21:43:26 +02:00
// Run provides a shell script interface for prompting a user to confirm an
// action with an affirmative or negative answer.
func (o Options) Run() error {
m, err := tea.NewProgram(model{
affirmative: o.Affirmative,
negative: o.Negative,
confirmation: o.Default,
defaultSelection: o.Default,
timeout: o.Timeout,
hasTimeout: o.Timeout > 0,
prompt: o.Prompt,
selectedStyle: o.SelectedStyle.ToLipgloss(),
unselectedStyle: o.UnselectedStyle.ToLipgloss(),
promptStyle: o.PromptStyle.ToLipgloss(),
2022-10-18 02:23:59 +02:00
}, tea.WithOutput(os.Stderr)).Run()
2022-07-26 21:43:26 +02:00
if err != nil {
2022-08-05 00:45:19 +02:00
return fmt.Errorf("unable to run confirm: %w", err)
2022-07-26 21:43:26 +02:00
}
2022-12-13 21:46:43 +01:00
if m.(model).aborted {
os.Exit(Aborted)
2022-12-13 21:46:43 +01:00
} else if m.(model).confirmation {
os.Exit(0)
} else {
os.Exit(1)
}
2022-07-26 21:43:26 +02:00
return nil
}
2022-08-03 18:28:02 +02:00
// BeforeReset hook. Used to unclutter style flags.
func (o Options) BeforeReset(ctx *kong.Context) error {
2022-08-05 00:45:19 +02:00
style.HideFlags(ctx)
return nil
2022-08-03 18:28:02 +02:00
}