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