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

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