This repository has been archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
template_builder.go
117 lines (93 loc) · 2.4 KB
/
template_builder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package goca
import (
"errors"
"fmt"
"strings"
)
// TemplateBuilder represents an OpenNebula syntax template
type TemplateBuilder struct {
elements []TemplateBuilderElement
}
// TemplateBuilderElement is an interface that must implement the String
// function
type TemplateBuilderElement interface {
String() string
}
// TemplateBuilderPair is a key / value pair
type TemplateBuilderPair struct {
key string
value string
}
// TemplateBuilderVector contains an array of keyvalue pairs
type TemplateBuilderVector struct {
key string
pairs []TemplateBuilderPair
}
// NewTemplateBuilder returns a new TemplateBuilder object
func NewTemplateBuilder() *TemplateBuilder {
return &TemplateBuilder{}
}
// NewVector creates a new vector in the template
func (t *TemplateBuilder) NewVector(key string) *TemplateBuilderVector {
vector := &TemplateBuilderVector{key: key}
t.elements = append(t.elements, vector)
return vector
}
// String prints the TemplateBuilder in OpenNebula syntax
func (t *TemplateBuilder) String() string {
s := ""
endToken := "\n"
for i, element := range t.elements {
if i == len(t.elements)-1 {
endToken = ""
}
s += element.String() + endToken
}
return s
}
// String prints a TemplateBuilderPair in OpenNebula syntax
func (t *TemplateBuilderPair) String() string {
return fmt.Sprintf("%s=\"%s\"", t.key, t.value)
}
func (t *TemplateBuilderVector) String() string {
s := fmt.Sprintf("%s=[\n", strings.ToUpper(t.key))
endToken := ",\n"
for i, pair := range t.pairs {
if i == len(t.pairs)-1 {
endToken = ""
}
s += fmt.Sprintf(" %s%s", pair.String(), endToken)
}
s += " ]"
return s
}
// AddValue adds a new pair to a TemplateBuilder objects
func (t *TemplateBuilder) AddValue(key string, v interface{}) error {
var val string
switch v := v.(type) {
default:
return errors.New("Unexpected type")
case int, uint:
val = fmt.Sprintf("%d", v)
case string:
val = v
}
pair := &TemplateBuilderPair{strings.ToUpper(key), val}
t.elements = append(t.elements, pair)
return nil
}
// AddValue adds a new pair to a TemplateBuilderVector
func (t *TemplateBuilderVector) AddValue(key string, v interface{}) error {
var val string
switch v := v.(type) {
default:
return errors.New("Unexpected type")
case int, uint:
val = fmt.Sprintf("%d", v)
case string:
val = v
}
pair := TemplateBuilderPair{strings.ToUpper(key), val}
t.pairs = append(t.pairs, pair)
return nil
}