1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-12-22 12:54:53 -05:00

Improve ObjectFormat interface (#28496)

The 4 functions are duplicated, especially as interface methods. I think
we just need to keep `MustID` the only one and remove other 3.

```
MustID(b []byte) ObjectID
MustIDFromString(s string) ObjectID
NewID(b []byte) (ObjectID, error)
NewIDFromString(s string) (ObjectID, error)
```

Introduced the new interfrace method `ComputeHash` which will replace
the interface `HasherInterface`. Now we don't need to keep two
interfaces.

Reintroduced `git.NewIDFromString` and `git.MustIDFromString`. The new
function will detect the hash length to decide which objectformat of it.
If it's 40, then it's SHA1. If it's 64, then it's SHA256. This will be
right if the commitID is a full one. So the parameter should be always a
full commit id.

@AdamMajer Please review.
This commit is contained in:
Lunny Xiao 2023-12-19 15:20:47 +08:00 committed by GitHub
parent 128eac9e0b
commit 4eb2a29910
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
39 changed files with 109 additions and 168 deletions

View file

@ -377,7 +377,7 @@ Gitea or set your environment appropriately.`, "")
newCommitIDs[count] = string(fields[1])
refFullNames[count] = git.RefName(fields[2])
commitID, _ := git.IDFromString(newCommitIDs[count])
commitID, _ := git.NewIDFromString(newCommitIDs[count])
if refFullNames[count] == git.BranchPrefix+"master" && !commitID.IsZero() && count == total {
masterPushed = true
}
@ -671,7 +671,7 @@ Gitea or set your environment appropriately.`, "")
if err != nil {
return err
}
commitID, _ := git.IDFromString(rs.OldOID)
commitID, _ := git.NewIDFromString(rs.OldOID)
if !commitID.IsZero() {
err = writeDataPktLine(ctx, os.Stdout, []byte("option old-oid "+rs.OldOID))
if err != nil {

View file

@ -30,9 +30,8 @@ func TestAddDeletedBranch(t *testing.T) {
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"})
assert.True(t, secondBranch.IsDeleted)
objectFormat := git.ObjectFormatFromName(repo.ObjectFormatName)
commit := &git.Commit{
ID: objectFormat.MustIDFromString(secondBranch.CommitID),
ID: git.MustIDFromString(secondBranch.CommitID),
CommitMessage: secondBranch.CommitMessage,
Committer: &git.Signature{
When: secondBranch.CommitTime.AsLocalTime(),

View file

@ -114,7 +114,7 @@ WHEN NOT MATCHED
// GetNextCommitStatusIndex retried 3 times to generate a resource index
func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
_, err := git.IDFromString(sha)
_, err := git.NewIDFromString(sha)
if err != nil {
return 0, git.ErrInvalidSHA{SHA: sha}
}

View file

@ -153,7 +153,7 @@ func GetLastCommitForPaths(ctx context.Context, commit *Commit, treePath string,
if typ != "commit" {
return nil, fmt.Errorf("unexpected type: %s for commit id: %s", typ, commitID)
}
c, err = CommitFromReader(commit.repo, commit.ID.Type().MustIDFromString(commitID), io.LimitReader(batchReader, size))
c, err = CommitFromReader(commit.repo, MustIDFromString(commitID), io.LimitReader(batchReader, size))
if err != nil {
return nil, err
}

View file

@ -71,10 +71,10 @@ readLoop:
switch string(split[0]) {
case "tree":
commit.Tree = *NewTree(gitRepo, objectID.Type().MustIDFromString(string(data)))
commit.Tree = *NewTree(gitRepo, MustIDFromString(string(data)))
_, _ = payloadSB.Write(line)
case "parent":
commit.Parents = append(commit.Parents, objectID.Type().MustIDFromString(string(data)))
commit.Parents = append(commit.Parents, MustIDFromString(string(data)))
_, _ = payloadSB.Write(line)
case "author":
commit.Author = &Signature{}

View file

@ -135,8 +135,8 @@ func TestHasPreviousCommit(t *testing.T) {
commit, err := repo.GetCommit("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0")
assert.NoError(t, err)
parentSHA := repo.objectFormat.MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2")
notParentSHA := repo.objectFormat.MustIDFromString("2839944139e0de9737a044f78b0e4b40d989a9e3")
parentSHA := MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2")
notParentSHA := MustIDFromString("2839944139e0de9737a044f78b0e4b40d989a9e3")
haz, err := commit.HasPreviousCommit(parentSHA)
assert.NoError(t, err)

View file

@ -92,11 +92,7 @@ func (c *LastCommitCache) Get(ref, entryPath string) (*Commit, error) {
// GetCommitByPath gets the last commit for the entry in the provided commit
func (c *LastCommitCache) GetCommitByPath(commitID, entryPath string) (*Commit, error) {
objectFormat, err := c.repo.GetObjectFormat()
if err != nil {
return nil, err
}
sha, err := objectFormat.NewIDFromString(commitID)
sha, err := NewIDFromString(commitID)
if err != nil {
return nil, err
}

View file

@ -6,6 +6,7 @@ package git
import (
"crypto/sha1"
"regexp"
"strconv"
)
// sha1Pattern can be used to determine if a string is an valid sha
@ -20,14 +21,12 @@ type ObjectFormat interface {
EmptyTree() ObjectID
// FullLength is the length of the hash's hex string
FullLength() int
// IsValid returns true if the input is a valid hash
IsValid(input string) bool
// MustID creates a new ObjectID from a byte slice
MustID(b []byte) ObjectID
MustIDFromString(s string) ObjectID
NewID(b []byte) (ObjectID, error)
NewIDFromString(s string) (ObjectID, error)
NewHasher() HasherInterface
// ComputeHash compute the hash for a given ObjectType and content
ComputeHash(t ObjectType, content []byte) ObjectID
}
type Sha1ObjectFormatImpl struct{}
@ -59,20 +58,18 @@ func (Sha1ObjectFormatImpl) MustID(b []byte) ObjectID {
return &id
}
func (h Sha1ObjectFormatImpl) MustIDFromString(s string) ObjectID {
return MustIDFromString(h, s)
}
// ComputeHash compute the hash for a given ObjectType and content
func (h Sha1ObjectFormatImpl) ComputeHash(t ObjectType, content []byte) ObjectID {
hasher := sha1.New()
_, _ = hasher.Write(t.Bytes())
_, _ = hasher.Write([]byte(" "))
_, _ = hasher.Write([]byte(strconv.FormatInt(int64(len(content)), 10)))
_, _ = hasher.Write([]byte{0})
func (h Sha1ObjectFormatImpl) NewID(b []byte) (ObjectID, error) {
return IDFromRaw(h, b)
}
func (h Sha1ObjectFormatImpl) NewIDFromString(s string) (ObjectID, error) {
return genericIDFromString(h, s)
}
func (h Sha1ObjectFormatImpl) NewHasher() HasherInterface {
return &Sha1Hasher{sha1.New()}
// HashSum generates a SHA1 for the provided hash
var sha1 Sha1Hash
copy(sha1[:], hasher.Sum(nil))
return &sha1
}
var Sha1ObjectFormat ObjectFormat = Sha1ObjectFormatImpl{}

View file

@ -6,11 +6,7 @@ package git
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"hash"
"strconv"
"strings"
)
type ObjectID interface {
@ -35,48 +31,36 @@ func (*Sha1Hash) Type() ObjectFormat { return Sha1ObjectFormat }
var _ ObjectID = &Sha1Hash{}
// EmptyObjectID creates a new ObjectID from an object format hash name
func EmptyObjectID(objectFormatName string) (ObjectID, error) {
objectFormat := ObjectFormatFromName(objectFormatName)
if objectFormat != nil {
return objectFormat.EmptyObjectID(), nil
}
return nil, errors.New("unsupported hash type")
}
func IDFromRaw(h ObjectFormat, b []byte) (ObjectID, error) {
if len(b) != h.FullLength()/2 {
return h.EmptyObjectID(), fmt.Errorf("length must be %d: %v", h.FullLength(), b)
}
return h.MustID(b), nil
}
func MustIDFromString(h ObjectFormat, s string) ObjectID {
b, _ := hex.DecodeString(s)
return h.MustID(b)
}
func genericIDFromString(h ObjectFormat, s string) (ObjectID, error) {
s = strings.TrimSpace(s)
if len(s) != h.FullLength() {
return h.EmptyObjectID(), fmt.Errorf("length must be %d: %s", h.FullLength(), s)
}
b, err := hex.DecodeString(s)
func MustIDFromString(hexHash string) ObjectID {
id, err := NewIDFromString(hexHash)
if err != nil {
return h.EmptyObjectID(), err
panic(err)
}
return h.NewID(b)
return id
}
func IDFromString(hexHash string) (ObjectID, error) {
func NewIDFromString(hexHash string) (ObjectID, error) {
var theObjectFormat ObjectFormat
for _, objectFormat := range SupportedObjectFormats {
if len(hexHash) == objectFormat.FullLength() {
return objectFormat.NewIDFromString(hexHash)
theObjectFormat = objectFormat
break
}
}
return nil, fmt.Errorf("invalid hash hex string: '%s' len: %d", hexHash, len(hexHash))
if theObjectFormat == nil {
return nil, fmt.Errorf("length %d has no matched object format: %s", len(hexHash), hexHash)
}
b, err := hex.DecodeString(hexHash)
if err != nil {
return nil, err
}
if len(b) != theObjectFormat.FullLength()/2 {
return theObjectFormat.EmptyObjectID(), fmt.Errorf("length must be %d: %v", theObjectFormat.FullLength(), b)
}
return theObjectFormat.MustID(b), nil
}
func IsEmptyCommitID(commitID string) bool {
@ -84,7 +68,7 @@ func IsEmptyCommitID(commitID string) bool {
return true
}
id, err := IDFromString(commitID)
id, err := NewIDFromString(commitID)
if err != nil {
return false
}
@ -92,37 +76,9 @@ func IsEmptyCommitID(commitID string) bool {
return id.IsZero()
}
// HasherInterface is a struct that will generate a Hash
type HasherInterface interface {
hash.Hash
HashSum() ObjectID
}
type Sha1Hasher struct {
hash.Hash
}
// ComputeBlobHash compute the hash for a given blob content
func ComputeBlobHash(hashType ObjectFormat, content []byte) ObjectID {
return ComputeHash(hashType, ObjectBlob, content)
}
// ComputeHash compute the hash for a given ObjectType and content
func ComputeHash(hashType ObjectFormat, t ObjectType, content []byte) ObjectID {
h := hashType.NewHasher()
_, _ = h.Write(t.Bytes())
_, _ = h.Write([]byte(" "))
_, _ = h.Write([]byte(strconv.FormatInt(int64(len(content)), 10)))
_, _ = h.Write([]byte{0})
return h.HashSum()
}
// HashSum generates a SHA1 for the provided hash
func (h *Sha1Hasher) HashSum() ObjectID {
var sha1 Sha1Hash
copy(sha1[:], h.Hash.Sum(nil))
return &sha1
return hashType.ComputeHash(ObjectBlob, content)
}
type ErrInvalidSHA struct {

View file

@ -57,7 +57,7 @@ func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
}
var err error
entry.ID, err = IDFromString(string(data[pos : pos+hash.Size*2]))
entry.ID, err = NewIDFromString(string(data[pos : pos+hash.Size*2]))
if err != nil {
return nil, fmt.Errorf("invalid ls-tree output: %w", err)
}

View file

@ -28,9 +28,9 @@ func TestParseTreeEntries(t *testing.T) {
Input: "100644 blob 61ab7345a1a3bbc590068ccae37b8515cfc5843c 1022\texample/file2.txt\n",
Expected: []*TreeEntry{
{
ID: Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
ID: MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
gogitTreeEntry: &object.TreeEntry{
Hash: plumbing.Hash(Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Hash: plumbing.Hash(MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Name: "example/file2.txt",
Mode: filemode.Regular,
},
@ -44,9 +44,9 @@ func TestParseTreeEntries(t *testing.T) {
"040000 tree 1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8 -\texample\n",
Expected: []*TreeEntry{
{
ID: Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
ID: MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
gogitTreeEntry: &object.TreeEntry{
Hash: plumbing.Hash(Sha1ObjectFormat.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Hash: plumbing.Hash(MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Name: "example/\n.txt",
Mode: filemode.Symlink,
},
@ -54,10 +54,10 @@ func TestParseTreeEntries(t *testing.T) {
sized: true,
},
{
ID: Sha1ObjectFormat.MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8"),
ID: MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8"),
sized: true,
gogitTreeEntry: &object.TreeEntry{
Hash: plumbing.Hash(Sha1ObjectFormat.MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8").RawValue()),
Hash: plumbing.Hash(MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8").RawValue()),
Name: "example",
Mode: filemode.Dir,
},

View file

@ -72,7 +72,7 @@ func parseTreeEntries(objectFormat ObjectFormat, data []byte, ptree *Tree) ([]*T
return nil, fmt.Errorf("unknown type: %v", string(entryMode))
}
entry.ID, err = objectFormat.NewIDFromString(string(entryObjectID))
entry.ID, err = NewIDFromString(string(entryObjectID))
if err != nil {
return nil, fmt.Errorf("invalid ls-tree output (invalid object id): %q, err: %w", line, err)
}

View file

@ -26,28 +26,28 @@ func TestParseTreeEntriesLong(t *testing.T) {
`,
Expected: []*TreeEntry{
{
ID: objectFormat.MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"),
ID: MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"),
name: "README.md",
entryMode: EntryModeBlob,
size: 8218,
sized: true,
},
{
ID: objectFormat.MustIDFromString("037f27dc9d353ae4fd50f0474b2194c593914e35"),
ID: MustIDFromString("037f27dc9d353ae4fd50f0474b2194c593914e35"),
name: "README_ZH.md",
entryMode: EntryModeBlob,
size: 4681,
sized: true,
},
{
ID: objectFormat.MustIDFromString("9846a94f7e8350a916632929d0fda38c90dd2ca8"),
ID: MustIDFromString("9846a94f7e8350a916632929d0fda38c90dd2ca8"),
name: "SECURITY.md",
entryMode: EntryModeBlob,
size: 429,
sized: true,
},
{
ID: objectFormat.MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"),
ID: MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"),
name: "assets",
entryMode: EntryModeTree,
sized: true,
@ -78,12 +78,12 @@ func TestParseTreeEntriesShort(t *testing.T) {
`,
Expected: []*TreeEntry{
{
ID: objectFormat.MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"),
ID: MustIDFromString("ea0d83c9081af9500ac9f804101b3fd0a5c293af"),
name: "README.md",
entryMode: EntryModeBlob,
},
{
ID: objectFormat.MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"),
ID: MustIDFromString("84b90550547016f73c5dd3f50dea662389e67b6d"),
name: "assets",
entryMode: EntryModeTree,
},

View file

@ -115,11 +115,7 @@ func FindLFSFile(repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, err
continue
case "commit":
// Read in the commit to get its tree and in case this is one of the last used commits
objectFormat, err := repo.GetObjectFormat()
if err != nil {
return nil, err
}
curCommit, err = git.CommitFromReader(repo, objectFormat.MustIDFromString(string(commitID)), io.LimitReader(batchReader, size))
curCommit, err = git.CommitFromReader(repo, git.MustIDFromString(string(commitID)), io.LimitReader(batchReader, size))
if err != nil {
return nil, err
}

View file

@ -81,7 +81,7 @@ func GetObjectFormatOfRepo(ctx context.Context, repoPath string) (ObjectFormat,
return nil, errors.New(stderr.String())
}
h, err := IDFromString(strings.TrimRight(stdout.String(), "\n"))
h, err := NewIDFromString(strings.TrimRight(stdout.String(), "\n"))
if err != nil {
return nil, err
}

View file

@ -5,7 +5,7 @@ package git
// GetBlob finds the blob object in the repository.
func (repo *Repository) GetBlob(idStr string) (*Blob, error) {
id, err := repo.objectFormat.NewIDFromString(idStr)
id, err := NewIDFromString(idStr)
if err != nil {
return nil, err
}

View file

@ -61,7 +61,7 @@ func TestRepository_GetBlob_NoId(t *testing.T) {
defer r.Close()
testCase := ""
testError := fmt.Errorf("length must be 40: %s", testCase)
testError := fmt.Errorf("length %d has no matched object format: %s", len(testCase), testCase)
blob, err := r.GetBlob(testCase)
assert.Nil(t, blob)

View file

@ -63,7 +63,7 @@ func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Com
return nil, runErr
}
id, err := repo.objectFormat.NewIDFromString(stdout)
id, err := NewIDFromString(stdout)
if err != nil {
return nil, err
}
@ -254,7 +254,7 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
}
return commits, err
}
objectID, err := repo.objectFormat.NewIDFromString(string(shaline[0:len]))
objectID, err := NewIDFromString(string(shaline[0:len]))
if err != nil {
return nil, err
}

View file

@ -43,7 +43,7 @@ func (repo *Repository) RemoveReference(name string) error {
func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
objectFormat := repo.objectFormat
if len(commitID) == hash.HexSize && objectFormat.IsValid(commitID) {
ID, err := objectFormat.NewIDFromString(commitID)
ID, err := NewIDFromString(commitID)
if err == nil {
return ID, nil
}
@ -59,7 +59,7 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
return objectFormat.EmptyObjectID(), err
}
return objectFormat.NewIDFromString(actualCommitID)
return NewIDFromString(actualCommitID)
}
// IsCommitExist returns true if given commit exists in current repository.

View file

@ -135,7 +135,7 @@ func (repo *Repository) getCommitFromBatchReader(rd *bufio.Reader, id ObjectID)
func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
IDType := repo.objectFormat
if len(commitID) == IDType.FullLength() && IDType.IsValid(commitID) {
ID, err := repo.objectFormat.NewIDFromString(commitID)
ID, err := NewIDFromString(commitID)
if err == nil {
return ID, nil
}
@ -155,5 +155,5 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
return nil, err
}
return repo.objectFormat.MustIDFromString(string(sha)), nil
return MustIDFromString(string(sha)), nil
}

View file

@ -30,7 +30,7 @@ func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string)
treeish = res[:len(res)-1]
}
}
id, err := objectFormat.NewIDFromString(treeish)
id, err := NewIDFromString(treeish)
if err != nil {
return err
}
@ -128,7 +128,7 @@ func (repo *Repository) WriteTree() (*Tree, error) {
if runErr != nil {
return nil, runErr
}
id, err := repo.objectFormat.NewIDFromString(strings.TrimSpace(stdout))
id, err := NewIDFromString(strings.TrimSpace(stdout))
if err != nil {
return nil, err
}

View file

@ -39,7 +39,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
return nil, ErrNotExist{commitID, ""}
}
sha, err := repo.objectFormat.NewIDFromString(string(shaBytes))
sha, err := NewIDFromString(string(shaBytes))
if err != nil {
log.Debug("Unable to get commit for: %s. Err: %v", commitID, err)
return nil, ErrNotExist{commitID, ""}

View file

@ -46,7 +46,7 @@ func (repo *Repository) GetObjectFormat() (ObjectFormat, error) {
if err != nil {
return nil, err
}
hash, err := IDFromString(str)
hash, err := NewIDFromString(str)
if err != nil {
return nil, err
}
@ -62,7 +62,7 @@ func (repo *Repository) HashObject(reader io.Reader) (ObjectID, error) {
if err != nil {
return nil, err
}
return repo.objectFormat.NewIDFromString(idStr)
return NewIDFromString(idStr)
}
func (repo *Repository) hashObject(reader io.Reader, save bool) (string, error) {

View file

@ -75,7 +75,7 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
if pattern == "" || strings.HasPrefix(refName, pattern) {
r := &Reference{
Name: refName,
Object: repo.objectFormat.MustIDFromString(sha),
Object: MustIDFromString(sha),
Type: typ,
repo: repo,
}

View file

@ -84,7 +84,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) {
return nil, err
}
id, err := repo.objectFormat.NewIDFromString(idStr)
id, err := NewIDFromString(idStr)
if err != nil {
return nil, err
}
@ -98,7 +98,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) {
// GetTagWithID returns a Git tag by given name and ID
func (repo *Repository) GetTagWithID(idStr, name string) (*Tag, error) {
id, err := repo.objectFormat.NewIDFromString(idStr)
id, err := NewIDFromString(idStr)
if err != nil {
return nil, err
}
@ -165,7 +165,7 @@ func parseTagRef(objectFormat ObjectFormat, ref map[string]string) (tag *Tag, er
Name: ref["refname:short"],
}
tag.ID, err = objectFormat.NewIDFromString(ref["objectname"])
tag.ID, err = NewIDFromString(ref["objectname"])
if err != nil {
return nil, fmt.Errorf("parse objectname '%s': %w", ref["objectname"], err)
}
@ -175,7 +175,7 @@ func parseTagRef(objectFormat ObjectFormat, ref map[string]string) (tag *Tag, er
tag.Object = tag.ID
} else {
// annotated tag
tag.Object, err = objectFormat.NewIDFromString(ref["object"])
tag.Object, err = NewIDFromString(ref["object"])
if err != nil {
return nil, fmt.Errorf("parse object '%s': %w", ref["object"], err)
}
@ -208,7 +208,7 @@ func parseTagRef(objectFormat ObjectFormat, ref map[string]string) (tag *Tag, er
// GetAnnotatedTag returns a Git tag by its SHA, must be an annotated tag
func (repo *Repository) GetAnnotatedTag(sha string) (*Tag, error) {
id, err := repo.objectFormat.NewIDFromString(sha)
id, err := NewIDFromString(sha)
if err != nil {
return nil, err
}

View file

@ -88,7 +88,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
// every tag should have a commit ID so return all errors
return nil, err
}
commitID, err := IDFromString(commitIDStr)
commitID, err := NewIDFromString(commitIDStr)
if err != nil {
return nil, err
}

View file

@ -64,7 +64,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
// every tag should have a commit ID so return all errors
return nil, err
}
commitID, err := repo.objectFormat.NewIDFromString(commitIDStr)
commitID, err := NewIDFromString(commitIDStr)
if err != nil {
return nil, err
}

View file

@ -224,8 +224,8 @@ func TestRepository_parseTagRef(t *testing.T) {
want: &Tag{
Name: "v1.9.1",
ID: sha1.MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"),
Object: sha1.MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"),
ID: MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"),
Object: MustIDFromString("ab23e4b7f4cd0caafe0174c0e7ef6d651ba72889"),
Type: "commit",
Tagger: parseAuthorLine(t, "Foo Bar <foo@bar.com> 1565789218 +0300"),
Message: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md\n",
@ -253,8 +253,8 @@ func TestRepository_parseTagRef(t *testing.T) {
want: &Tag{
Name: "v0.0.1",
ID: sha1.MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"),
Object: sha1.MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"),
ID: MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"),
Object: MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"),
Type: "tag",
Tagger: parseAuthorLine(t, "Foo Bar <foo@bar.com> 1565789218 +0300"),
Message: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md\n",
@ -311,8 +311,8 @@ qbHDASXl
want: &Tag{
Name: "v0.0.1",
ID: sha1.MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"),
Object: sha1.MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"),
ID: MustIDFromString("8c68a1f06fc59c655b7e3905b159d761e91c53c9"),
Object: MustIDFromString("3325fd8a973321fd59455492976c042dde3fd1ca"),
Type: "tag",
Tagger: parseAuthorLine(t, "Foo Bar <foo@bar.com> 1565789218 +0300"),
Message: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md",

View file

@ -63,5 +63,5 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt
if err != nil {
return nil, ConcatenateError(err, stderr.String())
}
return repo.objectFormat.NewIDFromString(strings.TrimSpace(stdout.String()))
return NewIDFromString(strings.TrimSpace(stdout.String()))
}

View file

@ -30,7 +30,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
idStr = res[:len(res)-1]
}
}
id, err := repo.objectFormat.NewIDFromString(idStr)
id, err := NewIDFromString(idStr)
if err != nil {
return nil, err
}

View file

@ -75,7 +75,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
idStr = res
}
}
id, err := repo.objectFormat.NewIDFromString(idStr)
id, err := NewIDFromString(idStr)
if err != nil {
return nil, err
}

View file

@ -50,7 +50,7 @@ l:
reftype := line[:spacepos]
switch string(reftype) {
case "object":
id, err := objectFormat.NewIDFromString(string(line[spacepos+1:]))
id, err := NewIDFromString(string(line[spacepos+1:]))
if err != nil {
return nil, err
}

View file

@ -144,7 +144,7 @@ func TestCommitToPushCommit(t *testing.T) {
When: now,
}
const hexString = "0123456789abcdef0123456789abcdef01234567"
sha1, err := git.IDFromString(hexString)
sha1, err := git.NewIDFromString(hexString)
assert.NoError(t, err)
pushCommit := CommitToPushCommit(&git.Commit{
ID: sha1,
@ -169,12 +169,11 @@ func TestListToPushCommits(t *testing.T) {
When: now,
}
hashType := git.Sha1ObjectFormat
const hexString1 = "0123456789abcdef0123456789abcdef01234567"
hash1, err := hashType.NewIDFromString(hexString1)
hash1, err := git.NewIDFromString(hexString1)
assert.NoError(t, err)
const hexString2 = "fedcba9876543210fedcba9876543210fedcba98"
hash2, err := hashType.NewIDFromString(hexString2)
hash2, err := git.NewIDFromString(hexString2)
assert.NoError(t, err)
l := []*git.Commit{

View file

@ -20,13 +20,13 @@ type PushUpdateOptions struct {
// IsNewRef return true if it's a first-time push to a branch, tag or etc.
func (opts *PushUpdateOptions) IsNewRef() bool {
commitID, err := git.IDFromString(opts.OldCommitID)
commitID, err := git.NewIDFromString(opts.OldCommitID)
return err == nil && commitID.IsZero()
}
// IsDelRef return true if it's a deletion to a branch or tag
func (opts *PushUpdateOptions) IsDelRef() bool {
commitID, err := git.IDFromString(opts.NewCommitID)
commitID, err := git.NewIDFromString(opts.NewCommitID)
return err == nil && commitID.IsZero()
}

View file

@ -73,7 +73,7 @@ func searchRefCommitByType(ctx *context.APIContext, refType, filter string) (str
func ConvertToObjectID(ctx gocontext.Context, repo *context.Repository, commitID string) (git.ObjectID, error) {
objectFormat, _ := repo.GitRepo.GetObjectFormat()
if len(commitID) == objectFormat.FullLength() && objectFormat.IsValid(commitID) {
sha, err := objectFormat.NewIDFromString(commitID)
sha, err := git.NewIDFromString(commitID)
if err == nil {
return sha, nil
}

View file

@ -83,8 +83,8 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
_ = stdoutReader.Close()
_ = stdoutWriter.Close()
}()
objectFormat, _ := repo.GetObjectFormat()
commitID := objectFormat.MustIDFromString(sha)
commitID := git.MustIDFromString(sha)
return git.NewCommand(repo.Ctx, "cat-file", "commit").AddDynamicArguments(sha).
Run(&git.RunOpts{

View file

@ -395,7 +395,7 @@ func LFSFileFind(ctx *context.Context) {
objectID = git.ComputeBlobHash(objectFormat, []byte(pointer.StringContent()))
sha = objectID.String()
} else {
objectID = objectFormat.MustIDFromString(sha)
objectID = git.MustIDFromString(sha)
}
ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs"
ctx.Data["Oid"] = oid

View file

@ -115,7 +115,7 @@ func createCommitStatus(ctx context.Context, job *actions_model.ActionRunJob) er
}
creator := user_model.NewActionsUser()
commitID, err := git.IDFromString(sha)
commitID, err := git.NewIDFromString(sha)
if err != nil {
return fmt.Errorf("HashTypeInterfaceFromHashString: %w", err)
}

View file

@ -130,8 +130,6 @@ func (e *errMergeConflict) Error() string {
func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, gitRepo *git.Repository) error {
log.Trace("Attempt to merge:\n%v", file)
objectFormat, _ := gitRepo.GetObjectFormat()
switch {
case file.stage1 != nil && (file.stage2 == nil || file.stage3 == nil):
// 1. Deleted in one or both:
@ -148,7 +146,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
// 2. Added in ours but not in theirs or identical in both
//
// Not a genuine conflict just add to the index
if err := gitRepo.AddObjectToIndex(file.stage2.mode, objectFormat.MustIDFromString(file.stage2.sha), file.stage2.path); err != nil {
if err := gitRepo.AddObjectToIndex(file.stage2.mode, git.MustIDFromString(file.stage2.sha), file.stage2.path); err != nil {
return err
}
return nil
@ -161,7 +159,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
// 4. Added in theirs but not ours:
//
// Not a genuine conflict just add to the index
return gitRepo.AddObjectToIndex(file.stage3.mode, objectFormat.MustIDFromString(file.stage3.sha), file.stage3.path)
return gitRepo.AddObjectToIndex(file.stage3.mode, git.MustIDFromString(file.stage3.sha), file.stage3.path)
case file.stage1 == nil:
// 5. Created by new in both
//
@ -222,7 +220,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g
return err
}
hash = strings.TrimSpace(hash)
return gitRepo.AddObjectToIndex(file.stage2.mode, objectFormat.MustIDFromString(hash), file.stage2.path)
return gitRepo.AddObjectToIndex(file.stage2.mode, git.MustIDFromString(hash), file.stage2.path)
default:
if file.stage1 != nil {
return &errMergeConflict{file.stage1.path}