-
Notifications
You must be signed in to change notification settings - Fork 2k
/
cli.go
112 lines (99 loc) · 3.32 KB
/
cli.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package e2eutil
import (
"context"
"fmt"
"os/exec"
"regexp"
"strings"
"time"
)
// Command sends a command line argument to Nomad and returns the unbuffered
// stdout as a string (or, if there's an error, the stderr)
func Command(cmd string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
bytes, err := exec.CommandContext(ctx, cmd, args...).CombinedOutput()
out := string(bytes)
if err != nil {
return out, fmt.Errorf("command %v %v failed: %v\nOutput: %v", cmd, args, err, out)
}
return out, err
}
// GetField returns the value of an output field (ex. the "Submit Date" field
// of `nomad job status :id`)
func GetField(output, key string) (string, error) {
re := regexp.MustCompile(`(?m)^` + key + ` += (.*)$`)
match := re.FindStringSubmatch(output)
if match == nil {
return "", fmt.Errorf("could not find field %q", key)
}
return match[1], nil
}
// GetSection returns a section, with its field header but without its title.
// (ex. the Allocations section of `nomad job status :id`)
func GetSection(output, key string) (string, error) {
// golang's regex engine doesn't support negative lookahead, so
// we can't stop at 2 newlines if we also want a section that includes
// single newlines. so split on the section title, and then split a second time
// on \n\n
re := regexp.MustCompile(`(?ms)^` + key + `\n(.*)`)
match := re.FindStringSubmatch(output)
if match == nil {
return "", fmt.Errorf("could not find section %q", key)
}
tail := match[1]
return strings.Split(tail, "\n\n")[0], nil
}
// ParseColumns maps the CLI output for a columized section (without title) to
// a slice of key->value pairs for each row in that section.
// (ex. the Allocations section of `nomad job status :id`)
func ParseColumns(section string) ([]map[string]string, error) {
parsed := []map[string]string{}
// field names and values are deliminated by two or more spaces, but can have a
// single space themselves. compress all the delimiters into a tab so we can
// break the fields on that
re := regexp.MustCompile(" {2,}")
section = re.ReplaceAllString(section, "\t")
rows := strings.Split(section, "\n")
breakFields := func(row string) []string {
return strings.FieldsFunc(row, func(c rune) bool { return c == '\t' })
}
fieldNames := breakFields(rows[0])
for _, row := range rows[1:] {
if row == "" {
continue
}
r := map[string]string{}
vals := breakFields(row)
for i, val := range vals {
if i >= len(fieldNames) {
return parsed, fmt.Errorf("section is misaligned with header\n%v", section)
}
r[fieldNames[i]] = val
}
parsed = append(parsed, r)
}
return parsed, nil
}
// ParseFields maps the CLI output for a key-value section (without title) to
// map of the key->value pairs in that section
// (ex. the Latest Deployment section of `nomad job status :id`)
func ParseFields(section string) (map[string]string, error) {
parsed := map[string]string{}
rows := strings.Split(strings.TrimSpace(section), "\n")
for _, row := range rows {
kv := strings.Split(row, "=")
if len(kv) == 0 {
continue
}
key := strings.TrimSpace(kv[0])
if len(kv) == 1 {
parsed[key] = ""
} else {
parsed[key] = strings.TrimSpace(strings.Join(kv[1:], " "))
}
}
return parsed, nil
}