github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/sha1.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  package git
     9  
    10  import (
    11  	"encoding/hex"
    12  	"fmt"
    13  	"regexp"
    14  	"strings"
    15  )
    16  
    17  // EmptySHA defines empty git SHA
    18  const EmptySHA = "0000000000000000000000000000000000000000"
    19  
    20  // EmptyTreeSHA is the SHA of an empty tree
    21  const EmptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
    22  
    23  // SHAPattern can be used to determine if a string is an valid sha
    24  var SHAPattern = regexp.MustCompile(`^[0-9a-f]{4,40}$`)
    25  
    26  // MustID always creates a new SHA1 from a [20]byte array with no validation of input.
    27  func MustID(b []byte) SHA1 {
    28  	var id SHA1
    29  	copy(id[:], b)
    30  	return id
    31  }
    32  
    33  // NewID creates a new SHA1 from a [20]byte array.
    34  func NewID(b []byte) (SHA1, error) {
    35  	if len(b) != 20 {
    36  		return SHA1{}, fmt.Errorf("Length must be 20: %v", b)
    37  	}
    38  	return MustID(b), nil
    39  }
    40  
    41  // MustIDFromString always creates a new sha from a ID with no validation of input.
    42  func MustIDFromString(s string) SHA1 {
    43  	b, _ := hex.DecodeString(s)
    44  	return MustID(b)
    45  }
    46  
    47  // NewIDFromString creates a new SHA1 from a ID string of length 40.
    48  func NewIDFromString(s string) (SHA1, error) {
    49  	var id SHA1
    50  	s = strings.TrimSpace(s)
    51  	if len(s) != 40 {
    52  		return id, fmt.Errorf("Length must be 40: %s", s)
    53  	}
    54  	b, err := hex.DecodeString(s)
    55  	if err != nil {
    56  		return id, err
    57  	}
    58  	return NewID(b)
    59  }