-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdevbuild_poll.go
91 lines (75 loc) · 2.1 KB
/
devbuild_poll.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
package handler
import (
"context"
"flag"
"fmt"
"html/template"
"net/url"
"strings"
"github.com/Masterminds/sprig/v3"
"github.com/go-resty/resty/v2"
"gopkg.in/yaml.v3"
_ "embed"
)
//go:embed devbuild_poll.md.tmpl
var devBuildPollResponseTmpl string
type pollParams struct {
buildID string
}
type pollResult struct {
Status struct {
Status string `json:"status,omitempty"`
PipelineViewURL string `json:"pipelineViewURL,omitempty"`
PipelineViewURLs []string `json:"pipelineViewURLs,omitempty"`
BuildReport map[string]any `json:"buildReport,omitempty"`
}
}
func parseCommandDevbuildPoll(args []string) (*pollParams, error) {
var ret pollParams
fs := flag.NewFlagSet("poll", flag.ContinueOnError)
fs.Parse(args)
if fs.NArg() < 1 {
return nil, fmt.Errorf("missing required positional arguments: buildId")
}
ret.buildID = fs.Arg(0)
return &ret, nil
}
func runCommandDevbuildPoll(_ context.Context, args []string) (string, error) {
params, err := parseCommandDevbuildPoll(args)
if err != nil {
return "", fmt.Errorf("failed to parse poll command: %v", err)
}
client := resty.New()
reqUrl, err := url.JoinPath(devBuildURL, params.buildID)
if err != nil {
return "", err
}
resp, err := client.R().
SetResult(pollResult{}).
// TODO: add auth in header.
Get(reqUrl)
if err != nil {
return "", err
}
if !resp.IsSuccess() {
return "", fmt.Errorf("poll devbuild failed: %s", resp.String())
}
result := resp.Result().(*pollResult)
// Create a new template and add a custom function to format JSON
t := template.Must(template.New("markdown").
Funcs(sprig.FuncMap()).
Funcs(template.FuncMap{"toYaml": func(v any) string {
yamlBytes, err := yaml.Marshal(v)
if err != nil {
return fmt.Sprintf("failed to marshal to YAML: %v", err)
}
return strings.TrimSuffix(string(yamlBytes), "\n")
}}).
Parse(devBuildPollResponseTmpl))
// Execute the template with the result data
var sb strings.Builder
if err := t.Execute(&sb, result); err != nil {
return "", fmt.Errorf("failed to execute template: %v", err)
}
return sb.String(), nil
}