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