dsnet/util.go

68 lines
1.2 KiB
Go
Raw Normal View History

2020-03-02 00:48:02 +01:00
package dsnet
2020-03-02 03:16:53 +01:00
import (
"bufio"
"fmt"
2020-03-02 03:54:43 +01:00
"os"
"strings"
2020-03-02 03:16:53 +01:00
)
func check(e error, optMsg ...string) {
2020-03-02 03:54:43 +01:00
if e != nil {
2020-10-24 21:51:03 +02:00
if len(optMsg) > 0 {
ExitFail("%s - %s", e, strings.Join(optMsg, " "))
}
2020-03-04 00:11:54 +01:00
ExitFail("%s", e)
2020-03-02 03:54:43 +01:00
}
2020-03-02 00:48:02 +01:00
}
2020-03-02 03:16:53 +01:00
func MustPromptString(prompt string, required bool) string {
reader := bufio.NewReader(os.Stdin)
var text string
var err error
for text == "" {
2020-03-02 22:36:41 +01:00
fmt.Fprintf(os.Stderr, "%s: ", prompt)
2020-03-02 03:16:53 +01:00
text, err = reader.ReadString('\n')
check(err)
text = strings.TrimSpace(text)
}
return text
}
func ExitFail(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, "\033[31m"+format+"\033[0m\n", a...)
os.Exit(1)
}
func ConfirmOrAbort(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format+" [y/n] ", a...)
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
if input == "y\n" {
return
} else {
ExitFail("Aborted.")
}
}
2020-03-06 23:32:04 +01:00
2020-05-28 16:50:19 +02:00
func BytesToSI(b uint64) string {
2020-03-06 23:32:04 +01:00
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}