aboutsummaryrefslogtreecommitdiffstats
path: root/entities/bug/status.go
blob: b8fba609fbf290a03196d7a3e834f41e1207ccff (plain) (blame)
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
package bug

import (
	"fmt"
	"io"
	"strconv"
	"strings"
)

type Status int

const (
	_ Status = iota
	OpenStatus
	ClosedStatus
)

func (s Status) String() string {
	switch s {
	case OpenStatus:
		return "open"
	case ClosedStatus:
		return "closed"
	default:
		return "unknown status"
	}
}

func (s Status) Action() string {
	switch s {
	case OpenStatus:
		return "opened"
	case ClosedStatus:
		return "closed"
	default:
		return "unknown status"
	}
}

func StatusFromString(str string) (Status, error) {
	cleaned := strings.ToLower(strings.TrimSpace(str))

	switch cleaned {
	case "open":
		return OpenStatus, nil
	case "closed":
		return ClosedStatus, nil
	default:
		return 0, fmt.Errorf("unknown status")
	}
}

func (s Status) Validate() error {
	if s != OpenStatus && s != ClosedStatus {
		return fmt.Errorf("invalid")
	}

	return nil
}

func (s Status) MarshalGQL(w io.Writer) {
	switch s {
	case OpenStatus:
		_, _ = fmt.Fprintf(w, strconv.Quote("OPEN"))
	case ClosedStatus:
		_, _ = fmt.Fprintf(w, strconv.Quote("CLOSED"))
	default:
		panic("missing case")
	}
}

func (s *Status) UnmarshalGQL(v interface{}) error {
	str, ok := v.(string)
	if !ok {
		return fmt.Errorf("enums must be strings")
	}
	switch str {
	case "OPEN":
		*s = OpenStatus
	case "CLOSED":
		*s = ClosedStatus
	default:
		return fmt.Errorf("%s is not a valid Status", str)
	}
	return nil
}