github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/sha1_nogogit.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 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 6 // Copyright 2015 The Gogs Authors. All rights reserved. 7 8 //go:build !gogit 9 10 package git 11 12 import ( 13 "crypto/sha1" 14 "encoding/hex" 15 "hash" 16 "strconv" 17 ) 18 19 // SHA1 a git commit name 20 type SHA1 [20]byte 21 22 // String returns a string representation of the SHA 23 func (s SHA1) String() string { 24 return hex.EncodeToString(s[:]) 25 } 26 27 // IsZero returns whether this SHA1 is all zeroes 28 func (s SHA1) IsZero() bool { 29 var empty SHA1 30 return s == empty 31 } 32 33 // ComputeBlobHash compute the hash for a given blob content 34 func ComputeBlobHash(content []byte) SHA1 { 35 return ComputeHash(ObjectBlob, content) 36 } 37 38 // ComputeHash compute the hash for a given ObjectType and content 39 func ComputeHash(t ObjectType, content []byte) SHA1 { 40 h := NewHasher(t, int64(len(content))) 41 _, _ = h.Write(content) 42 return h.Sum() 43 } 44 45 // Hasher is a struct that will generate a SHA1 46 type Hasher struct { 47 hash.Hash 48 } 49 50 // NewHasher takes an object type and size and creates a hasher to generate a SHA 51 func NewHasher(t ObjectType, size int64) Hasher { 52 h := Hasher{sha1.New()} 53 _, _ = h.Write(t.Bytes()) 54 _, _ = h.Write([]byte(" ")) 55 _, _ = h.Write([]byte(strconv.FormatInt(size, 10))) 56 _, _ = h.Write([]byte{0}) 57 return h 58 } 59 60 // Sum generates a SHA1 for the provided hash 61 func (h Hasher) Sum() (sha1 SHA1) { 62 copy(sha1[:], h.Hash.Sum(nil)) 63 return 64 }