85 lines
1.8 KiB
Go
85 lines
1.8 KiB
Go
package clifmt
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
var titleIndex = 0
|
|
var alignOffset = 30
|
|
|
|
// Warn returns a red warning ASCII sign. If a string is given
|
|
// as argument, it will print it after the warning sign
|
|
func Warn(s ...string) string {
|
|
if len(s) == 0 {
|
|
return Color(31, "/!\\")
|
|
}
|
|
|
|
return fmt.Sprintf("%s %s", Warn(), s[0])
|
|
}
|
|
|
|
// Info returns a blue info ASCII sign. If a string is given
|
|
// as argument, it will print it after the info sign
|
|
func Info(s ...string) string {
|
|
if len(s) == 0 {
|
|
return Color(34, "(!)")
|
|
}
|
|
|
|
return fmt.Sprintf("%s %s", Info(), s[0])
|
|
}
|
|
|
|
// Title prints a formatted title (auto-indexed from local counted)
|
|
func Title(s string) {
|
|
titleIndex++
|
|
fmt.Printf("\n%s |%d| %s %s\n", Color(33, ">>", false), titleIndex, s, Color(33, "<<", false))
|
|
|
|
}
|
|
|
|
// Align prints strings with space padding to align line ends (fixed width)
|
|
// also crops the content to add '...' at the end if too long (must have a space
|
|
// at the end)
|
|
func Align(s string) {
|
|
|
|
// 1. replace tabs with 4 spaces
|
|
tabs := strings.Split(s, "\t")
|
|
s = strings.Join(tabs, " ")
|
|
|
|
// 1. get real size
|
|
size := getRealSize(s)
|
|
|
|
if size > alignOffset-6 {
|
|
|
|
for i, l := 0, len(s); i < l; i++ { // find when real size is right under
|
|
next := fmt.Sprintf("%s\033[0m… ", s[0:i+1])
|
|
if getRealSize(next) >= alignOffset-5 {
|
|
s = next
|
|
break
|
|
}
|
|
|
|
}
|
|
size = getRealSize(s) - 1
|
|
}
|
|
|
|
// 2. print string
|
|
fmt.Printf("%s", s)
|
|
|
|
// 3. print trailing spaces
|
|
for i := size; i < alignOffset; i++ {
|
|
fmt.Printf(" ")
|
|
}
|
|
}
|
|
|
|
// getRealSize returns the real size escaping special characters
|
|
func getRealSize(s string) int {
|
|
// 1. get actual size
|
|
size := len(s)
|
|
|
|
// 2. remove \033[XYm format characters
|
|
size -= 7 * len(strings.Split(s, "\033"))
|
|
|
|
// 3. compensate 1 char for \033[0m
|
|
size += len(strings.Split(s, "\033[0m"))
|
|
|
|
return size
|
|
}
|