github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/repo_object.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 2014 The Gogs Authors. All rights reserved.
     7  
     8  package git
     9  
    10  import (
    11  	"bytes"
    12  	"io"
    13  	"strings"
    14  )
    15  
    16  // ObjectType git object type
    17  type ObjectType string
    18  
    19  const (
    20  	// ObjectCommit commit object type
    21  	ObjectCommit ObjectType = "commit"
    22  	// ObjectTree tree object type
    23  	ObjectTree ObjectType = "tree"
    24  	// ObjectBlob blob object type
    25  	ObjectBlob ObjectType = "blob"
    26  	// ObjectTag tag object type
    27  	ObjectTag ObjectType = "tag"
    28  	// ObjectBranch branch object type
    29  	ObjectBranch ObjectType = "branch"
    30  )
    31  
    32  // Bytes returns the byte array for the Object Type
    33  func (o ObjectType) Bytes() []byte {
    34  	return []byte(o)
    35  }
    36  
    37  // HashObject takes a reader and returns SHA1 hash for that reader
    38  func (repo *Repository) HashObject(reader io.Reader) (SHA1, error) {
    39  	idStr, err := repo.hashObject(reader)
    40  	if err != nil {
    41  		return SHA1{}, err
    42  	}
    43  	return NewIDFromString(idStr)
    44  }
    45  
    46  func (repo *Repository) hashObject(reader io.Reader) (string, error) {
    47  	cmd := NewCommand(repo.Ctx, "hash-object", "-w", "--stdin")
    48  	stdout := new(bytes.Buffer)
    49  	stderr := new(bytes.Buffer)
    50  	err := cmd.Run(&RunOpts{
    51  		Dir:    repo.Path,
    52  		Stdin:  reader,
    53  		Stdout: stdout,
    54  		Stderr: stderr,
    55  	})
    56  	if err != nil {
    57  		return "", err
    58  	}
    59  	return strings.TrimSpace(stdout.String()), nil
    60  }
    61  
    62  // GetRefType gets the type of the ref based on the string
    63  func (repo *Repository) GetRefType(ref string) ObjectType {
    64  	if repo.IsTagExist(ref) {
    65  		return ObjectTag
    66  	} else if repo.IsBranchExist(ref) {
    67  		return ObjectBranch
    68  	} else if repo.IsCommitExist(ref) {
    69  		return ObjectCommit
    70  	} else if _, err := repo.GetBlob(ref); err == nil {
    71  		return ObjectBlob
    72  	}
    73  	return ObjectType("invalid")
    74  }