drone-yaml/yaml/pretty/util.go

145 lines
2.4 KiB
Go
Raw Normal View History

// Copyright (c), the Drone Authors.
// Copyright (c) 2021, Robert Kaussow <mail@thegeeklab.de>
2019-02-10 19:00:16 +00:00
2019-01-22 23:44:17 +00:00
package pretty
2019-06-07 02:09:32 +00:00
import (
"strings"
"github.com/drone/drone-yaml/yaml"
)
2019-01-22 23:44:17 +00:00
func isPrimative(v interface{}) bool {
switch v.(type) {
2019-03-18 03:03:27 +00:00
case bool, string, int, int64, float64:
2019-01-22 23:44:17 +00:00
return true
case yaml.BytesSize:
return true
default:
return false
}
}
func isSlice(v interface{}) bool {
switch v.(type) {
case []interface{}:
return true
case []string:
return true
default:
return false
}
}
func isZero(v interface{}) bool {
switch v := v.(type) {
case bool:
return !v
2019-01-22 23:44:17 +00:00
case string:
return len(v) == 0
case int:
return v == 0
case float64:
return v == 0
case []interface{}:
return len(v) == 0
case []string:
return len(v) == 0
case map[interface{}]interface{}:
return len(v) == 0
case map[string]string:
return len(v) == 0
case yaml.BytesSize:
return int64(v) == 0
default:
return false
}
}
2019-06-07 02:09:32 +00:00
func isEscapeCode(b rune) bool {
2019-01-22 23:44:17 +00:00
switch b {
case '\a', '\b', '\f', '\n', '\r', '\t', '\v':
return true
default:
return false
}
}
2019-06-07 02:09:32 +00:00
func isQuoted(s string) bool {
// if the string is empty it should be quoted.
if len(s) == 0 {
return true
}
var r0, r1 byte
2019-06-07 02:09:32 +00:00
t := strings.TrimSpace(s)
// if the trimmed string does not match the string, it
// has starting or tailing white space and therefore
// needs to be quoted to preserve the whitespace
if t != s {
return true
}
if len(t) > 0 {
r0 = t[0]
}
2019-06-07 02:09:32 +00:00
if len(t) > 1 {
r1 = t[1]
}
switch r0 {
// if the yaml starts with any of these characters
// the string should be quoted.
case ',', '[', ']', '{', '}', '*', '"', '\'', '%', '@', '`', '|', '>', '#':
return true
case '&', '!', '-', ':', '?':
// if the yaml starts with any of these characters,
// followed by whitespace, the string should be quoted.
if r1 == ' ' {
return true
}
}
var prev rune
2019-06-07 02:09:32 +00:00
for _, b := range s {
switch {
case isEscapeCode(b):
return true
case b == ' ' && prev == ':':
return true
case b == '#' && prev == ' ':
return true
}
2019-06-07 02:09:32 +00:00
prev = b
}
// if the string ends in : it should be quoted otherwise
// it is interpreted as an object.
return strings.HasSuffix(t, ":")
}
2019-01-22 23:44:17 +00:00
func chunk(s string, chunkSize int) []string {
if len(s) == 0 {
return []string{s}
}
2019-01-22 23:44:17 +00:00
var chunks []string
2019-01-22 23:44:17 +00:00
for i := 0; i < len(s); i += chunkSize {
nn := i + chunkSize
if nn > len(s) {
nn = len(s)
}
2019-01-22 23:44:17 +00:00
chunks = append(chunks, s[i:nn])
}
2019-01-22 23:44:17 +00:00
return chunks
}