Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjust object format interface #28469

Merged
merged 16 commits into from
Dec 17, 2023
3 changes: 2 additions & 1 deletion models/git/branch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ 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: repo.ObjectFormat.MustIDFromString(secondBranch.CommitID),
ID: objectFormat.MustIDFromString(secondBranch.CommitID),
CommitMessage: secondBranch.CommitMessage,
Committer: &git.Signature{
When: secondBranch.CommitTime.AsLocalTime(),
Expand Down
4 changes: 2 additions & 2 deletions models/repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ type Repository struct {
IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"`
CloseIssuesViaCommitInAnyBranch bool `xorm:"NOT NULL DEFAULT false"`
Topics []string `xorm:"TEXT JSON"`
ObjectFormat git.ObjectFormat `xorm:"-"`
ObjectFormatName string `xorm:"-"`

TrustModel TrustModelType

Expand Down Expand Up @@ -277,7 +277,7 @@ func (repo *Repository) AfterLoad() {
repo.NumOpenProjects = repo.NumProjects - repo.NumClosedProjects
repo.NumOpenActionRuns = repo.NumActionRuns - repo.NumClosedActionRuns

repo.ObjectFormat = git.ObjectFormatFromID(git.Sha1)
repo.ObjectFormatName = "sha1"
lunny marked this conversation as resolved.
Show resolved Hide resolved
}

// LoadAttributes loads attributes of the repository.
Expand Down
2 changes: 1 addition & 1 deletion modules/git/blame_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestReadingBlameOutput(t *testing.T) {
}

for _, bypass := range []bool{false, true} {
blameReader, err := CreateBlameReader(ctx, &Sha1ObjectFormat{}, "./tests/repos/repo5_pulls", commit, "README.md", bypass)
blameReader, err := CreateBlameReader(ctx, Sha1ObjectFormat{}, "./tests/repos/repo5_pulls", commit, "README.md", bypass)
assert.NoError(t, err)
assert.NotNil(t, blameReader)
defer blameReader.Close()
Expand Down
63 changes: 27 additions & 36 deletions modules/git/object_format.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@ package git

import (
"crypto/sha1"
"fmt"
"regexp"
"strings"
)

type ObjectFormatID int

const (
Sha1 ObjectFormatID = iota
)

// sha1Pattern can be used to determine if a string is an valid sha
var sha1Pattern = regexp.MustCompile(`^[0-9a-f]{4,40}$`)

const Sha1ObjectFormatName = "sha1"
lunny marked this conversation as resolved.
Show resolved Hide resolved

func IsValidObjectFormat(name string) bool {
switch name {
lunny marked this conversation as resolved.
Show resolved Hide resolved
case Sha1ObjectFormatName:
return true
}
return false
}

type ObjectFormat interface {
ID() ObjectFormatID
String() string

// Empty is the hash of empty git
Expand All @@ -42,60 +43,50 @@ type ObjectFormat interface {

type Sha1ObjectFormat struct{}

func (*Sha1ObjectFormat) ID() ObjectFormatID { return Sha1 }
func (*Sha1ObjectFormat) String() string { return "sha1" }
func (*Sha1ObjectFormat) Empty() ObjectID { return &Sha1Hash{} }
func (*Sha1ObjectFormat) EmptyTree() ObjectID {
func (Sha1ObjectFormat) String() string { return Sha1ObjectFormatName }
func (Sha1ObjectFormat) Empty() ObjectID { return &Sha1Hash{} }
func (Sha1ObjectFormat) EmptyTree() ObjectID {
return &Sha1Hash{
0x4b, 0x82, 0x5d, 0xc6, 0x42, 0xcb, 0x6e, 0xb9, 0xa0, 0x60,
0xe5, 0x4b, 0xf8, 0xd6, 0x92, 0x88, 0xfb, 0xee, 0x49, 0x04,
}
}
func (*Sha1ObjectFormat) FullLength() int { return 40 }
func (*Sha1ObjectFormat) IsValid(input string) bool {
func (Sha1ObjectFormat) FullLength() int { return 40 }
func (Sha1ObjectFormat) IsValid(input string) bool {
return sha1Pattern.MatchString(input)
}

func (*Sha1ObjectFormat) MustID(b []byte) ObjectID {
func (Sha1ObjectFormat) MustID(b []byte) ObjectID {
var id Sha1Hash
copy(id[0:20], b)
return &id
}

func (h *Sha1ObjectFormat) MustIDFromString(s string) ObjectID {
func (h Sha1ObjectFormat) MustIDFromString(s string) ObjectID {
return MustIDFromString(h, s)
}

func (h *Sha1ObjectFormat) NewID(b []byte) (ObjectID, error) {
func (h Sha1ObjectFormat) NewID(b []byte) (ObjectID, error) {
return IDFromRaw(h, b)
}

func (h *Sha1ObjectFormat) NewIDFromString(s string) (ObjectID, error) {
func (h Sha1ObjectFormat) NewIDFromString(s string) (ObjectID, error) {
return genericIDFromString(h, s)
}

func (*Sha1ObjectFormat) NewEmptyID() ObjectID {
func (Sha1ObjectFormat) NewEmptyID() ObjectID {
return NewSha1()
}

func (h *Sha1ObjectFormat) NewHasher() HasherInterface {
func (h Sha1ObjectFormat) NewHasher() HasherInterface {
return &Sha1Hasher{sha1.New()}
}

func ObjectFormatFromID(id ObjectFormatID) ObjectFormat {
switch id {
case Sha1:
return &Sha1ObjectFormat{}
}

return nil
}

func ObjectFormatFromString(hash string) (ObjectFormat, error) {
switch strings.ToLower(hash) {
case "sha1":
return &Sha1ObjectFormat{}, nil
func ObjectFormatFromName(name string) ObjectFormat {
switch name {
case Sha1ObjectFormatName:
return Sha1ObjectFormat{}
default:
return nil
}

return nil, fmt.Errorf("unknown hash type: %s", hash)
}
4 changes: 2 additions & 2 deletions modules/git/object_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (h *Sha1Hash) IsZero() bool {
return bytes.Equal(empty[:], h[:])
}
func (h *Sha1Hash) RawValue() []byte { return h[:] }
func (*Sha1Hash) Type() ObjectFormat { return &Sha1ObjectFormat{} }
func (*Sha1Hash) Type() ObjectFormat { return Sha1ObjectFormat{} }

func NewSha1() *Sha1Hash {
return &Sha1Hash{}
Expand All @@ -41,7 +41,7 @@ func NewSha1() *Sha1Hash {
func NewHash(hash string) (ObjectID, error) {
hash = strings.ToLower(hash)
switch hash {
case "sha1":
case Sha1ObjectFormatName:
return &Sha1Hash{}, nil
}

Expand Down
2 changes: 1 addition & 1 deletion modules/git/object_id_gogit.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
func ParseGogitHash(h plumbing.Hash) ObjectID {
switch hash.Size {
case 20:
return ObjectFormatFromID(Sha1).MustID(h[:])
return Sha1ObjectFormat{}.MustID(h[:])
}

return nil
Expand Down
14 changes: 7 additions & 7 deletions modules/git/parse_gogit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ func TestParseTreeEntries(t *testing.T) {
Input: "100644 blob 61ab7345a1a3bbc590068ccae37b8515cfc5843c 1022\texample/file2.txt\n",
Expected: []*TreeEntry{
{
ID: ObjectFormatFromID(Sha1).MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
ID: Sha1ObjectFormat{}.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
gogitTreeEntry: &object.TreeEntry{
Hash: plumbing.Hash(ObjectFormatFromID(Sha1).MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Hash: plumbing.Hash(Sha1ObjectFormat{}.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Name: "example/file2.txt",
Mode: filemode.Regular,
},
Expand All @@ -44,20 +44,20 @@ func TestParseTreeEntries(t *testing.T) {
"040000 tree 1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8 -\texample\n",
Expected: []*TreeEntry{
{
ID: ObjectFormatFromID(Sha1).MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
ID: Sha1ObjectFormat{}.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c"),
gogitTreeEntry: &object.TreeEntry{
Hash: plumbing.Hash(ObjectFormatFromID(Sha1).MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Hash: plumbing.Hash(Sha1ObjectFormat{}.MustIDFromString("61ab7345a1a3bbc590068ccae37b8515cfc5843c").RawValue()),
Name: "example/\n.txt",
Mode: filemode.Symlink,
},
size: 234131,
sized: true,
},
{
ID: ObjectFormatFromID(Sha1).MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8"),
ID: Sha1ObjectFormat{}.MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8"),
sized: true,
gogitTreeEntry: &object.TreeEntry{
Hash: plumbing.Hash(ObjectFormatFromID(Sha1).MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8").RawValue()),
Hash: plumbing.Hash(Sha1ObjectFormat{}.MustIDFromString("1d01fb729fb0db5881daaa6030f9f2d3cd3d5ae8").RawValue()),
Name: "example",
Mode: filemode.Dir,
},
Expand All @@ -67,7 +67,7 @@ func TestParseTreeEntries(t *testing.T) {
}

for _, testCase := range testCases {
entries, err := ParseTreeEntries(ObjectFormatFromID(Sha1), []byte(testCase.Input))
entries, err := ParseTreeEntries(Sha1ObjectFormat{}, []byte(testCase.Input))
assert.NoError(t, err)
if len(entries) > 1 {
fmt.Println(testCase.Expected[0].ID)
Expand Down
6 changes: 3 additions & 3 deletions modules/git/parse_nogogit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

func TestParseTreeEntriesLong(t *testing.T) {
objectFormat := ObjectFormatFromID(Sha1)
objectFormat := Sha1ObjectFormat{}

testCases := []struct {
Input string
Expand Down Expand Up @@ -66,7 +66,7 @@ func TestParseTreeEntriesLong(t *testing.T) {
}

func TestParseTreeEntriesShort(t *testing.T) {
objectFormat := ObjectFormatFromID(Sha1)
objectFormat := Sha1ObjectFormat{}

testCases := []struct {
Input string
Expand Down Expand Up @@ -102,7 +102,7 @@ func TestParseTreeEntriesShort(t *testing.T) {

func TestParseTreeEntriesInvalid(t *testing.T) {
// there was a panic: "runtime error: slice bounds out of range" when the input was invalid: #20315
entries, err := ParseTreeEntries(ObjectFormatFromID(Sha1), []byte("100644 blob ea0d83c9081af9500ac9f804101b3fd0a5c293af"))
entries, err := ParseTreeEntries(Sha1ObjectFormat{}, []byte("100644 blob ea0d83c9081af9500ac9f804101b3fd0a5c293af"))
assert.Error(t, err)
assert.Len(t, entries, 0)
}
2 changes: 1 addition & 1 deletion modules/git/ref.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ func RefURL(repoURL, ref string) string {
return repoURL + "/src/branch/" + refName
case refFullName.IsTag():
return repoURL + "/src/tag/" + refName
case !ObjectFormatFromID(Sha1).IsValid(ref):
case !Sha1ObjectFormat{}.IsValid(ref):
// assume they mean a branch
return repoURL + "/src/branch/" + refName
default:
Expand Down
10 changes: 8 additions & 2 deletions modules/git/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,21 @@ func GetObjectFormatOfRepo(ctx context.Context, repoPath string) (ObjectFormat,
}

// InitRepository initializes a new Git repository.
func InitRepository(ctx context.Context, repoPath string, bare bool, objectFormat ObjectFormat) error {
func InitRepository(ctx context.Context, repoPath string, bare bool, objectFormatName string) error {
err := os.MkdirAll(repoPath, os.ModePerm)
if err != nil {
return err
}

cmd := NewCommand(ctx, "init")
if SupportHashSha256 {
cmd.AddOptionValues("--object-format", objectFormat.String())
if objectFormatName == "" {
objectFormatName = Sha1ObjectFormatName
}
if !IsValidObjectFormat(objectFormatName) {
return fmt.Errorf("invalid object format: %s", objectFormatName)
}
cmd.AddOptionValues("--object-format", objectFormatName)
}
if bare {
cmd.AddArguments("--bare")
Expand Down
2 changes: 1 addition & 1 deletion modules/git/repo_tag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
}

func TestRepository_parseTagRef(t *testing.T) {
sha1 := ObjectFormatFromID(Sha1)
sha1 := Sha1ObjectFormat{}
tests := []struct {
name string

Expand Down
2 changes: 1 addition & 1 deletion modules/git/tag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ ono`), tag: Tag{
}

for _, test := range testData {
tag, err := parseTagData(ObjectFormatFromID(Sha1), test.data)
tag, err := parseTagData(Sha1ObjectFormat{}, test.data)
assert.NoError(t, err)
assert.EqualValues(t, test.tag.ID, tag.ID)
assert.EqualValues(t, test.tag.Object, tag.Object)
Expand Down
2 changes: 1 addition & 1 deletion modules/repository/commits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func TestListToPushCommits(t *testing.T) {
When: now,
}

hashType := git.ObjectFormatFromID(git.Sha1)
hashType := git.Sha1ObjectFormat{}
const hexString1 = "0123456789abcdef0123456789abcdef01234567"
hash1, err := hashType.NewIDFromString(hexString1)
assert.NoError(t, err)
Expand Down
4 changes: 2 additions & 2 deletions modules/repository/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *r
}

// FIXME: fix the hash
if err := git.InitRepository(ctx, tmpDir, false, git.ObjectFormatFromID(git.Sha1)); err != nil {
if err := git.InitRepository(ctx, tmpDir, false, git.Sha1ObjectFormat{}.String()); err != nil {
return err
}

Expand Down Expand Up @@ -358,7 +358,7 @@ func GenerateRepository(ctx context.Context, doer, owner *user_model.User, templ
}

// FIXME - fix the hash
if err = CheckInitRepository(ctx, owner.Name, generateRepo.Name, git.ObjectFormatFromID(git.Sha1)); err != nil {
if err = CheckInitRepository(ctx, owner.Name, generateRepo.Name, git.Sha1ObjectFormat{}.String()); err != nil {
return generateRepo, err
}

Expand Down
4 changes: 2 additions & 2 deletions modules/repository/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func InitRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi
return nil
}

func CheckInitRepository(ctx context.Context, owner, name string, objectFormat git.ObjectFormat) (err error) {
func CheckInitRepository(ctx context.Context, owner, name, objectFormatName string) (err error) {
// Somehow the directory could exist.
repoPath := repo_model.RepoPath(owner, name)
isExist, err := util.IsExist(repoPath)
Expand All @@ -204,7 +204,7 @@ func CheckInitRepository(ctx context.Context, owner, name string, objectFormat g
}

// Init git bare new repository.
if err = git.InitRepository(ctx, repoPath, true, objectFormat); err != nil {
if err = git.InitRepository(ctx, repoPath, true, objectFormatName); err != nil {
return fmt.Errorf("git.InitRepository: %w", err)
} else if err = CreateDelegateHooks(repoPath); err != nil {
return fmt.Errorf("createDelegateHooks: %w", err)
Expand Down
24 changes: 12 additions & 12 deletions routers/api/v1/repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,18 +242,18 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre
}

repo, err := repo_service.CreateRepository(ctx, ctx.Doer, owner, repo_service.CreateRepoOptions{
Name: opt.Name,
Description: opt.Description,
IssueLabels: opt.IssueLabels,
Gitignores: opt.Gitignores,
License: opt.License,
Readme: opt.Readme,
IsPrivate: opt.Private,
AutoInit: opt.AutoInit,
DefaultBranch: opt.DefaultBranch,
TrustModel: repo_model.ToTrustModel(opt.TrustModel),
IsTemplate: opt.Template,
ObjectFormat: git.ObjectFormatFromID(git.Sha1),
Name: opt.Name,
Description: opt.Description,
IssueLabels: opt.IssueLabels,
Gitignores: opt.Gitignores,
License: opt.License,
Readme: opt.Readme,
IsPrivate: opt.Private,
AutoInit: opt.AutoInit,
DefaultBranch: opt.DefaultBranch,
TrustModel: repo_model.ToTrustModel(opt.TrustModel),
IsTemplate: opt.Template,
ObjectFormatName: git.Sha1ObjectFormatName,
})
if err != nil {
if repo_model.IsErrRepoAlreadyExist(err) {
Expand Down
2 changes: 1 addition & 1 deletion routers/web/repo/githttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ func dummyInfoRefs(ctx *context.Context) {
}
}()

if err := git.InitRepository(ctx, tmpDir, true, git.ObjectFormatFromID(git.Sha1)); err != nil {
if err := git.InitRepository(ctx, tmpDir, true, git.Sha1ObjectFormatName); err != nil {
log.Error("Failed to init bare repo for git-receive-pack cache: %v", err)
return
}
Expand Down
Loading
Loading