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.
pull/28527/head^2
Lunny Xiao 11 months ago committed by GitHub
parent 128eac9e0b
commit 4eb2a29910
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      cmd/hook.go
  2. 3
      models/git/branch_test.go
  3. 2
      models/git/commit_status.go
  4. 2
      modules/git/commit_info_nogogit.go
  5. 4
      modules/git/commit_reader.go
  6. 4
      modules/git/commit_test.go
  7. 6
      modules/git/last_commit_cache.go
  8. 37
      modules/git/object_format.go
  9. 88
      modules/git/object_id.go
  10. 2
      modules/git/parse_gogit.go
  11. 12
      modules/git/parse_gogit_test.go
  12. 2
      modules/git/parse_nogogit.go
  13. 12
      modules/git/parse_nogogit_test.go
  14. 6
      modules/git/pipeline/lfs_nogogit.go
  15. 2
      modules/git/repo.go
  16. 2
      modules/git/repo_blob.go
  17. 2
      modules/git/repo_blob_test.go
  18. 4
      modules/git/repo_commit.go
  19. 4
      modules/git/repo_commit_gogit.go
  20. 4
      modules/git/repo_commit_nogogit.go
  21. 4
      modules/git/repo_index.go
  22. 2
      modules/git/repo_language_stats_nogogit.go
  23. 4
      modules/git/repo_object.go
  24. 2
      modules/git/repo_ref_nogogit.go
  25. 10
      modules/git/repo_tag.go
  26. 2
      modules/git/repo_tag_gogit.go
  27. 2
      modules/git/repo_tag_nogogit.go
  28. 12
      modules/git/repo_tag_test.go
  29. 2
      modules/git/repo_tree.go
  30. 2
      modules/git/repo_tree_gogit.go
  31. 2
      modules/git/repo_tree_nogogit.go
  32. 2
      modules/git/tag.go
  33. 7
      modules/repository/commits_test.go
  34. 4
      modules/repository/push.go
  35. 2
      routers/api/v1/utils/git.go
  36. 4
      routers/private/hook_verification.go
  37. 2
      routers/web/repo/setting/lfs.go
  38. 2
      services/actions/commit_status.go
  39. 8
      services/pull/patch.go

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

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

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

@ -153,7 +153,7 @@ func GetLastCommitForPaths(ctx context.Context, commit *Commit, treePath string,
if typ != "commit" { if typ != "commit" {
return nil, fmt.Errorf("unexpected type: %s for commit id: %s", typ, commitID) 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 { if err != nil {
return nil, err return nil, err
} }

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

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

@ -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 // GetCommitByPath gets the last commit for the entry in the provided commit
func (c *LastCommitCache) GetCommitByPath(commitID, entryPath string) (*Commit, error) { func (c *LastCommitCache) GetCommitByPath(commitID, entryPath string) (*Commit, error) {
objectFormat, err := c.repo.GetObjectFormat() sha, err := NewIDFromString(commitID)
if err != nil {
return nil, err
}
sha, err := objectFormat.NewIDFromString(commitID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

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

@ -6,11 +6,7 @@ package git
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"hash"
"strconv"
"strings"
) )
type ObjectID interface { type ObjectID interface {
@ -35,48 +31,36 @@ func (*Sha1Hash) Type() ObjectFormat { return Sha1ObjectFormat }
var _ ObjectID = &Sha1Hash{} var _ ObjectID = &Sha1Hash{}
// EmptyObjectID creates a new ObjectID from an object format hash name func MustIDFromString(hexHash string) ObjectID {
func EmptyObjectID(objectFormatName string) (ObjectID, error) { id, err := NewIDFromString(hexHash)
objectFormat := ObjectFormatFromName(objectFormatName) if err != nil {
if objectFormat != nil { panic(err)
return objectFormat.EmptyObjectID(), nil
} }
return id
return nil, errors.New("unsupported hash type")
} }
func IDFromRaw(h ObjectFormat, b []byte) (ObjectID, error) { func NewIDFromString(hexHash string) (ObjectID, error) {
if len(b) != h.FullLength()/2 { var theObjectFormat ObjectFormat
return h.EmptyObjectID(), fmt.Errorf("length must be %d: %v", h.FullLength(), b) for _, objectFormat := range SupportedObjectFormats {
if len(hexHash) == objectFormat.FullLength() {
theObjectFormat = objectFormat
break
}
} }
return h.MustID(b), nil
}
func MustIDFromString(h ObjectFormat, s string) ObjectID { if theObjectFormat == nil {
b, _ := hex.DecodeString(s) return nil, fmt.Errorf("length %d has no matched object format: %s", len(hexHash), hexHash)
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)
b, err := hex.DecodeString(hexHash)
if err != nil { if err != nil {
return h.EmptyObjectID(), err return nil, err
} }
return h.NewID(b)
}
func IDFromString(hexHash string) (ObjectID, error) { if len(b) != theObjectFormat.FullLength()/2 {
for _, objectFormat := range SupportedObjectFormats { return theObjectFormat.EmptyObjectID(), fmt.Errorf("length must be %d: %v", theObjectFormat.FullLength(), b)
if len(hexHash) == objectFormat.FullLength() {
return objectFormat.NewIDFromString(hexHash)
}
} }
return theObjectFormat.MustID(b), nil
return nil, fmt.Errorf("invalid hash hex string: '%s' len: %d", hexHash, len(hexHash))
} }
func IsEmptyCommitID(commitID string) bool { func IsEmptyCommitID(commitID string) bool {
@ -84,7 +68,7 @@ func IsEmptyCommitID(commitID string) bool {
return true return true
} }
id, err := IDFromString(commitID) id, err := NewIDFromString(commitID)
if err != nil { if err != nil {
return false return false
} }
@ -92,37 +76,9 @@ func IsEmptyCommitID(commitID string) bool {
return id.IsZero() 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 // ComputeBlobHash compute the hash for a given blob content
func ComputeBlobHash(hashType ObjectFormat, content []byte) ObjectID { func ComputeBlobHash(hashType ObjectFormat, content []byte) ObjectID {
return ComputeHash(hashType, ObjectBlob, content) return hashType.ComputeHash(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
} }
type ErrInvalidSHA struct { type ErrInvalidSHA struct {

@ -57,7 +57,7 @@ func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
} }
var err error 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 { if err != nil {
return nil, fmt.Errorf("invalid ls-tree output: %w", err) return nil, fmt.Errorf("invalid ls-tree output: %w", err)
} }

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

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

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

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

@ -81,7 +81,7 @@ func GetObjectFormatOfRepo(ctx context.Context, repoPath string) (ObjectFormat,
return nil, errors.New(stderr.String()) 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 { if err != nil {
return nil, err return nil, err
} }

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

@ -61,7 +61,7 @@ func TestRepository_GetBlob_NoId(t *testing.T) {
defer r.Close() defer r.Close()
testCase := "" 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) blob, err := r.GetBlob(testCase)
assert.Nil(t, blob) assert.Nil(t, blob)

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

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

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

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

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

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

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

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

@ -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 // every tag should have a commit ID so return all errors
return nil, err return nil, err
} }
commitID, err := IDFromString(commitIDStr) commitID, err := NewIDFromString(commitIDStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -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 // every tag should have a commit ID so return all errors
return nil, err return nil, err
} }
commitID, err := repo.objectFormat.NewIDFromString(commitIDStr) commitID, err := NewIDFromString(commitIDStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }

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

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

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

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

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

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

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

@ -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) { func ConvertToObjectID(ctx gocontext.Context, repo *context.Repository, commitID string) (git.ObjectID, error) {
objectFormat, _ := repo.GitRepo.GetObjectFormat() objectFormat, _ := repo.GitRepo.GetObjectFormat()
if len(commitID) == objectFormat.FullLength() && objectFormat.IsValid(commitID) { if len(commitID) == objectFormat.FullLength() && objectFormat.IsValid(commitID) {
sha, err := objectFormat.NewIDFromString(commitID) sha, err := git.NewIDFromString(commitID)
if err == nil { if err == nil {
return sha, nil return sha, nil
} }

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

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

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

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

Loading…
Cancel
Save