summaryrefslogtreecommitdiff
path: root/cmd/generate/gerrit.go
blob: d2e9b8bbb80124dfe7c819128ff557a0928be7a6 (plain)
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
package main

import (
	"encoding"
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

// httpGetGerritJSON is like [httpGetJSON], but
// https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
func httpGetGerritJSON(u string, hdr map[string]string, out any) error {
	str, err := httpGet(u, hdr)
	if err != nil {
		return err
	}
	if _, body, ok := strings.Cut(str, "\n"); ok {
		str = body
	}
	return json.Unmarshal([]byte(str), out)
}

const GerritTimeFormat = "2006-01-02 15:04:05.000000000"

type GerritTime struct {
	Val time.Time
}

var (
	_ fmt.Stringer             = GerritTime{}
	_ encoding.TextMarshaler   = GerritTime{}
	_ encoding.TextUnmarshaler = (*GerritTime)(nil)
)

// String implements [fmt.Stringer].
func (t GerritTime) String() string {
	return t.Val.Format(GerritTimeFormat)
}

// MarshalText implements [encoding.TextMarshaler].
func (t GerritTime) MarshalText() ([]byte, error) {
	return []byte(t.String()), nil
}

// UnmarshalText implements [encoding.TextUnmarshaler].
func (t *GerritTime) UnmarshalText(data []byte) error {
	val, err := time.Parse(GerritTimeFormat, string(data))
	if err != nil {
		return err
	}
	t.Val = val
	return nil
}