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

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