2021-01-23 20:29:22 +00:00
|
|
|
package term
|
|
|
|
|
|
|
|
import (
|
2022-01-10 13:28:14 +00:00
|
|
|
"fmt"
|
2021-01-23 20:29:22 +00:00
|
|
|
"os"
|
2021-02-25 19:46:19 +00:00
|
|
|
"strings"
|
2021-01-23 20:29:22 +00:00
|
|
|
|
2021-04-14 18:14:01 +00:00
|
|
|
survey "github.com/AlecAivazis/survey/v2"
|
2021-01-23 20:29:22 +00:00
|
|
|
"github.com/mattn/go-isatty"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Terminal offers utilities to interact with the terminal.
|
|
|
|
type Terminal struct {
|
2022-01-10 13:28:14 +00:00
|
|
|
NoInput bool
|
|
|
|
ForceInput string
|
2021-01-23 20:29:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func New() *Terminal {
|
|
|
|
return &Terminal{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsInteractive returns whether the app is attached to an interactive terminal
|
|
|
|
// and can prompt the user.
|
|
|
|
func (t *Terminal) IsInteractive() bool {
|
2021-02-24 20:49:56 +00:00
|
|
|
return !t.NoInput && t.IsTTY()
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsTTY returns whether the app is attached to an interactive terminal.
|
|
|
|
func (t *Terminal) IsTTY() bool {
|
|
|
|
return isatty.IsTerminal(os.Stdin.Fd())
|
2021-01-23 20:29:22 +00:00
|
|
|
}
|
2021-02-25 19:46:19 +00:00
|
|
|
|
|
|
|
// SupportsUTF8 returns whether the computer is configured to support UTF-8.
|
|
|
|
func (t *Terminal) SupportsUTF8() bool {
|
|
|
|
lang := strings.ToUpper(os.Getenv("LANG"))
|
|
|
|
lc := strings.ToUpper(os.Getenv("LC_ALL"))
|
|
|
|
return strings.Contains(lang, "UTF") || strings.Contains(lc, "UTF")
|
|
|
|
}
|
2021-04-14 18:14:01 +00:00
|
|
|
|
|
|
|
// Confirm is a shortcut to prompt a yes/no question to the user.
|
|
|
|
func (t *Terminal) Confirm(msg string, defaultAnswer bool) (confirmed, skipped bool) {
|
|
|
|
if !t.IsInteractive() {
|
2022-01-10 13:28:14 +00:00
|
|
|
switch strings.ToLower(t.ForceInput) {
|
|
|
|
case "y":
|
|
|
|
return t.forceConfirm(msg, true)
|
|
|
|
case "n":
|
|
|
|
return t.forceConfirm(msg, false)
|
|
|
|
default:
|
|
|
|
return defaultAnswer, true
|
|
|
|
}
|
2021-04-14 18:14:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
confirmed = false
|
|
|
|
prompt := &survey.Confirm{
|
|
|
|
Message: msg,
|
|
|
|
Default: defaultAnswer,
|
|
|
|
}
|
|
|
|
survey.AskOne(prompt, &confirmed)
|
|
|
|
return confirmed, false
|
|
|
|
}
|
2022-01-10 13:28:14 +00:00
|
|
|
|
|
|
|
func (t *Terminal) forceConfirm(msg string, answer bool) (confirmed, skipped bool) {
|
|
|
|
msg = "? " + msg + " ("
|
|
|
|
if answer {
|
|
|
|
msg += "Y/n"
|
|
|
|
} else {
|
|
|
|
msg += "y/N"
|
|
|
|
}
|
|
|
|
msg += ")"
|
|
|
|
fmt.Println(msg)
|
|
|
|
|
|
|
|
return answer, false
|
|
|
|
}
|