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_nogogit.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. //go:build !gogit
  5. package git
  6. import (
  7. "crypto/sha1"
  8. "encoding/hex"
  9. "hash"
  10. "strconv"
  11. )
  12. // SHA1 a git commit name
  13. type SHA1 [20]byte
  14. // String returns a string representation of the SHA
  15. func (s SHA1) String() string {
  16. return hex.EncodeToString(s[:])
  17. }
  18. // IsZero returns whether this SHA1 is all zeroes
  19. func (s SHA1) IsZero() bool {
  20. var empty SHA1
  21. return s == empty
  22. }
  23. // ComputeBlobHash compute the hash for a given blob content
  24. func ComputeBlobHash(content []byte) SHA1 {
  25. return ComputeHash(ObjectBlob, content)
  26. }
  27. // ComputeHash compute the hash for a given ObjectType and content
  28. func ComputeHash(t ObjectType, content []byte) SHA1 {
  29. h := NewHasher(t, int64(len(content)))
  30. _, _ = h.Write(content)
  31. return h.Sum()
  32. }
  33. // Hasher is a struct that will generate a SHA1
  34. type Hasher struct {
  35. hash.Hash
  36. }
  37. // NewHasher takes an object type and size and creates a hasher to generate a SHA
  38. func NewHasher(t ObjectType, size int64) Hasher {
  39. h := Hasher{sha1.New()}
  40. _, _ = h.Write(t.Bytes())
  41. _, _ = h.Write([]byte(" "))
  42. _, _ = h.Write([]byte(strconv.FormatInt(size, 10)))
  43. _, _ = h.Write([]byte{0})
  44. return h
  45. }
  46. // Sum generates a SHA1 for the provided hash
  47. func (h Hasher) Sum() (sha1 SHA1) {
  48. copy(sha1[:], h.Hash.Sum(nil))
  49. return sha1
  50. }