| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package yaml |
| 5 |
|
| 6 |
import ( |
| 7 |
"reflect" |
| 8 |
"strings" |
| 9 |
|
| 10 |
y1_1 "go.yaml.in/yaml/v2" |
| 11 |
y1_2 "go.yaml.in/yaml/v3" |
| 12 |
"k8s.io/kube-openapi/pkg/validation/spec" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
var typeToTag = map[string]string{ |
| 17 |
"string": NodeTagString, |
| 18 |
"integer": NodeTagInt, |
| 19 |
"boolean": NodeTagBool, |
| 20 |
"number": NodeTagFloat, |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
func FormatNonStringStyle(node *Node, schema spec.Schema) { |
| 26 |
if len(schema.Type) != 1 { |
| 27 |
return |
| 28 |
} |
| 29 |
t := schema.Type[0] |
| 30 |
|
| 31 |
if !IsYaml1_1NonString(node) { |
| 32 |
return |
| 33 |
} |
| 34 |
switch { |
| 35 |
case t == "string" && schema.Format != "int-or-string": |
| 36 |
if (node.Style&DoubleQuotedStyle == 0) && (node.Style&SingleQuotedStyle == 0) { |
| 37 |
|
| 38 |
node.Style = DoubleQuotedStyle |
| 39 |
} |
| 40 |
case t == "boolean" || t == "integer" || t == "number": |
| 41 |
if (node.Style&DoubleQuotedStyle != 0) || (node.Style&SingleQuotedStyle != 0) { |
| 42 |
|
| 43 |
node.Style = 0 |
| 44 |
} |
| 45 |
default: |
| 46 |
return |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
if node.Tag == NodeTagNull { |
| 52 |
|
| 53 |
node.Style = 0 |
| 54 |
return |
| 55 |
} |
| 56 |
if tag, found := typeToTag[t]; found { |
| 57 |
|
| 58 |
node.Tag = tag |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
func IsYaml1_1NonString(node *Node) bool { |
| 73 |
if node.Kind != y1_2.ScalarNode { |
| 74 |
|
| 75 |
return false |
| 76 |
} |
| 77 |
return IsValueNonString(node.Value) |
| 78 |
} |
| 79 |
|
| 80 |
func IsValueNonString(value string) bool { |
| 81 |
if value == "" { |
| 82 |
return false |
| 83 |
} |
| 84 |
if strings.Contains(value, "\n") { |
| 85 |
|
| 86 |
return false |
| 87 |
} |
| 88 |
|
| 89 |
var i1 interface{} |
| 90 |
if err := y1_1.Unmarshal([]byte(value), &i1); err != nil { |
| 91 |
return false |
| 92 |
} |
| 93 |
if reflect.TypeOf(i1) != stringType { |
| 94 |
return true |
| 95 |
} |
| 96 |
|
| 97 |
return false |
| 98 |
} |
| 99 |
|
| 100 |
var stringType = reflect.TypeOf("string") |