| 1 |
package plumbing |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/hex" |
| 6 |
"sort" |
| 7 |
"strconv" |
| 8 |
|
| 9 |
"github.com/go-git/go-git/v5/plumbing/hash" |
| 10 |
) |
| 11 |
|
| 12 |
// Hash SHA1 hashed content |
| 13 |
type Hash [hash.Size]byte |
| 14 |
|
| 15 |
// ZeroHash is Hash with value zero |
| 16 |
var ZeroHash Hash |
| 17 |
|
| 18 |
// ComputeHash compute the hash for a given ObjectType and content |
| 19 |
func ComputeHash(t ObjectType, content []byte) Hash { |
| 20 |
h := NewHasher(t, int64(len(content))) |
| 21 |
h.Write(content) |
| 22 |
return h.Sum() |
| 23 |
} |
| 24 |
|
| 25 |
// NewHash return a new Hash from a hexadecimal hash representation |
| 26 |
func NewHash(s string) Hash { |
| 27 |
b, _ := hex.DecodeString(s) |
| 28 |
|
| 29 |
var h Hash |
| 30 |
copy(h[:], b) |
| 31 |
|
| 32 |
return h |
| 33 |
} |
| 34 |
|
| 35 |
func (h Hash) IsZero() bool { |
| 36 |
var empty Hash |
| 37 |
return h == empty |
| 38 |
} |
| 39 |
|
| 40 |
func (h Hash) String() string { |
| 41 |
return hex.EncodeToString(h[:]) |
| 42 |
} |
| 43 |
|
| 44 |
type Hasher struct { |
| 45 |
hash.Hash |
| 46 |
} |
| 47 |
|
| 48 |
func NewHasher(t ObjectType, size int64) Hasher { |
| 49 |
h := Hasher{hash.New(hash.CryptoType)} |
| 50 |
h.Write(t.Bytes()) |
| 51 |
h.Write([]byte(" ")) |
| 52 |
h.Write([]byte(strconv.FormatInt(size, 10))) |
| 53 |
h.Write([]byte{0}) |
| 54 |
return h |
| 55 |
} |
| 56 |
|
| 57 |
func (h Hasher) Sum() (hash Hash) { |
| 58 |
copy(hash[:], h.Hash.Sum(nil)) |
| 59 |
return |
| 60 |
} |
| 61 |
|
| 62 |
// HashesSort sorts a slice of Hashes in increasing order. |
| 63 |
func HashesSort(a []Hash) { |
| 64 |
sort.Sort(HashSlice(a)) |
| 65 |
} |
| 66 |
|
| 67 |
// HashSlice attaches the methods of sort.Interface to []Hash, sorting in |
| 68 |
// increasing order. |
| 69 |
type HashSlice []Hash |
| 70 |
|
| 71 |
func (p HashSlice) Len() int { return len(p) } |
| 72 |
func (p HashSlice) Less(i, j int) bool { return bytes.Compare(p[i][:], p[j][:]) < 0 } |
| 73 |
func (p HashSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } |
| 74 |
|
| 75 |
// IsHash returns true if the given string is a valid hash. |
| 76 |
func IsHash(s string) bool { |
| 77 |
switch len(s) { |
| 78 |
case hash.HexSize: |
| 79 |
_, err := hex.DecodeString(s) |
| 80 |
return err == nil |
| 81 |
default: |
| 82 |
return false |
| 83 |
} |
| 84 |
} |