code.gitea.io/gitea@v1.22.3/modules/git/repo_object.go (about) 1 // Copyright 2014 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 "bytes" 9 "io" 10 "strings" 11 ) 12 13 // ObjectType git object type 14 type ObjectType string 15 16 const ( 17 // ObjectCommit commit object type 18 ObjectCommit ObjectType = "commit" 19 // ObjectTree tree object type 20 ObjectTree ObjectType = "tree" 21 // ObjectBlob blob object type 22 ObjectBlob ObjectType = "blob" 23 // ObjectTag tag object type 24 ObjectTag ObjectType = "tag" 25 // ObjectBranch branch object type 26 ObjectBranch ObjectType = "branch" 27 ) 28 29 // Bytes returns the byte array for the Object Type 30 func (o ObjectType) Bytes() []byte { 31 return []byte(o) 32 } 33 34 type EmptyReader struct{} 35 36 func (EmptyReader) Read(p []byte) (int, error) { 37 return 0, io.EOF 38 } 39 40 func (repo *Repository) GetObjectFormat() (ObjectFormat, error) { 41 if repo != nil && repo.objectFormat != nil { 42 return repo.objectFormat, nil 43 } 44 45 str, err := repo.hashObject(EmptyReader{}, false) 46 if err != nil { 47 return nil, err 48 } 49 hash, err := NewIDFromString(str) 50 if err != nil { 51 return nil, err 52 } 53 54 repo.objectFormat = hash.Type() 55 56 return repo.objectFormat, nil 57 } 58 59 // HashObject takes a reader and returns hash for that reader 60 func (repo *Repository) HashObject(reader io.Reader) (ObjectID, error) { 61 idStr, err := repo.hashObject(reader, true) 62 if err != nil { 63 return nil, err 64 } 65 return NewIDFromString(idStr) 66 } 67 68 func (repo *Repository) hashObject(reader io.Reader, save bool) (string, error) { 69 var cmd *Command 70 if save { 71 cmd = NewCommand(repo.Ctx, "hash-object", "-w", "--stdin") 72 } else { 73 cmd = NewCommand(repo.Ctx, "hash-object", "--stdin") 74 } 75 stdout := new(bytes.Buffer) 76 stderr := new(bytes.Buffer) 77 err := cmd.Run(&RunOpts{ 78 Dir: repo.Path, 79 Stdin: reader, 80 Stdout: stdout, 81 Stderr: stderr, 82 }) 83 if err != nil { 84 return "", err 85 } 86 return strings.TrimSpace(stdout.String()), nil 87 } 88 89 // GetRefType gets the type of the ref based on the string 90 func (repo *Repository) GetRefType(ref string) ObjectType { 91 if repo.IsTagExist(ref) { 92 return ObjectTag 93 } else if repo.IsBranchExist(ref) { 94 return ObjectBranch 95 } else if repo.IsCommitExist(ref) { 96 return ObjectCommit 97 } else if _, err := repo.GetBlob(ref); err == nil { 98 return ObjectBlob 99 } 100 return ObjectType("invalid") 101 }