1package util
 2
 3import (
 4	"fmt"
 5	"io"
 6)
 7
 8// Hash is a git hash
 9type Hash string
10
11func (h Hash) String() string {
12	return string(h)
13}
14
15// UnmarshalGQL implement the Unmarshaler interface for gqlgen
16func (h *Hash) UnmarshalGQL(v interface{}) error {
17	_, ok := v.(string)
18	if !ok {
19		return fmt.Errorf("labels must be strings")
20	}
21
22	*h = v.(Hash)
23
24	if !h.IsValid() {
25		return fmt.Errorf("invalid hash")
26	}
27
28	return nil
29}
30
31// MarshalGQL implement the Marshaler interface for gqlgen
32func (h Hash) MarshalGQL(w io.Writer) {
33	w.Write([]byte(`"` + h.String() + `"`))
34}
35
36// IsValid tell if the hash is valid
37func (h *Hash) IsValid() bool {
38	if len(*h) != 40 {
39		return false
40	}
41	for _, r := range *h {
42		if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
43			return false
44		}
45	}
46	return true
47}