File: util.go

package info (click to toggle)
hcloud-cli 1.39.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,628 kB
  • sloc: sh: 36; makefile: 7
file content (342 lines) | stat: -rw-r--r-- 9,343 bytes parent folder | download | duplicates (2)
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package util

import (
	"encoding/json"
	"fmt"
	"os"
	"sort"
	"strings"
	"text/template"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/pflag"

	"github.com/hetznercloud/hcloud-go/v2/hcloud"
	"github.com/hetznercloud/hcloud-go/v2/hcloud/schema"
)

func YesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func NA(s string) string {
	if s == "" {
		return "-"
	}
	return s
}

func Datetime(t time.Time) string {
	return t.Local().Format(time.UnixDate)
}

func Age(t, currentTime time.Time) string {
	diff := currentTime.Sub(t)

	if int(diff.Hours()) >= 24 {
		days := int(diff.Hours()) / 24
		return fmt.Sprintf("%dd", days)
	}

	if int(diff.Hours()) > 0 {
		return fmt.Sprintf("%dh", int(diff.Hours()))
	}

	if int(diff.Minutes()) > 0 {
		return fmt.Sprintf("%dm", int(diff.Minutes()))
	}

	if int(diff.Seconds()) > 0 {
		return fmt.Sprintf("%ds", int(diff.Seconds()))
	}

	return "just now"
}

func ChainRunE(fns ...func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {
	return func(cmd *cobra.Command, args []string) error {
		for _, fn := range fns {
			if fn == nil {
				continue
			}
			if err := fn(cmd, args); err != nil {
				return err
			}
		}
		return nil
	}
}

func ExactlyOneSet(s string, ss ...string) bool {
	set := s != ""
	for _, s := range ss {
		if set && s != "" {
			return false
		}
		set = set || s != ""
	}
	return set
}

var outputDescription = `Output can be controlled with the -o flag. Use -o noheader to suppress the
table header. Displayed columns and their order can be set with
-o columns=%s (see available columns below).`

func ListLongDescription(intro string, columns []string) string {
	var colExample []string
	if len(columns) > 2 {
		colExample = columns[0:2]
	} else {
		colExample = columns
	}
	return fmt.Sprintf(
		"%s\n\n%s\n\nColumns:\n - %s",
		intro,
		fmt.Sprintf(outputDescription, strings.Join(colExample, ",")),
		strings.Join(columns, "\n - "),
	)
}

func SplitLabel(label string) []string {
	return strings.SplitN(label, "=", 2)
}

// SplitLabelVars splits up label into key and value and returns them as separate return values.
// If label doesn't contain the `=` separator, SplitLabelVars returns the original string as key,
// with an empty value.
func SplitLabelVars(label string) (string, string) {
	parts := strings.SplitN(label, "=", 2)
	if len(parts) != 2 {
		return label, ""
	}
	return parts[0], parts[1]
}

func LabelsToString(labels map[string]string) string {
	var labelsString []string
	keys := make([]string, 0, len(labels))
	for key := range labels {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, key := range keys {
		value := labels[key]
		if value == "" {
			labelsString = append(labelsString, key)
		} else {
			labelsString = append(labelsString, fmt.Sprintf("%s=%s", key, value))
		}
	}
	return strings.Join(labelsString, ", ")
}

// PrefixLines will prefix all individual lines in the text with the passed prefix.
func PrefixLines(text, prefix string) string {
	var lines []string

	for _, line := range strings.Split(text, "\n") {
		lines = append(lines, prefix+line)
	}

	return strings.Join(lines, "\n")
}

func DescribeFormat(object interface{}, format string) error {
	if !strings.HasSuffix(format, "\n") {
		format = format + "\n"
	}
	t, err := template.New("").Parse(format)
	if err != nil {
		return err
	}
	return t.Execute(os.Stdout, object)
}

func DescribeJSON(object interface{}) error {
	enc := json.NewEncoder(os.Stdout)
	return enc.Encode(object)
}

func LocationToSchema(location hcloud.Location) schema.Location {
	return schema.Location{
		ID:          location.ID,
		Name:        location.Name,
		Description: location.Description,
		Country:     location.Country,
		City:        location.City,
		Latitude:    location.Latitude,
		Longitude:   location.Longitude,
		NetworkZone: string(location.NetworkZone),
	}
}

func DatacenterToSchema(datacenter hcloud.Datacenter) schema.Datacenter {
	datacenterSchema := schema.Datacenter{
		ID:          datacenter.ID,
		Name:        datacenter.Name,
		Description: datacenter.Description,
		Location:    LocationToSchema(*datacenter.Location),
	}
	for _, st := range datacenter.ServerTypes.Supported {
		datacenterSchema.ServerTypes.Supported = append(datacenterSchema.ServerTypes.Supported, st.ID)
	}
	for _, st := range datacenter.ServerTypes.Available {
		datacenterSchema.ServerTypes.Available = append(datacenterSchema.ServerTypes.Available, st.ID)
	}
	return datacenterSchema
}

func ServerTypeToSchema(serverType hcloud.ServerType) schema.ServerType {
	serverTypeSchema := schema.ServerType{
		ID:                   serverType.ID,
		Name:                 serverType.Name,
		Description:          serverType.Description,
		Cores:                serverType.Cores,
		Memory:               serverType.Memory,
		Disk:                 serverType.Disk,
		StorageType:          string(serverType.StorageType),
		CPUType:              string(serverType.CPUType),
		Architecture:         string(serverType.Architecture),
		IncludedTraffic:      serverType.IncludedTraffic,
		DeprecatableResource: DeprecatableResourceToSchema(serverType.DeprecatableResource),
	}
	for _, pricing := range serverType.Pricings {
		serverTypeSchema.Prices = append(serverTypeSchema.Prices, schema.PricingServerTypePrice{
			Location: pricing.Location.Name,
			PriceHourly: schema.Price{
				Net:   pricing.Hourly.Net,
				Gross: pricing.Hourly.Gross,
			},
			PriceMonthly: schema.Price{
				Net:   pricing.Monthly.Net,
				Gross: pricing.Monthly.Gross,
			},
		})
	}
	return serverTypeSchema
}

func ImageToSchema(image hcloud.Image) schema.Image {
	imageSchema := schema.Image{
		ID:           image.ID,
		Name:         hcloud.String(image.Name),
		Description:  image.Description,
		Status:       string(image.Status),
		Type:         string(image.Type),
		ImageSize:    &image.ImageSize,
		DiskSize:     image.DiskSize,
		Created:      image.Created,
		OSFlavor:     image.OSFlavor,
		OSVersion:    hcloud.String(image.OSVersion),
		Architecture: string(image.Architecture),
		RapidDeploy:  image.RapidDeploy,
		Protection: schema.ImageProtection{
			Delete: image.Protection.Delete,
		},
		Deprecated: image.Deprecated,
		Labels:     image.Labels,
	}
	if image.CreatedFrom != nil {
		imageSchema.CreatedFrom = &schema.ImageCreatedFrom{
			ID:   image.CreatedFrom.ID,
			Name: image.CreatedFrom.Name,
		}
	}
	if image.BoundTo != nil {
		imageSchema.BoundTo = hcloud.Ptr(image.BoundTo.ID)
	}
	return imageSchema
}

func ISOToSchema(iso hcloud.ISO) schema.ISO {
	isoSchema := schema.ISO{
		ID:          iso.ID,
		Name:        iso.Name,
		Description: iso.Description,
		Type:        string(iso.Type),
		Deprecated:  iso.Deprecated,
	}

	if iso.Architecture != nil {
		isoSchema.Architecture = hcloud.Ptr(string(*iso.Architecture))
	}

	return isoSchema
}

func LoadBalancerTypeToSchema(loadBalancerType hcloud.LoadBalancerType) schema.LoadBalancerType {
	loadBalancerTypeSchema := schema.LoadBalancerType{
		ID:                      loadBalancerType.ID,
		Name:                    loadBalancerType.Name,
		Description:             loadBalancerType.Description,
		MaxConnections:          loadBalancerType.MaxConnections,
		MaxServices:             loadBalancerType.MaxServices,
		MaxTargets:              loadBalancerType.MaxTargets,
		MaxAssignedCertificates: loadBalancerType.MaxAssignedCertificates,
	}
	for _, pricing := range loadBalancerType.Pricings {
		loadBalancerTypeSchema.Prices = append(loadBalancerTypeSchema.Prices, schema.PricingLoadBalancerTypePrice{
			Location: pricing.Location.Name,
			PriceHourly: schema.Price{
				Net:   pricing.Hourly.Net,
				Gross: pricing.Hourly.Gross,
			},
			PriceMonthly: schema.Price{
				Net:   pricing.Monthly.Net,
				Gross: pricing.Monthly.Gross,
			},
		})
	}
	return loadBalancerTypeSchema
}

func PlacementGroupToSchema(placementGroup hcloud.PlacementGroup) schema.PlacementGroup {
	return schema.PlacementGroup{
		ID:      placementGroup.ID,
		Name:    placementGroup.Name,
		Labels:  placementGroup.Labels,
		Created: placementGroup.Created,
		Type:    string(placementGroup.Type),
		Servers: placementGroup.Servers,
	}
}

func DeprecatableResourceToSchema(deprecatableResource hcloud.DeprecatableResource) schema.DeprecatableResource {
	var deprecation *schema.DeprecationInfo

	if deprecatableResource.IsDeprecated() {
		deprecation = &schema.DeprecationInfo{
			Announced:        deprecatableResource.Deprecation.Announced,
			UnavailableAfter: deprecatableResource.Deprecation.UnavailableAfter,
		}
	}

	return schema.DeprecatableResource{
		Deprecation: deprecation,
	}
}

// ValidateRequiredFlags ensures that flags has values for all flags with
// the passed names.
//
// This function duplicates the functionality cobra provides when calling
// MarkFlagRequired. However, in some cases a flag cannot be marked as required
// in cobra, for example when it depends on other flags. In those cases this
// function comes in handy.
func ValidateRequiredFlags(flags *pflag.FlagSet, names ...string) error {
	var missingFlags []string

	for _, name := range names {
		if !flags.Changed(name) {
			missingFlags = append(missingFlags, `"`+name+`"`)
		}
	}
	if len(missingFlags) > 0 {
		return fmt.Errorf("hcloud: required flag(s) %s not set", strings.Join(missingFlags, ", "))
	}
	return nil
}