tailscale/util/prompt/prompt.go
James Tucker b9cdef18c0 util/prompt: add a default and take default in non-interactive cases
The Tailscale CLI is the primary configuration interface and as such it
is used in scripts, container setups, and many other places that do not
have a terminal available and should not be made to respond to prompts.

The default is set to false where the "risky" API is being used by the
CLI and true otherwise, this means that the `--yes` flags are only
required under interactive runs and scripts do not need to be concerned
with prompts or extra flags.

Updates #19445

Signed-off-by: James Tucker <james@tailscale.com>
2025-09-30 10:27:07 -07:00

40 lines
857 B
Go

// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package prompt provides a simple way to prompt the user for input.
package prompt
import (
"fmt"
"os"
"strings"
"github.com/mattn/go-isatty"
)
// YesNo takes a question and prompts the user to answer the
// question with a yes or no. It appends a [y/n] to the message.
//
// If there is no TTY on both Stdin and Stdout, assume that we're in a script
// and return the dflt result.
func YesNo(msg string, dflt bool) bool {
if !(isatty.IsTerminal(os.Stdin.Fd()) && isatty.IsTerminal(os.Stdout.Fd())) {
return dflt
}
if dflt {
fmt.Print(msg + " [Y/n] ")
} else {
fmt.Print(msg + " [y/N] ")
}
var resp string
fmt.Scanln(&resp)
resp = strings.ToLower(resp)
switch resp {
case "y", "yes", "sure":
return true
case "":
return dflt
}
return false
}