yay/pkg/text/text.go

101 lines
2.1 KiB
Go
Raw Normal View History

2020-07-10 02:36:45 +02:00
package text
import (
2020-07-11 00:48:30 +02:00
"fmt"
"io"
2020-07-10 02:36:45 +02:00
"strings"
"unicode"
"unicode/utf8"
2020-07-11 00:48:30 +02:00
"github.com/leonelquinteros/gotext"
2020-07-10 02:36:45 +02:00
)
const (
yDefault = "y"
nDefault = "n"
)
2021-08-11 20:13:28 +02:00
// SplitDBFromName split apart db/package to db and package.
2020-07-10 02:36:45 +02:00
func SplitDBFromName(pkg string) (db, name string) {
split := strings.SplitN(pkg, "/", 2)
if len(split) == 2 {
return split[0], split[1]
}
2021-08-11 20:13:28 +02:00
2020-07-10 02:36:45 +02:00
return "", split[0]
}
// LessRunes compares two rune values, and returns true if the first argument is lexicographicaly smaller.
func LessRunes(iRunes, jRunes []rune) bool {
max := len(iRunes)
if max > len(jRunes) {
max = len(jRunes)
}
for idx := 0; idx < max; idx++ {
ir := iRunes[idx]
jr := jRunes[idx]
lir := unicode.ToLower(ir)
ljr := unicode.ToLower(jr)
if lir != ljr {
return lir < ljr
}
// the lowercase runes are the same, so compare the original
if ir != jr {
return ir < jr
}
}
return len(iRunes) < len(jRunes)
}
2020-07-11 00:48:30 +02:00
// ContinueTask prompts if user wants to continue task.
// If NoConfirm is set the action will continue without user input.
func ContinueTask(input io.Reader, s string, preset, noConfirm bool) bool {
2020-07-11 00:48:30 +02:00
if noConfirm {
return preset
2020-07-11 00:48:30 +02:00
}
2021-08-11 20:13:28 +02:00
var (
response string
postFix string
n string
y string
2021-08-11 20:13:28 +02:00
yes = gotext.Get("yes")
no = gotext.Get("no")
)
2020-07-11 00:48:30 +02:00
// Only use localized "y" and "n" if they are latin characters.
if nRune, _ := utf8.DecodeRuneInString(no); unicode.Is(unicode.Latin, nRune) {
n = string(nRune)
2020-07-11 00:48:30 +02:00
} else {
n = nDefault
}
if yRune, _ := utf8.DecodeRuneInString(yes); unicode.Is(unicode.Latin, yRune) {
y = string(yRune)
} else {
y = yDefault
}
if preset { // If default behavior is true, use y as default.
postFix = fmt.Sprintf(" [%s/%s] ", strings.ToUpper(y), n)
} else { // If default behavior is anything else, use n as default.
2020-07-11 00:48:30 +02:00
postFix = fmt.Sprintf(" [%s/%s] ", y, strings.ToUpper(n))
}
OperationInfo(Bold(s), Bold(postFix))
2020-07-11 00:48:30 +02:00
if _, err := fmt.Fscanln(input, &response); err != nil {
return preset
2020-07-11 00:48:30 +02:00
}
return strings.EqualFold(response, yes) ||
strings.EqualFold(response, y) ||
(!strings.EqualFold(yDefault, n) && strings.EqualFold(response, yDefault))
2020-07-11 00:48:30 +02:00
}