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.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "github.com/go-git/go-git/v5/plumbing"
  12. )
  13. // EmptySHA defines empty git SHA
  14. const EmptySHA = "0000000000000000000000000000000000000000"
  15. // EmptyTreeSHA is the SHA of an empty tree
  16. const EmptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
  17. // SHAPattern can be used to determine if a string is an valid sha
  18. var SHAPattern = regexp.MustCompile(`^[0-9a-f]{4,40}$`)
  19. // SHA1 a git commit name
  20. type SHA1 = plumbing.Hash
  21. // MustID always creates a new SHA1 from a [20]byte array with no validation of input.
  22. func MustID(b []byte) SHA1 {
  23. var id SHA1
  24. copy(id[:], b)
  25. return id
  26. }
  27. // NewID creates a new SHA1 from a [20]byte array.
  28. func NewID(b []byte) (SHA1, error) {
  29. if len(b) != 20 {
  30. return SHA1{}, fmt.Errorf("Length must be 20: %v", b)
  31. }
  32. return MustID(b), nil
  33. }
  34. // MustIDFromString always creates a new sha from a ID with no validation of input.
  35. func MustIDFromString(s string) SHA1 {
  36. b, _ := hex.DecodeString(s)
  37. return MustID(b)
  38. }
  39. // NewIDFromString creates a new SHA1 from a ID string of length 40.
  40. func NewIDFromString(s string) (SHA1, error) {
  41. var id SHA1
  42. s = strings.TrimSpace(s)
  43. if len(s) != 40 {
  44. return id, fmt.Errorf("Length must be 40: %s", s)
  45. }
  46. b, err := hex.DecodeString(s)
  47. if err != nil {
  48. return id, err
  49. }
  50. return NewID(b)
  51. }