2019-12-02 14:15:50 +01:00
|
|
|
package utils
|
2018-02-07 19:02:18 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2018-06-25 16:31:44 +02:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"unicode/utf8"
|
2018-02-07 19:02:18 +01:00
|
|
|
|
2018-06-29 16:50:05 +02:00
|
|
|
"github.com/fatih/color"
|
2018-02-07 19:02:18 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// Log outputs a log message.
|
|
|
|
func Log(msg string, v ...interface{}) {
|
2018-06-29 16:50:05 +02:00
|
|
|
fmt.Printf(" %s\n", color.CyanString(msg, v...))
|
2018-02-07 19:02:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Fatal error
|
|
|
|
func Fatal(err error) {
|
2018-06-29 16:50:05 +02:00
|
|
|
fmt.Fprintf(os.Stderr, "\n %s %s\n\n", color.RedString("Error:"), err)
|
2018-02-07 19:02:18 +01:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
2018-06-25 16:31:44 +02:00
|
|
|
|
2018-06-29 16:38:13 +02:00
|
|
|
// Finds the ansi escape sequences (like colors)
|
|
|
|
// Taken from: https://github.com/chalk/ansi-regex/blob/d9d806ecb45d899cf43408906a4440060c5c50e5/index.js
|
|
|
|
var ansiEscapes = regexp.MustCompile(`[\x1B\x9B][[\]()#;?]*` +
|
|
|
|
`(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\\d]*)*)?\x07)` +
|
|
|
|
`|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PRZcf-ntqry=><~]))`)
|
2018-06-25 16:31:44 +02:00
|
|
|
|
2019-10-03 11:18:07 +02:00
|
|
|
// EscapeAwareRuneCountInString counts the number of runes in a
|
|
|
|
// string taking into account escape sequences.
|
2018-06-25 16:31:44 +02:00
|
|
|
func EscapeAwareRuneCountInString(s string) int {
|
|
|
|
n := utf8.RuneCountInString(s)
|
2018-06-29 16:38:13 +02:00
|
|
|
for _, sm := range ansiEscapes.FindAllString(s, -1) {
|
2018-06-25 16:31:44 +02:00
|
|
|
n -= utf8.RuneCountInString(sm)
|
|
|
|
}
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
|
2021-03-31 15:59:19 +02:00
|
|
|
// RightPad adds right padding in from of a string
|
2018-06-25 16:31:44 +02:00
|
|
|
func RightPad(str string, length int) string {
|
2018-09-12 14:03:07 +02:00
|
|
|
c := length - EscapeAwareRuneCountInString(str)
|
|
|
|
if c < 0 {
|
|
|
|
c = 0
|
|
|
|
}
|
|
|
|
return str + strings.Repeat(" ", c)
|
2018-06-25 16:31:44 +02:00
|
|
|
}
|