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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "bytes"
  6. "encoding/hex"
  7. "fmt"
  8. )
  9. type ObjectID interface {
  10. String() string
  11. IsZero() bool
  12. RawValue() []byte
  13. Type() ObjectFormat
  14. }
  15. type Sha1Hash [20]byte
  16. func (h *Sha1Hash) String() string {
  17. return hex.EncodeToString(h[:])
  18. }
  19. func (h *Sha1Hash) IsZero() bool {
  20. empty := Sha1Hash{}
  21. return bytes.Equal(empty[:], h[:])
  22. }
  23. func (h *Sha1Hash) RawValue() []byte { return h[:] }
  24. func (*Sha1Hash) Type() ObjectFormat { return Sha1ObjectFormat }
  25. var _ ObjectID = &Sha1Hash{}
  26. func MustIDFromString(hexHash string) ObjectID {
  27. id, err := NewIDFromString(hexHash)
  28. if err != nil {
  29. panic(err)
  30. }
  31. return id
  32. }
  33. type Sha256Hash [32]byte
  34. func (h *Sha256Hash) String() string {
  35. return hex.EncodeToString(h[:])
  36. }
  37. func (h *Sha256Hash) IsZero() bool {
  38. empty := Sha256Hash{}
  39. return bytes.Equal(empty[:], h[:])
  40. }
  41. func (h *Sha256Hash) RawValue() []byte { return h[:] }
  42. func (*Sha256Hash) Type() ObjectFormat { return Sha256ObjectFormat }
  43. func NewIDFromString(hexHash string) (ObjectID, error) {
  44. var theObjectFormat ObjectFormat
  45. for _, objectFormat := range DefaultFeatures().SupportedObjectFormats {
  46. if len(hexHash) == objectFormat.FullLength() {
  47. theObjectFormat = objectFormat
  48. break
  49. }
  50. }
  51. if theObjectFormat == nil {
  52. return nil, fmt.Errorf("length %d has no matched object format: %s", len(hexHash), hexHash)
  53. }
  54. b, err := hex.DecodeString(hexHash)
  55. if err != nil {
  56. return nil, err
  57. }
  58. if len(b) != theObjectFormat.FullLength()/2 {
  59. return theObjectFormat.EmptyObjectID(), fmt.Errorf("length must be %d: %v", theObjectFormat.FullLength(), b)
  60. }
  61. return theObjectFormat.MustID(b), nil
  62. }
  63. func IsEmptyCommitID(commitID string) bool {
  64. if commitID == "" {
  65. return true
  66. }
  67. id, err := NewIDFromString(commitID)
  68. if err != nil {
  69. return false
  70. }
  71. return id.IsZero()
  72. }
  73. // ComputeBlobHash compute the hash for a given blob content
  74. func ComputeBlobHash(hashType ObjectFormat, content []byte) ObjectID {
  75. return hashType.ComputeHash(ObjectBlob, content)
  76. }
  77. type ErrInvalidSHA struct {
  78. SHA string
  79. }
  80. func (err ErrInvalidSHA) Error() string {
  81. return fmt.Sprintf("invalid sha: %s", err.SHA)
  82. }