code.gitea.io/gitea@v1.19.3/modules/git/sha1.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 package git 6 7 import ( 8 "encoding/hex" 9 "fmt" 10 "regexp" 11 "strings" 12 ) 13 14 // EmptySHA defines empty git SHA 15 const EmptySHA = "0000000000000000000000000000000000000000" 16 17 // EmptyTreeSHA is the SHA of an empty tree 18 const EmptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" 19 20 // SHAFullLength is the full length of a git SHA 21 const SHAFullLength = 40 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 // IsValidSHAPattern will check if the provided string matches the SHA Pattern 27 func IsValidSHAPattern(sha string) bool { 28 return shaPattern.MatchString(sha) 29 } 30 31 // MustID always creates a new SHA1 from a [20]byte array with no validation of input. 32 func MustID(b []byte) SHA1 { 33 var id SHA1 34 copy(id[:], b) 35 return id 36 } 37 38 // NewID creates a new SHA1 from a [20]byte array. 39 func NewID(b []byte) (SHA1, error) { 40 if len(b) != 20 { 41 return SHA1{}, fmt.Errorf("Length must be 20: %v", b) 42 } 43 return MustID(b), nil 44 } 45 46 // MustIDFromString always creates a new sha from a ID with no validation of input. 47 func MustIDFromString(s string) SHA1 { 48 b, _ := hex.DecodeString(s) 49 return MustID(b) 50 } 51 52 // NewIDFromString creates a new SHA1 from a ID string of length 40. 53 func NewIDFromString(s string) (SHA1, error) { 54 var id SHA1 55 s = strings.TrimSpace(s) 56 if len(s) != SHAFullLength { 57 return id, fmt.Errorf("Length must be 40: %s", s) 58 } 59 b, err := hex.DecodeString(s) 60 if err != nil { 61 return id, err 62 } 63 return NewID(b) 64 }