2020-07-01 20:39:02 +03:00
|
|
|
package repository
|
2018-07-12 22:28:43 +03:00
|
|
|
|
2018-08-03 00:37:49 +03:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2019-08-11 15:08:03 +03:00
|
|
|
const idLengthSHA1 = 40
|
|
|
|
const idLengthSHA256 = 64
|
|
|
|
|
2018-08-13 16:28:16 +03:00
|
|
|
// Hash is a git hash
|
2018-07-12 22:28:43 +03:00
|
|
|
type Hash string
|
2018-08-03 00:37:49 +03:00
|
|
|
|
|
|
|
func (h Hash) String() string {
|
|
|
|
return string(h)
|
|
|
|
}
|
|
|
|
|
2018-08-13 16:28:16 +03:00
|
|
|
// UnmarshalGQL implement the Unmarshaler interface for gqlgen
|
2018-08-03 00:37:49 +03:00
|
|
|
func (h *Hash) UnmarshalGQL(v interface{}) error {
|
|
|
|
_, ok := v.(string)
|
|
|
|
if !ok {
|
2019-08-11 15:08:03 +03:00
|
|
|
return fmt.Errorf("hashes must be strings")
|
2018-08-03 00:37:49 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
*h = v.(Hash)
|
|
|
|
|
|
|
|
if !h.IsValid() {
|
|
|
|
return fmt.Errorf("invalid hash")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-08-13 16:28:16 +03:00
|
|
|
// MarshalGQL implement the Marshaler interface for gqlgen
|
2018-08-03 00:37:49 +03:00
|
|
|
func (h Hash) MarshalGQL(w io.Writer) {
|
2019-01-19 21:23:31 +03:00
|
|
|
_, _ = w.Write([]byte(`"` + h.String() + `"`))
|
2018-08-03 00:37:49 +03:00
|
|
|
}
|
|
|
|
|
2018-08-13 16:28:16 +03:00
|
|
|
// IsValid tell if the hash is valid
|
2018-08-03 00:37:49 +03:00
|
|
|
func (h *Hash) IsValid() bool {
|
2019-08-11 15:08:03 +03:00
|
|
|
// Support for both sha1 and sha256 git hashes
|
|
|
|
if len(*h) != idLengthSHA1 && len(*h) != idLengthSHA256 {
|
2018-08-03 00:37:49 +03:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
for _, r := range *h {
|
|
|
|
if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|