code.gitea.io/gitea@v1.19.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  // HashObject takes a reader and returns SHA1 hash for that reader
    35  func (repo *Repository) HashObject(reader io.Reader) (SHA1, error) {
    36  	idStr, err := repo.hashObject(reader)
    37  	if err != nil {
    38  		return SHA1{}, err
    39  	}
    40  	return NewIDFromString(idStr)
    41  }
    42  
    43  func (repo *Repository) hashObject(reader io.Reader) (string, error) {
    44  	cmd := NewCommand(repo.Ctx, "hash-object", "-w", "--stdin")
    45  	stdout := new(bytes.Buffer)
    46  	stderr := new(bytes.Buffer)
    47  	err := cmd.Run(&RunOpts{
    48  		Dir:    repo.Path,
    49  		Stdin:  reader,
    50  		Stdout: stdout,
    51  		Stderr: stderr,
    52  	})
    53  	if err != nil {
    54  		return "", err
    55  	}
    56  	return strings.TrimSpace(stdout.String()), nil
    57  }
    58  
    59  // GetRefType gets the type of the ref based on the string
    60  func (repo *Repository) GetRefType(ref string) ObjectType {
    61  	if repo.IsTagExist(ref) {
    62  		return ObjectTag
    63  	} else if repo.IsBranchExist(ref) {
    64  		return ObjectBranch
    65  	} else if repo.IsCommitExist(ref) {
    66  		return ObjectCommit
    67  	} else if _, err := repo.GetBlob(ref); err == nil {
    68  		return ObjectBlob
    69  	}
    70  	return ObjectType("invalid")
    71  }