code.gitea.io/gitea@v1.19.3/modules/git/sha1_nogogit.go (about)

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