You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sha1.go 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package git
  6. import (
  7. "encoding/hex"
  8. "fmt"
  9. "regexp"
  10. "strings"
  11. )
  12. // EmptySHA defines empty git SHA
  13. const EmptySHA = "0000000000000000000000000000000000000000"
  14. // EmptyTreeSHA is the SHA of an empty tree
  15. const EmptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
  16. // SHAPattern can be used to determine if a string is an valid sha
  17. var SHAPattern = regexp.MustCompile(`^[0-9a-f]{4,40}$`)
  18. // MustID always creates a new SHA1 from a [20]byte array with no validation of input.
  19. func MustID(b []byte) SHA1 {
  20. var id SHA1
  21. copy(id[:], b)
  22. return id
  23. }
  24. // NewID creates a new SHA1 from a [20]byte array.
  25. func NewID(b []byte) (SHA1, error) {
  26. if len(b) != 20 {
  27. return SHA1{}, fmt.Errorf("Length must be 20: %v", b)
  28. }
  29. return MustID(b), nil
  30. }
  31. // MustIDFromString always creates a new sha from a ID with no validation of input.
  32. func MustIDFromString(s string) SHA1 {
  33. b, _ := hex.DecodeString(s)
  34. return MustID(b)
  35. }
  36. // NewIDFromString creates a new SHA1 from a ID string of length 40.
  37. func NewIDFromString(s string) (SHA1, error) {
  38. var id SHA1
  39. s = strings.TrimSpace(s)
  40. if len(s) != 40 {
  41. return id, fmt.Errorf("Length must be 40: %s", s)
  42. }
  43. b, err := hex.DecodeString(s)
  44. if err != nil {
  45. return id, err
  46. }
  47. return NewID(b)
  48. }