refactor: remove Ctx field from git.Repository (#38500)

This commit is contained in:
wxiaoguang
2026-07-17 18:44:31 +08:00
committed by GitHub
parent 2c8e99bbf7
commit 5b078f72aa
235 changed files with 1234 additions and 1258 deletions
+1 -1
View File
@@ -129,7 +129,7 @@ func runRepoSyncReleases(ctx context.Context, _ *cli.Command) error {
log.Trace("Processing next %d repos of %d", len(repos), count) log.Trace("Processing next %d repos of %d", len(repos), count)
for _, repo := range repos { for _, repo := range repos {
log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RelativePath()) log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RelativePath())
gitRepo, err := gitrepo.OpenRepository(ctx, repo) gitRepo, err := gitrepo.OpenRepository(repo)
if err != nil { if err != nil {
log.Warn("OpenRepository: %v", err) log.Warn("OpenRepository: %v", err)
continue continue
+2 -2
View File
@@ -73,7 +73,7 @@ func GetActivityStats(ctx context.Context, repo *repo_model.Repository, timeFrom
} }
defer closer.Close() defer closer.Close()
code, err := gitRepo.GetCodeActivityStats(timeFrom, repo.DefaultBranch) code, err := gitRepo.GetCodeActivityStats(ctx, timeFrom, repo.DefaultBranch)
if err != nil { if err != nil {
return nil, fmt.Errorf("FillFromGit: %w", err) return nil, fmt.Errorf("FillFromGit: %w", err)
} }
@@ -90,7 +90,7 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository
} }
defer closer.Close() defer closer.Close()
code, err := gitRepo.GetCodeActivityStats(timeFrom, "") code, err := gitRepo.GetCodeActivityStats(ctx, timeFrom, "")
if err != nil { if err != nil {
return nil, fmt.Errorf("FillFromGit: %w", err) return nil, fmt.Errorf("FillFromGit: %w", err)
} }
+2 -2
View File
@@ -186,11 +186,11 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo2) gitRepo, err := gitrepo.OpenRepository(repo2)
assert.NoError(t, err) assert.NoError(t, err)
defer gitRepo.Close() defer gitRepo.Close()
commit, err := gitRepo.GetBranchCommit(repo2.DefaultBranch) commit, err := gitRepo.GetBranchCommit(t.Context(), repo2.DefaultBranch)
assert.NoError(t, err) assert.NoError(t, err)
defer func() { defer func() {
+3 -3
View File
@@ -108,14 +108,14 @@ func FixPublisherIDforTagReleases(ctx context.Context, x db.EngineMigration) err
return err return err
} }
} }
gitRepo, err = git.OpenRepository(ctx, repoPath(repo.OwnerName, repo.Name)) gitRepo, err = git.OpenRepository(repoPath(repo.OwnerName, repo.Name))
if err != nil { if err != nil {
log.Error("Error whilst opening git repo for [%d]%s/%s. Error: %v", repo.ID, repo.OwnerName, repo.Name, err) log.Error("Error whilst opening git repo for [%d]%s/%s. Error: %v", repo.ID, repo.OwnerName, repo.Name, err)
return err return err
} }
} }
commit, err := gitRepo.GetTagCommit(release.TagName) commit, err := gitRepo.GetTagCommit(ctx, release.TagName)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
log.Warn("Unable to find commit %s for Tag: %s in [%d]%s/%s. Cannot update publisher ID.", err.(git.ErrNotExist).ID, release.TagName, repo.ID, repo.OwnerName, repo.Name) log.Warn("Unable to find commit %s for Tag: %s in [%d]%s/%s. Cannot update publisher ID.", err.(git.ErrNotExist).ID, release.TagName, repo.ID, repo.OwnerName, repo.Name)
@@ -127,7 +127,7 @@ func FixPublisherIDforTagReleases(ctx context.Context, x db.EngineMigration) err
if commit.Author.Email == "" { if commit.Author.Email == "" {
log.Warn("Tag: %s in Repo[%d]%s/%s does not have a tagger.", release.TagName, repo.ID, repo.OwnerName, repo.Name) log.Warn("Tag: %s in Repo[%d]%s/%s does not have a tagger.", release.TagName, repo.ID, repo.OwnerName, repo.Name)
commit, err = gitRepo.GetCommit(commit.ID.String()) commit, err = gitRepo.GetCommit(ctx, commit.ID.String())
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
log.Warn("Unable to find commit %s for Tag: %s in [%d]%s/%s. Cannot update publisher ID.", err.(git.ErrNotExist).ID, release.TagName, repo.ID, repo.OwnerName, repo.Name) log.Warn("Unable to find commit %s for Tag: %s in [%d]%s/%s. Cannot update publisher ID.", err.(git.ErrNotExist).ID, release.TagName, repo.ID, repo.OwnerName, repo.Name)
+2 -2
View File
@@ -87,7 +87,7 @@ func FixReleaseSha1OnReleaseTable(ctx context.Context, x db.EngineMigration) err
userCache[repo.OwnerID] = user userCache[repo.OwnerID] = user
} }
gitRepo, err = gitrepo.OpenRepository(ctx, repo_model.StorageRepo(repo_model.RelativePath(user.Name, repo.Name))) gitRepo, err = gitrepo.OpenRepository(repo_model.StorageRepo(repo_model.RelativePath(user.Name, repo.Name)))
if err != nil { if err != nil {
return err return err
} }
@@ -95,7 +95,7 @@ func FixReleaseSha1OnReleaseTable(ctx context.Context, x db.EngineMigration) err
gitRepoCache[release.RepoID] = gitRepo gitRepoCache[release.RepoID] = gitRepo
} }
release.Sha1, err = gitRepo.GetTagCommitID(release.TagName) release.Sha1, err = gitRepo.GetTagCommitID(ctx, release.TagName)
if err != nil && !git.IsErrNotExist(err) { if err != nil && !git.IsErrNotExist(err) {
return err return err
} }
+2 -2
View File
@@ -41,13 +41,13 @@ func (c *commitChecker) IsCommitIDExisting(commitID string) bool {
if c.gitRepo == nil { if c.gitRepo == nil {
r, closer, err := gitrepo.RepositoryFromContextOrOpen(c.ctx, c.gitRepoFacade) r, closer, err := gitrepo.RepositoryFromContextOrOpen(c.ctx, c.gitRepoFacade)
if err != nil { if err != nil {
log.Error("unable to open repository: %s Error: %v", gitrepo.RepoGitURL(c.gitRepoFacade), err) log.Error("Unable to open repository: %s Error: %v", c.gitRepoFacade.RelativePath(), err)
return false return false
} }
c.gitRepo, c.gitRepoCloser = r, closer c.gitRepo, c.gitRepoCloser = r, closer
} }
exist = c.gitRepo.IsReferenceExist(commitID) // Don't use IsObjectExist since it doesn't support short hashes with gogit edition. exist = c.gitRepo.IsReferenceExist(c.ctx, commitID) // Don't use IsObjectExist since it doesn't support short hashes with gogit edition.
c.commitCache[commitID] = exist c.commitCache[commitID] = exist
return exist return exist
} }
+3 -2
View File
@@ -36,7 +36,7 @@ func ParseScopedWorkflows(ctx context.Context, gitRepo *git.Repository, sourceCo
parsed := make([]*ParsedScopedWorkflow, 0, len(entries)) parsed := make([]*ParsedScopedWorkflow, 0, len(entries))
for _, entry := range entries { for _, entry := range entries {
content, err := GetContentFromEntry(gitRepo, entry) content, err := GetContentFromEntry(ctx, gitRepo, entry)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -60,6 +60,7 @@ func ParseScopedWorkflows(ctx context.Context, gitRepo *git.Repository, sourceCo
// MatchScopedWorkflows evaluates already-parsed scoped workflows against one consuming event. // MatchScopedWorkflows evaluates already-parsed scoped workflows against one consuming event.
// It returns the workflows whose `on:` matches, and those that matched the event but were excluded by a branch/paths filter (filtered). // It returns the workflows whose `on:` matches, and those that matched the event but were excluded by a branch/paths filter (filtered).
func MatchScopedWorkflows( func MatchScopedWorkflows(
ctx context.Context,
parsed []*ParsedScopedWorkflow, parsed []*ParsedScopedWorkflow,
consumerGitRepo *git.Repository, consumerGitRepo *git.Repository,
consumerCommit *git.Commit, consumerCommit *git.Commit,
@@ -77,7 +78,7 @@ func MatchScopedWorkflows(
TriggerEvent: evt, TriggerEvent: evt,
Content: p.Content, Content: p.Content,
} }
switch detectWorkflowMatch(consumerGitRepo, consumerCommit, triggedEvent, payload, evt) { switch detectWorkflowMatch(ctx, consumerGitRepo, consumerCommit, triggedEvent, payload, evt) {
case detectMatched: case detectMatched:
matched = append(matched, dwf) matched = append(matched, dwf)
case detectFilteredOut: case detectFilteredOut:
+15 -15
View File
@@ -105,8 +105,8 @@ func listWorkflowsInDirs(ctx context.Context, gitRepo *git.Repository, commit *g
return workflowDir, ret, nil return workflowDir, ret, nil
} }
func GetContentFromEntry(gitRepo *git.Repository, entry *git.TreeEntry) ([]byte, error) { func GetContentFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry) ([]byte, error) {
f, err := entry.Blob(gitRepo).DataAsync() f, err := entry.Blob(gitRepo).DataAsync(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -189,7 +189,7 @@ func DetectWorkflows(
} }
for _, entry := range entries { for _, entry := range entries {
content, err := GetContentFromEntry(gitRepo, entry) content, err := GetContentFromEntry(ctx, gitRepo, entry)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -217,7 +217,7 @@ func DetectWorkflows(
TriggerEvent: evt, TriggerEvent: evt,
Content: content, Content: content,
} }
switch detectWorkflowMatch(gitRepo, commit, triggedEvent, payload, evt) { switch detectWorkflowMatch(ctx, gitRepo, commit, triggedEvent, payload, evt) {
case detectMatched: case detectMatched:
workflows = append(workflows, dwf) workflows = append(workflows, dwf)
case detectFilteredOut: case detectFilteredOut:
@@ -239,7 +239,7 @@ func DetectScheduledWorkflows(ctx context.Context, gitRepo *git.Repository, comm
wfs := make([]*DetectedWorkflow, 0, len(entries)) wfs := make([]*DetectedWorkflow, 0, len(entries))
for _, entry := range entries { for _, entry := range entries {
content, err := GetContentFromEntry(gitRepo, entry) content, err := GetContentFromEntry(ctx, gitRepo, entry)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -266,7 +266,7 @@ func DetectScheduledWorkflows(ctx context.Context, gitRepo *git.Repository, comm
return wfs, nil return wfs, nil
} }
func detectWorkflowMatch(gitRepo *git.Repository, commit *git.Commit, triggedEvent webhook_module.HookEventType, payload api.Payloader, evt *jobparser.Event) detectResult { func detectWorkflowMatch(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, triggedEvent webhook_module.HookEventType, payload api.Payloader, evt *jobparser.Event) detectResult {
if !canGithubEventMatch(evt.Name, triggedEvent) { if !canGithubEventMatch(evt.Name, triggedEvent) {
return detectNotApplicable return detectNotApplicable
} }
@@ -286,7 +286,7 @@ func detectWorkflowMatch(gitRepo *git.Repository, commit *git.Commit, triggedEve
case // push case // push
webhook_module.HookEventPush: webhook_module.HookEventPush:
return matchPushEvent(gitRepo, commit, payload.(*api.PushPayload), evt) return matchPushEvent(ctx, gitRepo, commit, payload.(*api.PushPayload), evt)
case // issues case // issues
webhook_module.HookEventIssues, webhook_module.HookEventIssues,
@@ -315,7 +315,7 @@ func detectWorkflowMatch(gitRepo *git.Repository, commit *git.Commit, triggedEve
webhook_module.HookEventPullRequestLabel, webhook_module.HookEventPullRequestLabel,
webhook_module.HookEventPullRequestReviewRequest, webhook_module.HookEventPullRequestReviewRequest,
webhook_module.HookEventPullRequestMilestone: webhook_module.HookEventPullRequestMilestone:
return matchPullRequestEvent(gitRepo, commit, payload.(*api.PullRequestPayload), evt) return matchPullRequestEvent(ctx, gitRepo, commit, payload.(*api.PullRequestPayload), evt)
case // pull_request_review case // pull_request_review
webhook_module.HookEventPullRequestReviewApproved, webhook_module.HookEventPullRequestReviewApproved,
@@ -359,7 +359,7 @@ func detectWorkflowMatch(gitRepo *git.Repository, commit *git.Commit, triggedEve
} }
} }
func matchPushEvent(gitRepo *git.Repository, commit *git.Commit, pushPayload *api.PushPayload, evt *jobparser.Event) detectResult { func matchPushEvent(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, pushPayload *api.PushPayload, evt *jobparser.Event) detectResult {
// with no special filter parameters // with no special filter parameters
if len(evt.Acts()) == 0 { if len(evt.Acts()) == 0 {
return detectMatched return detectMatched
@@ -425,7 +425,7 @@ func matchPushEvent(gitRepo *git.Repository, commit *git.Commit, pushPayload *ap
matchTimes++ matchTimes++
break break
} }
filesChanged, err := commit.GetFilesChangedSinceCommit(gitRepo, pushPayload.Before) filesChanged, err := commit.GetFilesChangedSinceCommit(ctx, gitRepo, pushPayload.Before)
if err != nil { if err != nil {
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err) log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err)
return detectNotApplicable return detectNotApplicable
@@ -442,7 +442,7 @@ func matchPushEvent(gitRepo *git.Repository, commit *git.Commit, pushPayload *ap
matchTimes++ matchTimes++
break break
} }
filesChanged, err := commit.GetFilesChangedSinceCommit(gitRepo, pushPayload.Before) filesChanged, err := commit.GetFilesChangedSinceCommit(ctx, gitRepo, pushPayload.Before)
if err != nil { if err != nil {
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err) log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err)
return detectNotApplicable return detectNotApplicable
@@ -516,7 +516,7 @@ func matchIssuesEvent(issuePayload *api.IssuePayload, evt *jobparser.Event) bool
return matchTimes == len(evt.Acts()) return matchTimes == len(evt.Acts())
} }
func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayload *api.PullRequestPayload, evt *jobparser.Event) detectResult { func matchPullRequestEvent(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, prPayload *api.PullRequestPayload, evt *jobparser.Event) detectResult {
acts := evt.Acts() acts := evt.Acts()
activityTypeMatched := false activityTypeMatched := false
matchTimes := 0 matchTimes := 0
@@ -560,7 +560,7 @@ func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayloa
err error err error
) )
if evt.Name == GithubEventPullRequestTarget && (len(acts["paths"]) > 0 || len(acts["paths-ignore"]) > 0) { if evt.Name == GithubEventPullRequestTarget && (len(acts["paths"]) > 0 || len(acts["paths-ignore"]) > 0) {
headCommit, err = gitRepo.GetCommit(prPayload.PullRequest.Head.Sha) headCommit, err = gitRepo.GetCommit(ctx, prPayload.PullRequest.Head.Sha)
if err != nil { if err != nil {
log.Error("GetCommit [ref: %s]: %v", prPayload.PullRequest.Head.Sha, err) log.Error("GetCommit [ref: %s]: %v", prPayload.PullRequest.Head.Sha, err)
return detectNotApplicable return detectNotApplicable
@@ -592,7 +592,7 @@ func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayloa
matchTimes++ matchTimes++
} }
case "paths": case "paths":
filesChanged, err := headCommit.GetFilesChangedSinceCommit(gitRepo, prPayload.PullRequest.MergeBase) filesChanged, err := headCommit.GetFilesChangedSinceCommit(ctx, gitRepo, prPayload.PullRequest.MergeBase)
if err != nil { if err != nil {
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err) log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err)
return detectNotApplicable return detectNotApplicable
@@ -605,7 +605,7 @@ func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayloa
matchTimes++ matchTimes++
} }
case "paths-ignore": case "paths-ignore":
filesChanged, err := headCommit.GetFilesChangedSinceCommit(gitRepo, prPayload.PullRequest.MergeBase) filesChanged, err := headCommit.GetFilesChangedSinceCommit(ctx, gitRepo, prPayload.PullRequest.MergeBase)
if err != nil { if err != nil {
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err) log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err)
return detectNotApplicable return detectNotApplicable
+1 -1
View File
@@ -243,7 +243,7 @@ func TestDetectMatched(t *testing.T) {
evts, err := GetEventsFromContent(fullWorkflowContent(tc.yamlOn)) evts, err := GetEventsFromContent(fullWorkflowContent(tc.yamlOn))
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, evts, 1) assert.Len(t, evts, 1)
assert.Equal(t, tc.expected, detectWorkflowMatch(nil, tc.commit, tc.triggedEvent, tc.payload, evts[0])) assert.Equal(t, tc.expected, detectWorkflowMatch(t.Context(), nil, tc.commit, tc.triggedEvent, tc.payload, evts[0]))
}) })
} }
} }
+3 -3
View File
@@ -29,15 +29,15 @@ type BatchChecker struct {
// NewBatchChecker creates a check attribute reader for the current repository and provided commit ID // NewBatchChecker creates a check attribute reader for the current repository and provided commit ID
// If treeish is empty, then it will use current working directory, otherwise it will use the provided treeish on the bare repo // If treeish is empty, then it will use current working directory, otherwise it will use the provided treeish on the bare repo
func NewBatchChecker(repo *git.Repository, treeish string, attributes []string) (checker *BatchChecker, returnedErr error) { func NewBatchChecker(ctx context.Context, repo *git.Repository, treeish string, attributes []string) (checker *BatchChecker, returnedErr error) {
ctx, cancel := context.WithCancel(repo.Ctx) ctx, cancel := context.WithCancel(ctx)
defer func() { defer func() {
if returnedErr != nil { if returnedErr != nil {
cancel() cancel()
} }
}() }()
cmd, envs, cleanup, err := checkAttrCommand(repo, treeish, nil, attributes) cmd, envs, cleanup, err := checkAttrCommand(ctx, repo, treeish, nil, attributes)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+6 -5
View File
@@ -118,7 +118,8 @@ func expectedAttrs() *Attributes {
func Test_BatchChecker(t *testing.T) { func Test_BatchChecker(t *testing.T) {
setting.AppDataPath = t.TempDir() setting.AppDataPath = t.TempDir()
repoPath := "../tests/repos/language_stats_repo" repoPath := "../tests/repos/language_stats_repo"
gitRepo, err := git.OpenRepository(t.Context(), repoPath) ctx := t.Context()
gitRepo, err := git.OpenRepository(repoPath)
require.NoError(t, err) require.NoError(t, err)
defer gitRepo.Close() defer gitRepo.Close()
@@ -126,7 +127,7 @@ func Test_BatchChecker(t *testing.T) {
t.Run("Create index file to run git check-attr", func(t *testing.T) { t.Run("Create index file to run git check-attr", func(t *testing.T) {
defer test.MockVariableValue(&git.DefaultFeatures().SupportCheckAttrOnBare, false)() defer test.MockVariableValue(&git.DefaultFeatures().SupportCheckAttrOnBare, false)()
checker, err := NewBatchChecker(gitRepo, commitID, LinguistAttributes) checker, err := NewBatchChecker(ctx, gitRepo, commitID, LinguistAttributes)
assert.NoError(t, err) assert.NoError(t, err)
defer checker.Close() defer checker.Close()
attributes, err := checker.CheckPath("i-am-a-python.p") attributes, err := checker.CheckPath("i-am-a-python.p")
@@ -143,11 +144,11 @@ func Test_BatchChecker(t *testing.T) {
}) })
assert.NoError(t, err) assert.NoError(t, err)
tempRepo, err := git.OpenRepository(t.Context(), dir) tempRepo, err := git.OpenRepository(dir)
assert.NoError(t, err) assert.NoError(t, err)
defer tempRepo.Close() defer tempRepo.Close()
checker, err := NewBatchChecker(tempRepo, "", LinguistAttributes) checker, err := NewBatchChecker(t.Context(), tempRepo, "", LinguistAttributes)
assert.NoError(t, err) assert.NoError(t, err)
defer checker.Close() defer checker.Close()
attributes, err := checker.CheckPath("i-am-a-python.p") attributes, err := checker.CheckPath("i-am-a-python.p")
@@ -161,7 +162,7 @@ func Test_BatchChecker(t *testing.T) {
} }
t.Run("Run git check-attr in bare repository", func(t *testing.T) { t.Run("Run git check-attr in bare repository", func(t *testing.T) {
checker, err := NewBatchChecker(gitRepo, commitID, LinguistAttributes) checker, err := NewBatchChecker(ctx, gitRepo, commitID, LinguistAttributes)
assert.NoError(t, err) assert.NoError(t, err)
defer checker.Close() defer checker.Close()
+3 -3
View File
@@ -14,7 +14,7 @@ import (
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/git/gitcmd"
) )
func checkAttrCommand(gitRepo *git.Repository, treeish string, filenames, attributes []string) (*gitcmd.Command, []string, func(), error) { func checkAttrCommand(ctx context.Context, gitRepo *git.Repository, treeish string, filenames, attributes []string) (*gitcmd.Command, []string, func(), error) {
cancel := func() {} cancel := func() {}
envs := []string{"GIT_FLUSH=1"} envs := []string{"GIT_FLUSH=1"}
cmd := gitcmd.NewCommand("check-attr", "-z") cmd := gitcmd.NewCommand("check-attr", "-z")
@@ -28,7 +28,7 @@ func checkAttrCommand(gitRepo *git.Repository, treeish string, filenames, attrib
cmd.AddArguments("--source") cmd.AddArguments("--source")
cmd.AddDynamicArguments(treeish) cmd.AddDynamicArguments(treeish)
} else { } else {
indexFilename, worktree, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(treeish) indexFilename, worktree, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(ctx, treeish)
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -62,7 +62,7 @@ type CheckAttributeOpts struct {
// CheckAttributes return the attributes of the given filenames and attributes in the given treeish. // CheckAttributes return the attributes of the given filenames and attributes in the given treeish.
// If treeish is empty, then it will use current working directory, otherwise it will use the provided treeish on the bare repo // If treeish is empty, then it will use current working directory, otherwise it will use the provided treeish on the bare repo
func CheckAttributes(ctx context.Context, gitRepo *git.Repository, treeish string, opts CheckAttributeOpts) (map[string]*Attributes, error) { func CheckAttributes(ctx context.Context, gitRepo *git.Repository, treeish string, opts CheckAttributeOpts) (map[string]*Attributes, error) {
cmd, envs, cancel, err := checkAttrCommand(gitRepo, treeish, opts.Filenames, opts.Attributes) cmd, envs, cancel, err := checkAttrCommand(ctx, gitRepo, treeish, opts.Filenames, opts.Attributes)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+2 -2
View File
@@ -18,7 +18,7 @@ import (
func Test_Checker(t *testing.T) { func Test_Checker(t *testing.T) {
setting.AppDataPath = t.TempDir() setting.AppDataPath = t.TempDir()
repoPath := "../tests/repos/language_stats_repo" repoPath := "../tests/repos/language_stats_repo"
gitRepo, err := git.OpenRepository(t.Context(), repoPath) gitRepo, err := git.OpenRepository(repoPath)
require.NoError(t, err) require.NoError(t, err)
defer gitRepo.Close() defer gitRepo.Close()
@@ -44,7 +44,7 @@ func Test_Checker(t *testing.T) {
}) })
assert.NoError(t, err) assert.NoError(t, err)
tempRepo, err := git.OpenRepository(t.Context(), dir) tempRepo, err := git.OpenRepository(dir)
assert.NoError(t, err) assert.NoError(t, err)
defer tempRepo.Close() defer tempRepo.Close()
+11 -10
View File
@@ -6,6 +6,7 @@ package git
import ( import (
"bytes" "bytes"
"context"
"encoding/base64" "encoding/base64"
"errors" "errors"
"io" "io"
@@ -23,11 +24,11 @@ func (b *Blob) Name() string {
} }
// GetBlobBytes Gets the limited content of the blob // GetBlobBytes Gets the limited content of the blob
func (b *Blob) GetBlobBytes(limit int64) ([]byte, error) { func (b *Blob) GetBlobBytes(ctx context.Context, limit int64) ([]byte, error) {
if limit <= 0 { if limit <= 0 {
return nil, nil return nil, nil
} }
dataRc, err := b.DataAsync() dataRc, err := b.DataAsync(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -36,15 +37,15 @@ func (b *Blob) GetBlobBytes(limit int64) ([]byte, error) {
} }
// GetBlobContent Gets the limited content of the blob as raw text // GetBlobContent Gets the limited content of the blob as raw text
func (b *Blob) GetBlobContent(limit int64) (string, error) { func (b *Blob) GetBlobContent(ctx context.Context, limit int64) (string, error) {
buf, err := b.GetBlobBytes(limit) buf, err := b.GetBlobBytes(ctx, limit)
return string(buf), err return string(buf), err
} }
// GetBlobLineCount gets line count of the blob. // GetBlobLineCount gets line count of the blob.
// It will also try to write the content to w if it's not nil, then we could pre-fetch the content without reading it again. // It will also try to write the content to w if it's not nil, then we could pre-fetch the content without reading it again.
func (b *Blob) GetBlobLineCount(w io.Writer) (int, error) { func (b *Blob) GetBlobLineCount(ctx context.Context, w io.Writer) (int, error) {
reader, err := b.DataAsync() reader, err := b.DataAsync(ctx)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -70,8 +71,8 @@ func (b *Blob) GetBlobLineCount(w io.Writer) (int, error) {
} }
// GetBlobContentBase64 Reads the content of the blob with a base64 encoding and returns the encoded string // GetBlobContentBase64 Reads the content of the blob with a base64 encoding and returns the encoded string
func (b *Blob) GetBlobContentBase64(originContent *strings.Builder) (string, error) { func (b *Blob) GetBlobContentBase64(ctx context.Context, originContent *strings.Builder) (string, error) {
dataRc, err := b.DataAsync() dataRc, err := b.DataAsync(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -103,8 +104,8 @@ loop:
} }
// GuessContentType guesses the content type of the blob. // GuessContentType guesses the content type of the blob.
func (b *Blob) GuessContentType() (typesniffer.SniffedType, error) { func (b *Blob) GuessContentType(ctx context.Context) (typesniffer.SniffedType, error) {
buf, err := b.GetBlobBytes(typesniffer.SniffContentSize) buf, err := b.GetBlobBytes(ctx, typesniffer.SniffContentSize)
if err != nil { if err != nil {
return typesniffer.SniffedType{}, err return typesniffer.SniffedType{}, err
} }
+3 -2
View File
@@ -7,6 +7,7 @@
package git package git
import ( import (
"context"
"io" "io"
"gitea.dev/modules/log" "gitea.dev/modules/log"
@@ -27,7 +28,7 @@ func (b *Blob) gogitEncodedObj() (plumbing.EncodedObject, error) {
// DataAsync gets a ReadCloser for the contents of a blob without reading it all. // DataAsync gets a ReadCloser for the contents of a blob without reading it all.
// Calling the Close function on the result will discard all unread output. // Calling the Close function on the result will discard all unread output.
func (b *Blob) DataAsync() (io.ReadCloser, error) { func (b *Blob) DataAsync(_ context.Context) (io.ReadCloser, error) {
obj, err := b.gogitEncodedObj() obj, err := b.gogitEncodedObj()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -36,7 +37,7 @@ func (b *Blob) DataAsync() (io.ReadCloser, error) {
} }
// Size returns the uncompressed size of the blob // Size returns the uncompressed size of the blob
func (b *Blob) Size() int64 { func (b *Blob) Size(_ context.Context) int64 {
obj, err := b.gogitEncodedObj() obj, err := b.gogitEncodedObj()
if err != nil { if err != nil {
log.Error("Error getting gogit encoded object for blob %s(%s): %v", b.name, b.ID.String(), err) log.Error("Error getting gogit encoded object for blob %s(%s): %v", b.name, b.ID.String(), err)
+5 -4
View File
@@ -6,6 +6,7 @@
package git package git
import ( import (
"context"
"io" "io"
"gitea.dev/modules/log" "gitea.dev/modules/log"
@@ -23,8 +24,8 @@ type Blob struct {
// DataAsync gets a ReadCloser for the contents of a blob without reading it all. // DataAsync gets a ReadCloser for the contents of a blob without reading it all.
// Calling the Close function on the result will discard all unread output. // Calling the Close function on the result will discard all unread output.
func (b *Blob) DataAsync() (_ io.ReadCloser, retErr error) { func (b *Blob) DataAsync(ctx context.Context) (_ io.ReadCloser, retErr error) {
batch, cancel, err := b.repo.CatFileBatch(b.repo.Ctx) batch, cancel, err := b.repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -50,12 +51,12 @@ func (b *Blob) DataAsync() (_ io.ReadCloser, retErr error) {
} }
// Size returns the uncompressed size of the blob // Size returns the uncompressed size of the blob
func (b *Blob) Size() int64 { func (b *Blob) Size(ctx context.Context) int64 {
if b.gotSize { if b.gotSize {
return b.size return b.size
} }
batch, cancel, err := b.repo.CatFileBatch(b.repo.Ctx) batch, cancel, err := b.repo.CatFileBatch(ctx)
if err != nil { if err != nil {
log.Debug("error whilst reading size for %s in %s. Error: %v", b.ID.String(), b.repo.Path, err) log.Debug("error whilst reading size for %s in %s. Error: %v", b.ID.String(), b.repo.Path, err)
return 0 return 0
+4 -4
View File
@@ -16,14 +16,14 @@ import (
func TestBlob_Data(t *testing.T) { func TestBlob_Data(t *testing.T) {
output := "file2\n" output := "file2\n"
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(t.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
require.NoError(t, err) require.NoError(t, err)
defer repo.Close() defer repo.Close()
testBlob, err := repo.GetBlob("6c493ff740f9380390d5c9ddef4af18697ac9375") testBlob, err := repo.GetBlob("6c493ff740f9380390d5c9ddef4af18697ac9375")
assert.NoError(t, err) assert.NoError(t, err)
r, err := testBlob.DataAsync() r, err := testBlob.DataAsync(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
require.NotNil(t, r) require.NotNil(t, r)
@@ -36,7 +36,7 @@ func TestBlob_Data(t *testing.T) {
func Benchmark_Blob_Data(b *testing.B) { func Benchmark_Blob_Data(b *testing.B) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(b.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@@ -48,7 +48,7 @@ func Benchmark_Blob_Data(b *testing.B) {
} }
for b.Loop() { for b.Loop() {
r, err := testBlob.DataAsync() r, err := testBlob.DataAsync(b.Context())
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
+1
View File
@@ -39,6 +39,7 @@ type CatFileBatch interface {
type CatFileBatchCloser interface { type CatFileBatchCloser interface {
CatFileBatch CatFileBatch
Context() context.Context
Close() Close()
} }
+4
View File
@@ -40,6 +40,10 @@ func (b *catFileBatchCommand) getBatch() *catFileBatchCommunicator {
return b.batch return b.batch
} }
func (b *catFileBatchCommand) Context() context.Context {
return b.ctx
}
func (b *catFileBatchCommand) QueryContent(obj string) (*CatFileObject, BufferedReader, error) { func (b *catFileBatchCommand) QueryContent(obj string) (*CatFileObject, BufferedReader, error) {
if strings.Contains(obj, "\n") { if strings.Contains(obj, "\n") {
setting.PanicInDevOrTesting("invalid object name with newline: %q", obj) setting.PanicInDevOrTesting("invalid object name with newline: %q", obj)
+4
View File
@@ -51,6 +51,10 @@ func (b *catFileBatchLegacy) getBatchCheck() *catFileBatchCommunicator {
return b.batchCheck return b.batchCheck
} }
func (b *catFileBatchLegacy) Context() context.Context {
return b.ctx
}
func (b *catFileBatchLegacy) QueryContent(obj string) (*CatFileObject, BufferedReader, error) { func (b *catFileBatchLegacy) QueryContent(obj string) (*CatFileObject, BufferedReader, error) {
if strings.Contains(obj, "\n") { if strings.Contains(obj, "\n") {
setting.PanicInDevOrTesting("invalid object name with newline: %q", obj) setting.PanicInDevOrTesting("invalid object name with newline: %q", obj)
+22 -22
View File
@@ -46,12 +46,12 @@ func (c *Commit) ParentID(n int) (ObjectID, error) {
} }
// Parent returns n-th parent (0-based index) of the commit. // Parent returns n-th parent (0-based index) of the commit.
func (c *Commit) Parent(gitRepo *Repository, n int) (*Commit, error) { func (c *Commit) Parent(ctx context.Context, gitRepo *Repository, n int) (*Commit, error) {
id, err := c.ParentID(n) id, err := c.ParentID(n)
if err != nil { if err != nil {
return nil, err return nil, err
} }
parent, err := gitRepo.getCommit(id) parent, err := gitRepo.getCommit(ctx, id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -65,11 +65,11 @@ func (c *Commit) ParentCount() int {
} }
// GetCommitByPath return the commit of relative path object. // GetCommitByPath return the commit of relative path object.
func (c *Commit) GetCommitByPath(gitRepo *Repository, relpath string) (*Commit, error) { func (c *Commit) GetCommitByPath(ctx context.Context, gitRepo *Repository, relpath string) (*Commit, error) {
if gitRepo.LastCommitCache != nil { if gitRepo.LastCommitCache != nil {
return gitRepo.LastCommitCache.GetCommitByPath(c.ID.String(), relpath) return gitRepo.LastCommitCache.GetCommitByPath(ctx, c.ID.String(), relpath)
} }
return gitRepo.getCommitByPathWithID(c.ID, relpath) return gitRepo.getCommitByPathWithID(ctx, c.ID, relpath)
} }
func (c *Commit) Tree() *Tree { func (c *Commit) Tree() *Tree {
@@ -92,13 +92,13 @@ func (c *Commit) SubTree(ctx context.Context, gitRepo *Repository, relpath strin
} }
// CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
func (c *Commit) CommitsByRange(gitRepo *Repository, page, pageSize int, not, since, until string) ([]*Commit, error) { func (c *Commit) CommitsByRange(ctx context.Context, gitRepo *Repository, page, pageSize int, not, since, until string) ([]*Commit, error) {
return gitRepo.commitsByRangeWithTime(c.ID, page, pageSize, not, since, until) return gitRepo.commitsByRangeWithTime(ctx, c.ID, page, pageSize, not, since, until)
} }
// CommitsBefore returns all the commits before current revision // CommitsBefore returns all the commits before current revision
func (c *Commit) CommitsBefore(gitRepo *Repository) ([]*Commit, error) { func (c *Commit) CommitsBefore(ctx context.Context, gitRepo *Repository) ([]*Commit, error) {
return gitRepo.getCommitsBefore(c.ID) return gitRepo.getCommitsBefore(ctx, c.ID)
} }
// HasPreviousCommit returns true if a given commitHash is contained in commit's parents // HasPreviousCommit returns true if a given commitHash is contained in commit's parents
@@ -128,7 +128,7 @@ func (c *Commit) HasPreviousCommit(ctx context.Context, gitRepo *Repository, obj
// IsForcePush returns true if a push from oldCommitHash to this is a force push // IsForcePush returns true if a push from oldCommitHash to this is a force push
func (c *Commit) IsForcePush(ctx context.Context, gitRepo *Repository, oldCommitID string) (bool, error) { func (c *Commit) IsForcePush(ctx context.Context, gitRepo *Repository, oldCommitID string) (bool, error) {
objectFormat, err := gitRepo.GetObjectFormat() objectFormat, err := gitRepo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return false, err return false, err
} }
@@ -136,7 +136,7 @@ func (c *Commit) IsForcePush(ctx context.Context, gitRepo *Repository, oldCommit
return false, nil return false, nil
} }
oldCommit, err := gitRepo.GetCommit(oldCommitID) oldCommit, err := gitRepo.GetCommit(ctx, oldCommitID)
if err != nil { if err != nil {
return false, err return false, err
} }
@@ -145,13 +145,13 @@ func (c *Commit) IsForcePush(ctx context.Context, gitRepo *Repository, oldCommit
} }
// CommitsBeforeLimit returns num commits before current revision // CommitsBeforeLimit returns num commits before current revision
func (c *Commit) CommitsBeforeLimit(gitRepo *Repository, num int) ([]*Commit, error) { func (c *Commit) CommitsBeforeLimit(ctx context.Context, gitRepo *Repository, num int) ([]*Commit, error) {
return gitRepo.getCommitsBeforeLimit(c.ID, num) return gitRepo.getCommitsBeforeLimit(ctx, c.ID, num)
} }
// CommitsBeforeUntil returns the commits in range "[cur, ref)" // CommitsBeforeUntil returns the commits in range "[cur, ref)"
func (c *Commit) CommitsBeforeUntil(gitRepo *Repository, ref RefName) ([]*Commit, error) { func (c *Commit) CommitsBeforeUntil(ctx context.Context, gitRepo *Repository, ref RefName) ([]*Commit, error) {
return gitRepo.CommitsBetween(c.ID.RefName(), ref, -1) return gitRepo.CommitsBetween(ctx, c.ID.RefName(), ref, -1)
} }
// SearchCommitsOptions specify the parameters for SearchCommits // SearchCommitsOptions specify the parameters for SearchCommits
@@ -194,19 +194,19 @@ func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommits
} }
// SearchCommits returns the commits match the keyword before current revision // SearchCommits returns the commits match the keyword before current revision
func (c *Commit) SearchCommits(gitRepo *Repository, opts SearchCommitsOptions) ([]*Commit, error) { func (c *Commit) SearchCommits(ctx context.Context, gitRepo *Repository, opts SearchCommitsOptions) ([]*Commit, error) {
return gitRepo.searchCommits(c.ID, opts) return gitRepo.searchCommits(ctx, c.ID, opts)
} }
// GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
func (c *Commit) GetFilesChangedSinceCommit(gitRepo *Repository, pastCommit string) ([]string, error) { func (c *Commit) GetFilesChangedSinceCommit(ctx context.Context, gitRepo *Repository, pastCommit string) ([]string, error) {
return gitRepo.GetFilesChangedBetween(pastCommit, c.ID.String()) return gitRepo.GetFilesChangedBetween(ctx, pastCommit, c.ID.String())
} }
// FileChangedSinceCommit Returns true if the file given has changed since the past commit // FileChangedSinceCommit Returns true if the file given has changed since the past commit
// YOU MUST ENSURE THAT pastCommit is a valid commit ID. // YOU MUST ENSURE THAT pastCommit is a valid commit ID.
func (c *Commit) FileChangedSinceCommit(gitRepo *Repository, filename, pastCommit string) (bool, error) { func (c *Commit) FileChangedSinceCommit(ctx context.Context, gitRepo *Repository, filename, pastCommit string) (bool, error) {
return gitRepo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String()) return gitRepo.FileChangedBetweenCommits(ctx, filename, pastCommit, c.ID.String())
} }
// GetFileContent reads a file content as a string or returns false if this was not possible // GetFileContent reads a file content as a string or returns false if this was not possible
@@ -216,7 +216,7 @@ func (c *Commit) GetFileContent(ctx context.Context, gitRepo *Repository, filena
return "", err return "", err
} }
r, err := entry.Blob(gitRepo).DataAsync() r, err := entry.Blob(gitRepo).DataAsync(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
+3 -3
View File
@@ -29,7 +29,7 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, repoLink string, gitRepo
var err error var err error
if gitRepo.LastCommitCache != nil { if gitRepo.LastCommitCache != nil {
var unHitPaths []string var unHitPaths []string
revs, unHitPaths, err = getLastCommitForPathsByCache(commit.ID.String(), treePath, entryPaths, gitRepo.LastCommitCache) revs, unHitPaths, err = getLastCommitForPathsByCache(ctx, commit.ID.String(), treePath, entryPaths, gitRepo.LastCommitCache)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -132,11 +132,11 @@ func getFileHashes(c cgobject.CommitNode, treePath string, paths []string) (map[
return hashes, nil return hashes, nil
} }
func getLastCommitForPathsByCache(commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*Commit, []string, error) { func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*Commit, []string, error) {
var unHitEntryPaths []string var unHitEntryPaths []string
results := make(map[string]*Commit) results := make(map[string]*Commit)
for _, p := range paths { for _, p := range paths {
lastCommit, err := cache.Get(commitID, path.Join(treePath, p)) lastCommit, err := cache.Get(ctx, commitID, path.Join(treePath, p))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
+4 -4
View File
@@ -28,7 +28,7 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, repoLink string, gitRepo
var revs map[string]*Commit var revs map[string]*Commit
if gitRepo.LastCommitCache != nil { if gitRepo.LastCommitCache != nil {
var unHitPaths []string var unHitPaths []string
revs, unHitPaths, err = getLastCommitForPathsByCache(commit.ID.String(), treePath, entryPaths, gitRepo.LastCommitCache) revs, unHitPaths, err = getLastCommitForPathsByCache(ctx, commit.ID.String(), treePath, entryPaths, gitRepo.LastCommitCache)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -83,11 +83,11 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, repoLink string, gitRepo
return commitsInfo, treeCommit, nil return commitsInfo, treeCommit, nil
} }
func getLastCommitForPathsByCache(commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*Commit, []string, error) { func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*Commit, []string, error) {
var unHitEntryPaths []string var unHitEntryPaths []string
results := make(map[string]*Commit) results := make(map[string]*Commit)
for _, p := range paths { for _, p := range paths {
lastCommit, err := cache.Get(commitID, path.Join(treePath, p)) lastCommit, err := cache.Get(ctx, commitID, path.Join(treePath, p))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -125,7 +125,7 @@ func GetLastCommitForPaths(ctx context.Context, gitRepo *Repository, commit *Com
continue continue
} }
c, err := gitRepo.GetCommit(commitID) // Ensure the commit exists in the repository c, err := gitRepo.GetCommit(ctx, commitID) // Ensure the commit exists in the repository
if err != nil { if err != nil {
return nil, err return nil, err
} }
+2 -2
View File
@@ -18,11 +18,11 @@ import (
) )
func TestEntries_GetCommitsInfo_ContextErr(t *testing.T) { func TestEntries_GetCommitsInfo_ContextErr(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) repo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
require.NoError(t, err) require.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetCommit("feaf4ba6bc635fec442f46ddd4512416ec43c2c2") commit, err := repo.GetCommit(t.Context(), "feaf4ba6bc635fec442f46ddd4512416ec43c2c2")
require.NoError(t, err) require.NoError(t, err)
entries, err := commit.Tree().ListEntries(t.Context(), repo) entries, err := commit.Tree().ListEntries(t.Context(), repo)
require.NoError(t, err) require.NoError(t, err)
+4 -4
View File
@@ -84,7 +84,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) {
}, "feaf4ba6bc635fec442f46ddd4512416ec43c2c2"}, }, "feaf4ba6bc635fec442f46ddd4512416ec43c2c2"},
} }
for _, testCase := range testCases { for _, testCase := range testCases {
commit, err := repo1.GetCommit(testCase.CommitID) commit, err := repo1.GetCommit(t.Context(), testCase.CommitID)
if err != nil { if err != nil {
assert.NoError(t, err, "Unable to get commit: %s from testcase due to error: %v", testCase.CommitID, err) assert.NoError(t, err, "Unable to get commit: %s from testcase due to error: %v", testCase.CommitID, err)
// no point trying to do anything else for this test. // no point trying to do anything else for this test.
@@ -132,7 +132,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) {
func TestEntries_GetCommitsInfo(t *testing.T) { func TestEntries_GetCommitsInfo(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
@@ -142,7 +142,7 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
} }
clonedRepo1, err := OpenRepository(t.Context(), clonedPath) clonedRepo1, err := OpenRepository(clonedPath)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
} }
@@ -151,7 +151,7 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
testGetCommitsInfo(t, clonedRepo1) testGetCommitsInfo(t, clonedRepo1)
t.Run("NonExistingSubmoduleAsNil", func(t *testing.T) { t.Run("NonExistingSubmoduleAsNil", func(t *testing.T) {
commit, err := bareRepo1.GetCommit("HEAD") commit, err := bareRepo1.GetCommit(t.Context(), "HEAD")
require.NoError(t, err) require.NoError(t, err)
treeEntry, err := commit.GetTreeEntryByPath(t.Context(), bareRepo1, "file1.txt") treeEntry, err := commit.GetTreeEntryByPath(t.Context(), bareRepo1, "file1.txt")
require.NoError(t, err) require.NoError(t, err)
+4 -4
View File
@@ -60,7 +60,7 @@ signed commit`
0x94, 0x33, 0xb2, 0xa6, 0x2b, 0x96, 0x4c, 0x17, 0xa4, 0x48, 0x5a, 0xe1, 0x80, 0xf4, 0x5f, 0x59, 0x94, 0x33, 0xb2, 0xa6, 0x2b, 0x96, 0x4c, 0x17, 0xa4, 0x48, 0x5a, 0xe1, 0x80, 0xf4, 0x5f, 0x59,
0x5d, 0x3e, 0x69, 0xd3, 0x1b, 0x78, 0x60, 0x87, 0x77, 0x5e, 0x28, 0xc6, 0xb6, 0x39, 0x9d, 0xf0, 0x5d, 0x3e, 0x69, 0xd3, 0x1b, 0x78, 0x60, 0x87, 0x77, 0x5e, 0x28, 0xc6, 0xb6, 0x39, 0x9d, 0xf0,
} }
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare_sha256")) gitRepo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare_sha256"))
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, gitRepo) assert.NotNil(t, gitRepo)
defer gitRepo.Close() defer gitRepo.Close()
@@ -103,14 +103,14 @@ signed commit`, commitFromReader.Signature.Payload)
func TestHasPreviousCommitSha256(t *testing.T) { func TestHasPreviousCommitSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
repo, err := OpenRepository(t.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetCommit("f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc") commit, err := repo.GetCommit(t.Context(), "f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc")
assert.NoError(t, err) assert.NoError(t, err)
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
parentSHA := MustIDFromString("b0ec7af4547047f12d5093e37ef8f1b3b5415ed8ee17894d43a34d7d34212e9c") parentSHA := MustIDFromString("b0ec7af4547047f12d5093e37ef8f1b3b5415ed8ee17894d43a34d7d34212e9c")
+1 -1
View File
@@ -23,7 +23,7 @@ func (c *Commit) GetSubModules(ctx context.Context, gitRepo *Repository) (*Objec
return nil, err return nil, err
} }
rd, err := entry.Blob(gitRepo).DataAsync() rd, err := entry.Blob(gitRepo).DataAsync(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+7 -7
View File
@@ -56,7 +56,7 @@ gpgsig -----BEGIN PGP SIGNATURE-----
empty commit` empty commit`
sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2} sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2}
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) gitRepo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, gitRepo) assert.NotNil(t, gitRepo)
defer gitRepo.Close() defer gitRepo.Close()
@@ -120,7 +120,7 @@ gpgsig -----BEGIN PGP SIGNATURE-----
ISO-8859-1` ISO-8859-1`
commitString = strings.ReplaceAll(commitString, "<SPACE>", " ") commitString = strings.ReplaceAll(commitString, "<SPACE>", " ")
sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2} sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2}
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) gitRepo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, gitRepo) assert.NotNil(t, gitRepo)
defer gitRepo.Close() defer gitRepo.Close()
@@ -162,11 +162,11 @@ ISO-8859-1`, commitFromReader.Signature.Payload)
func TestHasPreviousCommit(t *testing.T) { func TestHasPreviousCommit(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(t.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetCommit("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0") commit, err := repo.GetCommit(t.Context(), "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0")
assert.NoError(t, err) assert.NoError(t, err)
parentSHA := MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2") parentSHA := MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2")
@@ -187,14 +187,14 @@ func TestHasPreviousCommit(t *testing.T) {
func Test_GetCommitBranchStart(t *testing.T) { func Test_GetCommitBranchStart(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(t.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetBranchCommit("branch1") commit, err := repo.GetBranchCommit(t.Context(), "branch1")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "2839944139e0de9737a044f78b0e4b40d989a9e3", commit.ID.String()) assert.Equal(t, "2839944139e0de9737a044f78b0e4b40d989a9e3", commit.ID.String())
startCommitID, err := repo.GetCommitBranchStart(os.Environ(), "branch1", commit.ID.String()) startCommitID, err := repo.GetCommitBranchStart(t.Context(), os.Environ(), "branch1", commit.ID.String())
assert.NoError(t, err) assert.NoError(t, err)
assert.NotEmpty(t, startCommitID) assert.NotEmpty(t, startCommitID)
assert.Equal(t, "95bb4d39648ee7e325106df01a621c530863a653", startCommitID) assert.Equal(t, "95bb4d39648ee7e325106df01a621c530863a653", startCommitID)
+13 -13
View File
@@ -27,20 +27,20 @@ const (
) )
// GetRawDiff dumps diff results of repository in given commit ID to io.Writer. // GetRawDiff dumps diff results of repository in given commit ID to io.Writer.
func GetRawDiff(repo *Repository, commitID string, diffType RawDiffType, writer io.Writer) (retErr error) { func GetRawDiff(ctx context.Context, repo *Repository, commitID string, diffType RawDiffType, writer io.Writer) (retErr error) {
cmd, err := getRepoRawDiffForFileCmd(repo.Ctx, repo, "", commitID, diffType, "") cmd, err := getRepoRawDiffForFileCmd(ctx, repo, "", commitID, diffType, "")
if err != nil { if err != nil {
return fmt.Errorf("getRepoRawDiffForFileCmd: %w", err) return fmt.Errorf("getRepoRawDiffForFileCmd: %w", err)
} }
return cmd.WithStdoutCopy(writer).RunWithStderr(repo.Ctx) return cmd.WithStdoutCopy(writer).RunWithStderr(ctx)
} }
// GetFileDiffCutAroundLine cuts the old or new part of the diff of a file around a specific line number // GetFileDiffCutAroundLine cuts the old or new part of the diff of a file around a specific line number
func GetFileDiffCutAroundLine( func GetFileDiffCutAroundLine(
repo *Repository, startCommit, endCommit, treePath string, ctx context.Context, repo *Repository, startCommit, endCommit, treePath string,
line int64, old bool, numbersOfLine int, line int64, old bool, numbersOfLine int,
) (ret string, retErr error) { ) (ret string, retErr error) {
cmd, err := getRepoRawDiffForFileCmd(repo.Ctx, repo, startCommit, endCommit, RawDiffNormal, treePath) cmd, err := getRepoRawDiffForFileCmd(ctx, repo, startCommit, endCommit, RawDiffNormal, treePath)
if err != nil { if err != nil {
return "", fmt.Errorf("getRepoRawDiffForFileCmd: %w", err) return "", fmt.Errorf("getRepoRawDiffForFileCmd: %w", err)
} }
@@ -50,13 +50,13 @@ func GetFileDiffCutAroundLine(
ret, err = CutDiffAroundLine(stdoutReader, line, old, numbersOfLine) ret, err = CutDiffAroundLine(stdoutReader, line, old, numbersOfLine)
return err return err
}) })
return ret, cmd.RunWithStderr(repo.Ctx) return ret, cmd.RunWithStderr(ctx)
} }
// getRepoRawDiffForFile returns an io.Reader for the diff results of file in given commit ID // getRepoRawDiffForFile returns an io.Reader for the diff results of file in given commit ID
// and a "finish" function to wait for the git command and clean up resources after reading is done. // and a "finish" function to wait for the git command and clean up resources after reading is done.
func getRepoRawDiffForFileCmd(_ context.Context, repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string) (*gitcmd.Command, error) { func getRepoRawDiffForFileCmd(ctx context.Context, repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string) (*gitcmd.Command, error) {
commit, err := repo.GetCommit(endCommit) commit, err := repo.GetCommit(ctx, endCommit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -75,7 +75,7 @@ func getRepoRawDiffForFileCmd(_ context.Context, repo *Repository, startCommit,
} else if commit.ParentCount() == 0 { } else if commit.ParentCount() == 0 {
cmd.AddArguments("show").AddDynamicArguments(endCommit).AddDashesAndList(files...) cmd.AddArguments("show").AddDynamicArguments(endCommit).AddDashesAndList(files...)
} else { } else {
c, err := commit.Parent(repo, 0) c, err := commit.Parent(ctx, repo, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -90,7 +90,7 @@ func getRepoRawDiffForFileCmd(_ context.Context, repo *Repository, startCommit,
} else if commit.ParentCount() == 0 { } else if commit.ParentCount() == 0 {
cmd.AddArguments("format-patch", "--no-signature", "--stdout", "--root").AddDynamicArguments(endCommit).AddDashesAndList(files...) cmd.AddArguments("format-patch", "--no-signature", "--stdout", "--root").AddDynamicArguments(endCommit).AddDashesAndList(files...)
} else { } else {
c, err := commit.Parent(repo, 0) c, err := commit.Parent(ctx, repo, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -292,9 +292,9 @@ func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLi
} }
// GetAffectedFiles returns the affected files between two commits // GetAffectedFiles returns the affected files between two commits
func GetAffectedFiles(repo *Repository, branchName, oldCommitID, newCommitID string, env []string) ([]string, error) { func GetAffectedFiles(ctx context.Context, repo *Repository, branchName, oldCommitID, newCommitID string, env []string) ([]string, error) {
if oldCommitID == emptySha1ObjectID.String() || oldCommitID == emptySha256ObjectID.String() { if oldCommitID == emptySha1ObjectID.String() || oldCommitID == emptySha256ObjectID.String() {
startCommitID, err := repo.GetCommitBranchStart(env, branchName, newCommitID) startCommitID, err := repo.GetCommitBranchStart(ctx, env, branchName, newCommitID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -323,7 +323,7 @@ func GetAffectedFiles(repo *Repository, branchName, oldCommitID, newCommitID str
} }
return scanner.Err() return scanner.Err()
}). }).
Run(repo.Ctx) Run(ctx)
if err != nil { if err != nil {
log.Error("Unable to get affected files for commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err) log.Error("Unable to get affected files for commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
} }
+2 -2
View File
@@ -11,7 +11,7 @@ import (
) )
func TestGrepSearch(t *testing.T) { func TestGrepSearch(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "language_stats_repo")) repo, err := OpenRepository(filepath.Join(testReposDir, "language_stats_repo"))
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
@@ -74,7 +74,7 @@ func TestGrepSearch(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, res) assert.Empty(t, res)
res, err = GrepSearch(t.Context(), &Repository{Path: "no-such-git-repo"}, "no-such-content", GrepOptions{}) res, err = GrepSearch(t.Context(), &Repository{RepositoryBase: RepositoryBase{Path: "no-such-git-repo"}}, "no-such-content", GrepOptions{})
assert.Error(t, err) assert.Error(t, err)
assert.Empty(t, res) assert.Empty(t, res)
} }
@@ -22,7 +22,7 @@ import (
) )
// GetLanguageStats calculates language stats for git repository at specified commit // GetLanguageStats calculates language stats for git repository at specified commit
func GetLanguageStats(_ context.Context, repo *git_module.Repository, commitID string) (map[string]int64, error) { func GetLanguageStats(ctx context.Context, repo *git_module.Repository, commitID string) (map[string]int64, error) {
r, err := git.PlainOpen(repo.Path) r, err := git.PlainOpen(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -43,7 +43,7 @@ func GetLanguageStats(_ context.Context, repo *git_module.Repository, commitID s
return nil, err return nil, err
} }
checker, err := attribute.NewBatchChecker(repo, commitID, attribute.LinguistAttributes) checker, err := attribute.NewBatchChecker(ctx, repo, commitID, attribute.LinguistAttributes)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -58,7 +58,7 @@ func GetLanguageStats(ctx context.Context, repo *git.Repository, commitID string
return nil, err return nil, err
} }
checker, err := attribute.NewBatchChecker(repo, commitID, attribute.LinguistAttributes) checker, err := attribute.NewBatchChecker(ctx, repo, commitID, attribute.LinguistAttributes)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -78,8 +78,6 @@ func GetLanguageStats(ctx context.Context, repo *git.Repository, commitID string
for _, f := range entries { for _, f := range entries {
select { select {
case <-repo.Ctx.Done():
return sizes, repo.Ctx.Err()
case <-ctx.Done(): case <-ctx.Done():
return sizes, ctx.Err() return sizes, ctx.Err()
default: default:
@@ -18,7 +18,7 @@ import (
func TestRepository_GetLanguageStats(t *testing.T) { func TestRepository_GetLanguageStats(t *testing.T) {
setting.AppDataPath = t.TempDir() setting.AppDataPath = t.TempDir()
repoPath := "../tests/repos/language_stats_repo" repoPath := "../tests/repos/language_stats_repo"
gitRepo, err := git.OpenRepository(t.Context(), repoPath) gitRepo, err := git.OpenRepository(repoPath)
require.NoError(t, err) require.NoError(t, err)
defer gitRepo.Close() defer gitRepo.Close()
+6 -5
View File
@@ -4,6 +4,7 @@
package git package git
import ( import (
"context"
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
@@ -53,7 +54,7 @@ func (c *LastCommitCache) Put(ref, entryPath, commitID string) error {
} }
// Get gets the last commit information by commit id and entry path // Get gets the last commit information by commit id and entry path
func (c *LastCommitCache) Get(ref, entryPath string) (*Commit, error) { func (c *LastCommitCache) Get(ctx context.Context, ref, entryPath string) (*Commit, error) {
if c == nil || c.cache == nil { if c == nil || c.cache == nil {
return nil, nil //nolint:nilnil // return nil when cache is not available return nil, nil //nolint:nilnil // return nil when cache is not available
} }
@@ -71,7 +72,7 @@ func (c *LastCommitCache) Get(ref, entryPath string) (*Commit, error) {
} }
} }
commit, err := c.repo.GetCommit(commitID) commit, err := c.repo.GetCommit(ctx, commitID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -83,18 +84,18 @@ 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(ctx context.Context, commitID, entryPath string) (*Commit, error) {
sha, err := NewIDFromString(commitID) sha, err := NewIDFromString(commitID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
lastCommit, err := c.Get(sha.String(), entryPath) lastCommit, err := c.Get(ctx, sha.String(), entryPath)
if err != nil || lastCommit != nil { if err != nil || lastCommit != nil {
return lastCommit, err return lastCommit, err
} }
lastCommit, err = c.repo.getCommitByPathWithID(sha, entryPath) lastCommit, err = c.repo.getCommitByPathWithID(ctx, sha, entryPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+2 -2
View File
@@ -25,7 +25,7 @@ type Note struct {
// FIXME: Add LastCommitCache support // FIXME: Add LastCommitCache support
func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note) error { func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note) error {
log.Trace("Searching for git note corresponding to the commit %q in the repository %q", commitID, repo.Path) log.Trace("Searching for git note corresponding to the commit %q in the repository %q", commitID, repo.Path)
notes, err := repo.GetCommit(NotesRef) notes, err := repo.GetCommit(ctx, NotesRef)
if err != nil { if err != nil {
if IsErrNotExist(err) { if IsErrNotExist(err) {
return err return err
@@ -62,7 +62,7 @@ func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note)
} }
blob := entry.Blob(repo) blob := entry.Blob(repo)
dataRc, err := blob.DataAsync() dataRc, err := blob.DataAsync(ctx)
if err != nil { if err != nil {
log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err) log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err)
return err return err
+3 -3
View File
@@ -12,7 +12,7 @@ import (
func TestGetNotes(t *testing.T) { func TestGetNotes(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
@@ -25,7 +25,7 @@ func TestGetNotes(t *testing.T) {
func TestGetNestedNotes(t *testing.T) { func TestGetNestedNotes(t *testing.T) {
repoPath := filepath.Join(testReposDir, "repo3_notes") repoPath := filepath.Join(testReposDir, "repo3_notes")
repo, err := OpenRepository(t.Context(), repoPath) repo, err := OpenRepository(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
@@ -40,7 +40,7 @@ func TestGetNestedNotes(t *testing.T) {
func TestGetNonExistentNotes(t *testing.T) { func TestGetNonExistentNotes(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
+3 -2
View File
@@ -6,6 +6,7 @@
package pipeline package pipeline
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"sort" "sort"
@@ -19,7 +20,7 @@ import (
) )
// FindLFSFile finds commits that contain a provided pointer file hash // FindLFSFile finds commits that contain a provided pointer file hash
func FindLFSFile(repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, error) { func FindLFSFile(ctx context.Context, repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, error) {
resultsMap := map[string]*LFSResult{} resultsMap := map[string]*LFSResult{}
results := make([]*LFSResult, 0) results := make([]*LFSResult, 0)
@@ -80,6 +81,6 @@ func FindLFSFile(repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, err
} }
sort.Sort(lfsResultSlice(results)) sort.Sort(lfsResultSlice(results))
err = fillResultNameRev(repo.Ctx, repo.Path, results) err = fillResultNameRev(ctx, repo.Path, results)
return results, err return results, err
} }
+7 -6
View File
@@ -8,6 +8,7 @@ package pipeline
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"io" "io"
"sort" "sort"
@@ -16,24 +17,24 @@ import (
) )
// FindLFSFile finds commits that contain a provided pointer file hash // FindLFSFile finds commits that contain a provided pointer file hash
func FindLFSFile(repo *git.Repository, objectID git.ObjectID) (results []*LFSResult, _ error) { func FindLFSFile(ctx context.Context, repo *git.Repository, objectID git.ObjectID) (results []*LFSResult, _ error) {
cmd := gitcmd.NewCommand("rev-list", "--all") cmd := gitcmd.NewCommand("rev-list", "--all")
revListReader, revListReaderClose := cmd.MakeStdoutPipe() revListReader, revListReaderClose := cmd.MakeStdoutPipe()
defer revListReaderClose() defer revListReaderClose()
err := cmd.WithDir(repo.Path). err := cmd.WithDir(repo.Path).
WithPipelineFunc(func(context gitcmd.Context) (err error) { WithPipelineFunc(func(context gitcmd.Context) (err error) {
results, err = findLFSFileFunc(repo, objectID, revListReader) results, err = findLFSFileFunc(ctx, repo, objectID, revListReader)
return err return err
}).RunWithStderr(repo.Ctx) }).RunWithStderr(ctx)
return results, err return results, err
} }
func findLFSFileFunc(repo *git.Repository, objectID git.ObjectID, revListReader io.Reader) ([]*LFSResult, error) { func findLFSFileFunc(ctx context.Context, repo *git.Repository, objectID git.ObjectID, revListReader io.Reader) ([]*LFSResult, error) {
resultsMap := map[string]*LFSResult{} resultsMap := map[string]*LFSResult{}
results := make([]*LFSResult, 0) results := make([]*LFSResult, 0)
// Next feed the commits in order into cat-file --batch, followed by their trees and sub trees as necessary. // Next feed the commits in order into cat-file --batch, followed by their trees and sub trees as necessary.
// so let's create a batch stdin and stdout // so let's create a batch stdin and stdout
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -145,6 +146,6 @@ func findLFSFileFunc(repo *git.Repository, objectID git.ObjectID, revListReader
} }
sort.Sort(lfsResultSlice(results)) sort.Sort(lfsResultSlice(results))
err = fillResultNameRev(repo.Ctx, repo.Path, results) err = fillResultNameRev(ctx, repo.Path, results)
return results, err return results, err
} }
+2 -2
View File
@@ -15,13 +15,13 @@ import (
func TestFindLFSFile(t *testing.T) { func TestFindLFSFile(t *testing.T) {
repoPath := "../../../tests/gitea-repositories-meta/user2/lfs.git" repoPath := "../../../tests/gitea-repositories-meta/user2/lfs.git"
gitRepo, err := git.OpenRepository(t.Context(), repoPath) gitRepo, err := git.OpenRepository(repoPath)
require.NoError(t, err) require.NoError(t, err)
defer gitRepo.Close() defer gitRepo.Close()
objectID := git.MustIDFromString("2b6c6c4eaefa24b22f2092c3d54b263ff26feb58") objectID := git.MustIDFromString("2b6c6c4eaefa24b22f2092c3d54b263ff26feb58")
stats, err := FindLFSFile(gitRepo, objectID) stats, err := FindLFSFile(t.Context(), gitRepo, objectID)
require.NoError(t, err) require.NoError(t, err)
tm, err := time.Parse(time.RFC3339, "2022-12-21T17:56:42-05:00") tm, err := time.Parse(time.RFC3339, "2022-12-21T17:56:42-05:00")
+3 -2
View File
@@ -4,6 +4,7 @@
package git package git
import ( import (
"context"
"regexp" "regexp"
"strings" "strings"
@@ -50,8 +51,8 @@ type Reference struct {
} }
// Commit return the commit of the reference // Commit return the commit of the reference
func (ref *Reference) Commit() (*Commit, error) { func (ref *Reference) Commit(ctx context.Context) (*Commit, error) {
return ref.repo.getCommit(ref.Object) return ref.repo.getCommit(ctx, ref.Object)
} }
// ShortName returns the short name of the reference // ShortName returns the short name of the reference
+22 -5
View File
@@ -19,6 +19,23 @@ import (
"gitea.dev/modules/proxy" "gitea.dev/modules/proxy"
) )
type RepositoryFacade interface {
RelativePath() string
}
type RepositoryBase struct {
Path string
LastCommitCache *LastCommitCache
tagCache *ObjectCache[*Tag]
objectFormatCache ObjectFormat
}
func prepareRepositoryBase(repoPath string) RepositoryBase {
return RepositoryBase{Path: repoPath, tagCache: newObjectCache[*Tag]()}
}
const prettyLogFormat = `--pretty=format:%H` const prettyLogFormat = `--pretty=format:%H`
func (repo *Repository) ShowPrettyFormatLogToList(ctx context.Context, revisionRange string) ([]*Commit, error) { func (repo *Repository) ShowPrettyFormatLogToList(ctx context.Context, revisionRange string) ([]*Commit, error) {
@@ -29,10 +46,10 @@ func (repo *Repository) ShowPrettyFormatLogToList(ctx context.Context, revisionR
if err != nil { if err != nil {
return nil, err return nil, err
} }
return repo.parsePrettyFormatLogToList(logs) return repo.parsePrettyFormatLogToList(ctx, logs)
} }
func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, error) { func (repo *Repository) parsePrettyFormatLogToList(ctx context.Context, logs []byte) ([]*Commit, error) {
var commits []*Commit var commits []*Commit
if len(logs) == 0 { if len(logs) == 0 {
return commits, nil return commits, nil
@@ -41,7 +58,7 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro
parts := bytes.SplitSeq(logs, []byte{'\n'}) parts := bytes.SplitSeq(logs, []byte{'\n'})
for commitID := range parts { for commitID := range parts {
commit, err := repo.GetCommit(string(commitID)) commit, err := repo.GetCommit(ctx, string(commitID))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -81,12 +98,12 @@ func InitRepository(ctx context.Context, repoPath string, bare bool, objectForma
} }
// IsEmpty Check if repository is empty. // IsEmpty Check if repository is empty.
func (repo *Repository) IsEmpty() (bool, error) { func (repo *Repository) IsEmpty(ctx context.Context) (bool, error) {
stdout, _, err := gitcmd.NewCommand(). stdout, _, err := gitcmd.NewCommand().
AddOptionFormat("--git-dir=%s", repo.Path). AddOptionFormat("--git-dir=%s", repo.Path).
AddArguments("rev-list", "-n", "1", "--all"). AddArguments("rev-list", "-n", "1", "--all").
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
if (gitcmd.IsErrorExitCode(err, 1) && err.Stderr() == "") || gitcmd.IsErrorExitCode(err, 129) { if (gitcmd.IsErrorExitCode(err, 1) && err.Stderr() == "") || gitcmd.IsErrorExitCode(err, 129) {
// git 2.11 exits with 129 if the repo is empty // git 2.11 exits with 129 if the repo is empty
+9 -19
View File
@@ -7,7 +7,6 @@
package git package git
import ( import (
"context"
"path/filepath" "path/filepath"
gitealog "gitea.dev/modules/log" gitealog "gitea.dev/modules/log"
@@ -24,22 +23,14 @@ import (
const isGogit = true const isGogit = true
// Repository represents a Git repository.
type Repository struct { type Repository struct {
Path string RepositoryBase
tagCache *ObjectCache[*Tag]
gogitRepo *gogit.Repository gogitRepo *gogit.Repository
gogitStorage *filesystem.Storage gogitStorage *filesystem.Storage
Ctx context.Context
LastCommitCache *LastCommitCache
objectFormat ObjectFormat
} }
// OpenRepository opens the repository at the given path within the context.Context func OpenRepository(repoPath string) (*Repository, error) {
func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
repoPath, err := filepath.Abs(repoPath) repoPath, err := filepath.Abs(repoPath)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -74,14 +65,13 @@ func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
return nil, err return nil, err
} }
return &Repository{ repo := &Repository{
Path: repoPath, RepositoryBase: prepareRepositoryBase(repoPath),
gogitRepo: gogitRepo, gogitRepo: gogitRepo,
gogitStorage: storage, gogitStorage: storage,
tagCache: newObjectCache[*Tag](), }
Ctx: ctx, repo.objectFormatCache = ParseGogitHash(plumbing.ZeroHash).Type()
objectFormat: ParseGogitHash(plumbing.ZeroHash).Type(), return repo, nil
}, nil
} }
// Close this repository, in particular close the underlying gogitStorage if this is not nil // Close this repository, in particular close the underlying gogitStorage if this is not nil
+13 -17
View File
@@ -12,29 +12,21 @@ import (
"sync" "sync"
"gitea.dev/modules/log" "gitea.dev/modules/log"
"gitea.dev/modules/setting"
"gitea.dev/modules/util" "gitea.dev/modules/util"
) )
const isGogit = false const isGogit = false
// Repository represents a Git repository.
type Repository struct { type Repository struct {
Path string RepositoryBase
tagCache *ObjectCache[*Tag]
mu sync.Mutex mu sync.Mutex
catFileBatchCloser CatFileBatchCloser catFileBatchCloser CatFileBatchCloser
catFileBatchInUse bool catFileBatchInUse bool
Ctx context.Context
LastCommitCache *LastCommitCache
objectFormat ObjectFormat
} }
// OpenRepository opens the repository at the given path with the provided context. func OpenRepository(repoPath string) (*Repository, error) {
func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
repoPath, err := filepath.Abs(repoPath) repoPath, err := filepath.Abs(repoPath)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -46,12 +38,7 @@ func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
if !exist { if !exist {
return nil, util.NewNotExistErrorf("no such file or directory") return nil, util.NewNotExistErrorf("no such file or directory")
} }
return &Repository{RepositoryBase: prepareRepositoryBase(repoPath)}, nil
return &Repository{
Path: repoPath,
tagCache: newObjectCache[*Tag](),
Ctx: ctx,
}, nil
} }
// CatFileBatch obtains a "batch object provider" for this repository. // CatFileBatch obtains a "batch object provider" for this repository.
@@ -60,6 +47,14 @@ func (repo *Repository) CatFileBatch(ctx context.Context) (_ CatFileBatch, close
repo.mu.Lock() repo.mu.Lock()
defer repo.mu.Unlock() defer repo.mu.Unlock()
if repo.catFileBatchCloser != nil && !repo.catFileBatchInUse {
if ctx != repo.catFileBatchCloser.Context() {
repo.catFileBatchCloser.Close()
repo.catFileBatchCloser = nil
repo.catFileBatchInUse = false
}
}
if repo.catFileBatchCloser == nil { if repo.catFileBatchCloser == nil {
repo.catFileBatchCloser, err = NewBatch(ctx, repo.Path) repo.catFileBatchCloser, err = NewBatch(ctx, repo.Path)
if err != nil { if err != nil {
@@ -87,6 +82,7 @@ func (repo *Repository) CatFileBatch(ctx context.Context) (_ CatFileBatch, close
func (repo *Repository) Close() error { func (repo *Repository) Close() error {
if repo == nil { if repo == nil {
setting.PanicInDevOrTesting("don't close a nil repository")
return nil return nil
} }
repo.mu.Lock() repo.mu.Lock()
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func TestRepoCatFileBatch(t *testing.T) { func TestRepoCatFileBatch(t *testing.T) {
t.Run("MissingRepoAndClose", func(t *testing.T) { t.Run("MissingRepoAndClose", func(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) repo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
require.NoError(t, err) require.NoError(t, err)
repo.Path = "/no-such" // when the repo is missing (it usually occurs during testing because the fixtures are synced frequently) repo.Path = "/no-such" // when the repo is missing (it usually occurs during testing because the fixtures are synced frequently)
_, _, err = repo.CatFileBatch(t.Context()) _, _, err = repo.CatFileBatch(t.Context())
+4 -4
View File
@@ -14,7 +14,7 @@ import (
func TestRepository_GetBlob_Found(t *testing.T) { func TestRepository_GetBlob_Found(t *testing.T) {
repoPath := filepath.Join(testReposDir, "repo1_bare") repoPath := filepath.Join(testReposDir, "repo1_bare")
r, err := OpenRepository(t.Context(), repoPath) r, err := OpenRepository(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
defer r.Close() defer r.Close()
@@ -30,7 +30,7 @@ func TestRepository_GetBlob_Found(t *testing.T) {
blob, err := r.GetBlob(testCase.OID) blob, err := r.GetBlob(testCase.OID)
assert.NoError(t, err) assert.NoError(t, err)
dataReader, err := blob.DataAsync() dataReader, err := blob.DataAsync(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
data, err := io.ReadAll(dataReader) data, err := io.ReadAll(dataReader)
@@ -42,7 +42,7 @@ func TestRepository_GetBlob_Found(t *testing.T) {
func TestRepository_GetBlob_NotExist(t *testing.T) { func TestRepository_GetBlob_NotExist(t *testing.T) {
repoPath := filepath.Join(testReposDir, "repo1_bare") repoPath := filepath.Join(testReposDir, "repo1_bare")
r, err := OpenRepository(t.Context(), repoPath) r, err := OpenRepository(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
defer r.Close() defer r.Close()
@@ -56,7 +56,7 @@ func TestRepository_GetBlob_NotExist(t *testing.T) {
func TestRepository_GetBlob_NoId(t *testing.T) { func TestRepository_GetBlob_NoId(t *testing.T) {
repoPath := filepath.Join(testReposDir, "repo1_bare") repoPath := filepath.Join(testReposDir, "repo1_bare")
r, err := OpenRepository(t.Context(), repoPath) r, err := OpenRepository(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
defer r.Close() defer r.Close()
+4 -2
View File
@@ -5,6 +5,8 @@
package git package git
import ( import (
"context"
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/git/gitcmd"
) )
@@ -12,13 +14,13 @@ import (
const BranchPrefix = "refs/heads/" const BranchPrefix = "refs/heads/"
// AddRemote adds a new remote to repository. // AddRemote adds a new remote to repository.
func (repo *Repository) AddRemote(name, url string, fetch bool) error { func (repo *Repository) AddRemote(ctx context.Context, name, url string, fetch bool) error {
cmd := gitcmd.NewCommand("remote", "add") cmd := gitcmd.NewCommand("remote", "add")
if fetch { if fetch {
cmd.AddArguments("-f") cmd.AddArguments("-f")
} }
_, _, err := cmd.AddDynamicArguments(name, url). _, _, err := cmd.AddDynamicArguments(name, url).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
return err return err
} }
+9 -8
View File
@@ -7,6 +7,7 @@
package git package git
import ( import (
"context"
"sort" "sort"
"strings" "strings"
@@ -19,7 +20,7 @@ import (
// Unlike the implementation of IsObjectExist in nogogit edition, it does not support short hashes here. // Unlike the implementation of IsObjectExist in nogogit edition, it does not support short hashes here.
// For example, IsObjectExist("153f451") will return false, but it will return true in nogogit edition. // For example, IsObjectExist("153f451") will return false, but it will return true in nogogit edition.
// To fix this, the solution could be adding support for short hashes in gogit edition if it's really needed. // To fix this, the solution could be adding support for short hashes in gogit edition if it's really needed.
func (repo *Repository) IsObjectExist(name string) bool { func (repo *Repository) IsObjectExist(_ context.Context, name string) bool {
if name == "" { if name == "" {
return false return false
} }
@@ -33,7 +34,7 @@ func (repo *Repository) IsObjectExist(name string) bool {
// Unlike the implementation of IsObjectExist in nogogit edition, it does not support blob hashes here. // Unlike the implementation of IsObjectExist in nogogit edition, it does not support blob hashes here.
// For example, IsObjectExist([existing_blob_hash]) will return false, but it will return true in nogogit edition. // For example, IsObjectExist([existing_blob_hash]) will return false, but it will return true in nogogit edition.
// To fix this, the solution could be refusing to support blob hashes in nogogit edition since a blob hash is not a reference. // To fix this, the solution could be refusing to support blob hashes in nogogit edition since a blob hash is not a reference.
func (repo *Repository) IsReferenceExist(name string) bool { func (repo *Repository) IsReferenceExist(_ context.Context, name string) bool {
if name == "" { if name == "" {
return false return false
} }
@@ -44,7 +45,7 @@ func (repo *Repository) IsReferenceExist(name string) bool {
} }
// IsBranchExist returns true if given branch exists in current repository. // IsBranchExist returns true if given branch exists in current repository.
func (repo *Repository) IsBranchExist(name string) bool { func (repo *Repository) IsBranchExist(_ context.Context, name string) bool {
if name == "" { if name == "" {
return false return false
} }
@@ -60,7 +61,7 @@ func (repo *Repository) IsBranchExist(name string) bool {
// Branches are returned with sort of `-committerdate` as the nogogit // Branches are returned with sort of `-committerdate` as the nogogit
// implementation. This requires full fetch, sort and then the // implementation. This requires full fetch, sort and then the
// skip/limit applies later as gogit returns in undefined order. // skip/limit applies later as gogit returns in undefined order.
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) { func (repo *Repository) GetBranchNames(_ context.Context, skip, limit int) ([]string, int, error) {
type BranchData struct { type BranchData struct {
name string name string
committerDate int64 committerDate int64
@@ -100,7 +101,7 @@ func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
} }
// WalkReferences walks all the references from the repository // WalkReferences walks all the references from the repository
func (repo *Repository) WalkReferences(arg ObjectType, skip, limit int, walkfn func(sha1, refname string) error) (int, error) { func (repo *Repository) WalkReferences(ctx context.Context, arg ObjectType, skip, limit int, walkfn func(sha1, refname string) error) (int, error) {
i := 0 i := 0
var iter storer.ReferenceIter var iter storer.ReferenceIter
var err error var err error
@@ -130,13 +131,13 @@ func (repo *Repository) WalkReferences(arg ObjectType, skip, limit int, walkfn f
if limit != 0 && i >= skip+limit { if limit != 0 && i >= skip+limit {
return storer.ErrStop return storer.ErrStop
} }
return nil return ctx.Err()
}) })
return i, err return i, err
} }
// GetRefsBySha returns all references filtered with prefix that belong to a sha commit hash // GetRefsBySha returns all references filtered with prefix that belong to a sha commit hash
func (repo *Repository) GetRefsBySha(sha, prefix string) ([]string, error) { func (repo *Repository) GetRefsBySha(ctx context.Context, sha, prefix string) ([]string, error) {
var revList []string var revList []string
iter, err := repo.gogitRepo.References() iter, err := repo.gogitRepo.References()
if err != nil { if err != nil {
@@ -146,7 +147,7 @@ func (repo *Repository) GetRefsBySha(sha, prefix string) ([]string, error) {
if ref.Hash().String() == sha && strings.HasPrefix(string(ref.Name()), prefix) { if ref.Hash().String() == sha && strings.HasPrefix(string(ref.Name()), prefix) {
revList = append(revList, string(ref.Name())) revList = append(revList, string(ref.Name()))
} }
return nil return ctx.Err()
}) })
return revList, err return revList, err
} }
+12 -12
View File
@@ -18,12 +18,12 @@ import (
// IsObjectExist returns true if the given object exists in the repository. // IsObjectExist returns true if the given object exists in the repository.
// FIXME: this function doesn't seem right, it is only used by GarbageCollectLFSMetaObjectsForRepo // FIXME: this function doesn't seem right, it is only used by GarbageCollectLFSMetaObjectsForRepo
func (repo *Repository) IsObjectExist(name string) bool { func (repo *Repository) IsObjectExist(ctx context.Context, name string) bool {
if name == "" { if name == "" {
return false return false
} }
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
log.Debug("Error opening CatFileBatch %v", err) log.Debug("Error opening CatFileBatch %v", err)
return false return false
@@ -38,12 +38,12 @@ func (repo *Repository) IsObjectExist(name string) bool {
} }
// IsReferenceExist returns true if given reference exists in the repository. // IsReferenceExist returns true if given reference exists in the repository.
func (repo *Repository) IsReferenceExist(name string) bool { func (repo *Repository) IsReferenceExist(ctx context.Context, name string) bool {
if name == "" { if name == "" {
return false return false
} }
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
log.Error("Error opening CatFileBatch %v", err) log.Error("Error opening CatFileBatch %v", err)
return false return false
@@ -54,23 +54,23 @@ func (repo *Repository) IsReferenceExist(name string) bool {
} }
// IsBranchExist returns true if given branch exists in current repository. // IsBranchExist returns true if given branch exists in current repository.
func (repo *Repository) IsBranchExist(name string) bool { func (repo *Repository) IsBranchExist(ctx context.Context, name string) bool {
if repo == nil || name == "" { if repo == nil || name == "" {
return false return false
} }
return repo.IsReferenceExist(BranchPrefix + name) return repo.IsReferenceExist(ctx, BranchPrefix+name)
} }
// GetBranchNames returns branches from the repository, skipping "skip" initial branches and // GetBranchNames returns branches from the repository, skipping "skip" initial branches and
// returning at most "limit" branches, or all branches if "limit" is 0. // returning at most "limit" branches, or all branches if "limit" is 0.
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) { func (repo *Repository) GetBranchNames(ctx context.Context, skip, limit int) ([]string, int, error) {
return callShowRef(repo.Ctx, repo.Path, BranchPrefix, gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}, skip, limit) return callShowRef(ctx, repo.Path, BranchPrefix, gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}, skip, limit)
} }
// WalkReferences walks all the references from the repository // WalkReferences walks all the references from the repository
// refType should be empty, ObjectTag or ObjectBranch. All other values are equivalent to empty. // refType should be empty, ObjectTag or ObjectBranch. All other values are equivalent to empty.
func (repo *Repository) WalkReferences(refType ObjectType, skip, limit int, walkfn func(sha1, refname string) error) (int, error) { func (repo *Repository) WalkReferences(ctx context.Context, refType ObjectType, skip, limit int, walkfn func(sha1, refname string) error) (int, error) {
var args gitcmd.TrustedCmdArgs var args gitcmd.TrustedCmdArgs
switch refType { switch refType {
case ObjectTag: case ObjectTag:
@@ -79,7 +79,7 @@ func (repo *Repository) WalkReferences(refType ObjectType, skip, limit int, walk
args = gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"} args = gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}
} }
return WalkShowRef(repo.Ctx, repo.Path, args, skip, limit, walkfn) return WalkShowRef(ctx, repo.Path, args, skip, limit, walkfn)
} }
// callShowRef return refs, if limit = 0 it will not limit // callShowRef return refs, if limit = 0 it will not limit
@@ -172,9 +172,9 @@ func WalkShowRef(ctx context.Context, repoPath string, extraArgs gitcmd.TrustedC
} }
// GetRefsBySha returns all references filtered with prefix that belong to a sha commit hash // GetRefsBySha returns all references filtered with prefix that belong to a sha commit hash
func (repo *Repository) GetRefsBySha(sha, prefix string) ([]string, error) { func (repo *Repository) GetRefsBySha(ctx context.Context, sha, prefix string) ([]string, error) {
var revList []string var revList []string
_, err := WalkShowRef(repo.Ctx, repo.Path, nil, 0, 0, func(walkSha, refname string) error { _, err := WalkShowRef(ctx, repo.Path, nil, 0, 0, func(walkSha, refname string) error {
if walkSha == sha && strings.HasPrefix(refname, prefix) { if walkSha == sha && strings.HasPrefix(refname, prefix) {
revList = append(revList, refname) revList = append(revList, refname)
} }
+22 -20
View File
@@ -13,25 +13,25 @@ import (
func TestRepository_GetBranches(t *testing.T) { func TestRepository_GetBranches(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
branches, countAll, err := bareRepo1.GetBranchNames(0, 2) branches, countAll, err := bareRepo1.GetBranchNames(t.Context(), 0, 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, branches, 2) assert.Len(t, branches, 2)
assert.Equal(t, 3, countAll) assert.Equal(t, 3, countAll)
assert.ElementsMatch(t, []string{"master", "branch2"}, branches) assert.ElementsMatch(t, []string{"master", "branch2"}, branches)
branches, countAll, err = bareRepo1.GetBranchNames(0, 0) branches, countAll, err = bareRepo1.GetBranchNames(t.Context(), 0, 0)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, branches, 3) assert.Len(t, branches, 3)
assert.Equal(t, 3, countAll) assert.Equal(t, 3, countAll)
assert.ElementsMatch(t, []string{"master", "branch2", "branch1"}, branches) assert.ElementsMatch(t, []string{"master", "branch2", "branch1"}, branches)
branches, countAll, err = bareRepo1.GetBranchNames(5, 1) branches, countAll, err = bareRepo1.GetBranchNames(t.Context(), 5, 1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, branches) assert.Empty(t, branches)
@@ -41,14 +41,14 @@ func TestRepository_GetBranches(t *testing.T) {
func BenchmarkRepository_GetBranches(b *testing.B) { func BenchmarkRepository_GetBranches(b *testing.B) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(b.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
defer bareRepo1.Close() defer bareRepo1.Close()
for b.Loop() { for b.Loop() {
_, _, err := bareRepo1.GetBranchNames(0, 0) _, _, err := bareRepo1.GetBranchNames(b.Context(), 0, 0)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@@ -57,47 +57,48 @@ func BenchmarkRepository_GetBranches(b *testing.B) {
func TestGetRefsBySha(t *testing.T) { func TestGetRefsBySha(t *testing.T) {
bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls") bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls")
bareRepo5, err := OpenRepository(t.Context(), bareRepo5Path) bareRepo5, err := OpenRepository(bareRepo5Path)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer bareRepo5.Close() defer bareRepo5.Close()
// do not exist // do not exist
branches, err := bareRepo5.GetRefsBySha("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "") branches, err := bareRepo5.GetRefsBySha(t.Context(), "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "")
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, branches) assert.Empty(t, branches)
// refs/pull/1/head // refs/pull/1/head
branches, err = bareRepo5.GetRefsBySha("c83380d7056593c51a699d12b9c00627bd5743e9", PullPrefix) branches, err = bareRepo5.GetRefsBySha(t.Context(), "c83380d7056593c51a699d12b9c00627bd5743e9", PullPrefix)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []string{"refs/pull/1/head"}, branches) assert.Equal(t, []string{"refs/pull/1/head"}, branches)
branches, err = bareRepo5.GetRefsBySha("d8e0bbb45f200e67d9a784ce55bd90821af45ebd", BranchPrefix) branches, err = bareRepo5.GetRefsBySha(t.Context(), "d8e0bbb45f200e67d9a784ce55bd90821af45ebd", BranchPrefix)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []string{"refs/heads/master", "refs/heads/master-clone"}, branches) assert.Equal(t, []string{"refs/heads/master", "refs/heads/master-clone"}, branches)
branches, err = bareRepo5.GetRefsBySha("58a4bcc53ac13e7ff76127e0fb518b5262bf09af", BranchPrefix) branches, err = bareRepo5.GetRefsBySha(t.Context(), "58a4bcc53ac13e7ff76127e0fb518b5262bf09af", BranchPrefix)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, []string{"refs/heads/test-patch-1"}, branches) assert.Equal(t, []string{"refs/heads/test-patch-1"}, branches)
} }
func BenchmarkGetRefsBySha(b *testing.B) { func BenchmarkGetRefsBySha(b *testing.B) {
bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls") bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls")
bareRepo5, err := OpenRepository(b.Context(), bareRepo5Path) bareRepo5, err := OpenRepository(bareRepo5Path)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
defer bareRepo5.Close() defer bareRepo5.Close()
_, _ = bareRepo5.GetRefsBySha("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "") _, _ = bareRepo5.GetRefsBySha(b.Context(), "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "")
_, _ = bareRepo5.GetRefsBySha("d8e0bbb45f200e67d9a784ce55bd90821af45ebd", "") _, _ = bareRepo5.GetRefsBySha(b.Context(), "d8e0bbb45f200e67d9a784ce55bd90821af45ebd", "")
_, _ = bareRepo5.GetRefsBySha("c83380d7056593c51a699d12b9c00627bd5743e9", "") _, _ = bareRepo5.GetRefsBySha(b.Context(), "c83380d7056593c51a699d12b9c00627bd5743e9", "")
_, _ = bareRepo5.GetRefsBySha("58a4bcc53ac13e7ff76127e0fb518b5262bf09af", "") _, _ = bareRepo5.GetRefsBySha(b.Context(), "58a4bcc53ac13e7ff76127e0fb518b5262bf09af", "")
} }
func TestRepository_IsObjectExist(t *testing.T) { func TestRepository_IsObjectExist(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) ctx := t.Context()
repo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
require.NoError(t, err) require.NoError(t, err)
defer repo.Close() defer repo.Close()
@@ -143,13 +144,14 @@ func TestRepository_IsObjectExist(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, repo.IsObjectExist(tt.arg)) assert.Equal(t, tt.want, repo.IsObjectExist(ctx, tt.arg))
}) })
} }
} }
func TestRepository_IsReferenceExist(t *testing.T) { func TestRepository_IsReferenceExist(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) ctx := t.Context()
repo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
require.NoError(t, err) require.NoError(t, err)
defer repo.Close() defer repo.Close()
@@ -195,7 +197,7 @@ func TestRepository_IsReferenceExist(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, repo.IsReferenceExist(tt.arg)) assert.Equal(t, tt.want, repo.IsReferenceExist(ctx, tt.arg))
}) })
} }
} }
+53 -52
View File
@@ -6,6 +6,7 @@ package git
import ( import (
"bytes" "bytes"
"context"
"io" "io"
"strconv" "strconv"
"strings" "strings"
@@ -15,36 +16,36 @@ import (
) )
// GetBranchCommitID returns last commit ID string of given branch. // GetBranchCommitID returns last commit ID string of given branch.
func (repo *Repository) GetBranchCommitID(name string) (string, error) { func (repo *Repository) GetBranchCommitID(ctx context.Context, name string) (string, error) {
return repo.GetRefCommitID(BranchPrefix + name) return repo.GetRefCommitID(ctx, BranchPrefix+name)
} }
// GetTagCommitID returns last commit ID string of given tag. // GetTagCommitID returns last commit ID string of given tag.
func (repo *Repository) GetTagCommitID(name string) (string, error) { func (repo *Repository) GetTagCommitID(ctx context.Context, name string) (string, error) {
return repo.GetRefCommitID(TagPrefix + name) return repo.GetRefCommitID(ctx, TagPrefix+name)
} }
// GetCommit returns a commit object of by the git ref. // GetCommit returns a commit object of by the git ref.
func (repo *Repository) GetCommit(ref string) (*Commit, error) { func (repo *Repository) GetCommit(ctx context.Context, ref string) (*Commit, error) {
id, err := repo.ConvertToGitID(ref) id, err := repo.ConvertToGitID(ctx, ref)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return repo.getCommit(id) return repo.getCommit(ctx, id)
} }
// GetBranchCommit returns the last commit of given branch. // GetBranchCommit returns the last commit of given branch.
func (repo *Repository) GetBranchCommit(name string) (*Commit, error) { func (repo *Repository) GetBranchCommit(ctx context.Context, name string) (*Commit, error) {
return repo.GetCommit(RefNameFromBranch(name).String()) return repo.GetCommit(ctx, RefNameFromBranch(name).String())
} }
// GetTagCommit get the commit of the specific tag via name // GetTagCommit get the commit of the specific tag via name
func (repo *Repository) GetTagCommit(name string) (*Commit, error) { func (repo *Repository) GetTagCommit(ctx context.Context, name string) (*Commit, error) {
return repo.GetCommit(RefNameFromTag(name).String()) return repo.GetCommit(ctx, RefNameFromTag(name).String())
} }
func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Commit, error) { func (repo *Repository) getCommitByPathWithID(ctx context.Context, id ObjectID, relpath string) (*Commit, error) {
// File name starts with ':' must be escaped. // File name starts with ':' must be escaped.
if strings.HasPrefix(relpath, ":") { if strings.HasPrefix(relpath, ":") {
relpath = `\` + relpath relpath = `\` + relpath
@@ -54,7 +55,7 @@ func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Com
AddDynamicArguments(id.String()). AddDynamicArguments(id.String()).
AddDashesAndList(relpath). AddDashesAndList(relpath).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if runErr != nil { if runErr != nil {
return nil, runErr return nil, runErr
} }
@@ -64,20 +65,20 @@ func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Com
return nil, err return nil, err
} }
return repo.getCommit(id) return repo.getCommit(ctx, id)
} }
// GetCommitByPath returns the last commit of relative path. // GetCommitByPath returns the last commit of relative path.
func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { func (repo *Repository) GetCommitByPath(ctx context.Context, relpath string) (*Commit, error) {
stdout, _, runErr := gitcmd.NewCommand("log", "-1", prettyLogFormat). stdout, _, runErr := gitcmd.NewCommand("log", "-1", prettyLogFormat).
AddDashesAndList(relpath). AddDashesAndList(relpath).
WithDir(repo.Path). WithDir(repo.Path).
RunStdBytes(repo.Ctx) RunStdBytes(ctx)
if runErr != nil { if runErr != nil {
return nil, runErr return nil, runErr
} }
commits, err := repo.parsePrettyFormatLogToList(stdout) commits, err := repo.parsePrettyFormatLogToList(ctx, stdout)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -88,7 +89,7 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
} }
// commitsByRangeWithTime returns the specific page commits before current revision, with not, since, until support // commitsByRangeWithTime returns the specific page commits before current revision, with not, since, until support
func (repo *Repository) commitsByRangeWithTime(id ObjectID, page, pageSize int, not, since, until string) ([]*Commit, error) { func (repo *Repository) commitsByRangeWithTime(ctx context.Context, id ObjectID, page, pageSize int, not, since, until string) ([]*Commit, error) {
cmd := gitcmd.NewCommand("log"). cmd := gitcmd.NewCommand("log").
AddOptionFormat("--skip=%d", (page-1)*pageSize). AddOptionFormat("--skip=%d", (page-1)*pageSize).
AddOptionFormat("--max-count=%d", pageSize). AddOptionFormat("--max-count=%d", pageSize).
@@ -105,15 +106,15 @@ func (repo *Repository) commitsByRangeWithTime(id ObjectID, page, pageSize int,
cmd.AddOptionFormat("--until=%s", until) cmd.AddOptionFormat("--until=%s", until)
} }
stdout, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx) stdout, _, err := cmd.WithDir(repo.Path).RunStdBytes(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return repo.parsePrettyFormatLogToList(stdout) return repo.parsePrettyFormatLogToList(ctx, stdout)
} }
func (repo *Repository) searchCommits(id ObjectID, opts SearchCommitsOptions) ([]*Commit, error) { func (repo *Repository) searchCommits(ctx context.Context, id ObjectID, opts SearchCommitsOptions) ([]*Commit, error) {
// add common arguments to git command // add common arguments to git command
addCommonSearchArgs := func(c *gitcmd.Command) { addCommonSearchArgs := func(c *gitcmd.Command) {
// ignore case // ignore case
@@ -159,7 +160,7 @@ func (repo *Repository) searchCommits(id ObjectID, opts SearchCommitsOptions) ([
// search for commits matching given constraints and keywords in commit msg // search for commits matching given constraints and keywords in commit msg
addCommonSearchArgs(cmd) addCommonSearchArgs(cmd)
stdout, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx) stdout, _, err := cmd.WithDir(repo.Path).RunStdBytes(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -180,7 +181,7 @@ func (repo *Repository) searchCommits(id ObjectID, opts SearchCommitsOptions) ([
hashCmd.AddDynamicArguments(v) hashCmd.AddDynamicArguments(v)
// search with given constraints for commit matching sha hash of v // search with given constraints for commit matching sha hash of v
hashMatching, _, err := hashCmd.WithDir(repo.Path).RunStdBytes(repo.Ctx) hashMatching, _, err := hashCmd.WithDir(repo.Path).RunStdBytes(ctx)
if err != nil || bytes.Contains(stdout, hashMatching) { if err != nil || bytes.Contains(stdout, hashMatching) {
continue continue
} }
@@ -189,17 +190,17 @@ func (repo *Repository) searchCommits(id ObjectID, opts SearchCommitsOptions) ([
} }
} }
return repo.parsePrettyFormatLogToList(bytes.TrimSuffix(stdout, []byte{'\n'})) return repo.parsePrettyFormatLogToList(ctx, bytes.TrimSuffix(stdout, []byte{'\n'}))
} }
// FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2 // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
// You must ensure that id1 and id2 are valid commit ids. // You must ensure that id1 and id2 are valid commit ids.
func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) { func (repo *Repository) FileChangedBetweenCommits(ctx context.Context, filename, id1, id2 string) (bool, error) {
stdout, _, err := gitcmd.NewCommand("diff", "--name-only", "-z"). stdout, _, err := gitcmd.NewCommand("diff", "--name-only", "-z").
AddDynamicArguments(id1, id2). AddDynamicArguments(id1, id2).
AddDashesAndList(filename). AddDashesAndList(filename).
WithDir(repo.Path). WithDir(repo.Path).
RunStdBytes(repo.Ctx) RunStdBytes(ctx)
if err != nil { if err != nil {
return false, err return false, err
} }
@@ -219,7 +220,7 @@ type CommitsByFileAndRangeOptions struct {
} }
// CommitsByFileAndRange return the commits according revision file and the page // CommitsByFileAndRange return the commits according revision file and the page
func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions) (commits []*Commit, hasMore bool, _ error) { func (repo *Repository) CommitsByFileAndRange(ctx context.Context, opts CommitsByFileAndRangeOptions) (commits []*Commit, hasMore bool, _ error) {
limit := setting.Git.CommitsRangeSize limit := setting.Git.CommitsRangeSize
gitCmd := gitcmd.NewCommand("--no-pager", "log"). gitCmd := gitcmd.NewCommand("--no-pager", "log").
AddArguments("--pretty=tformat:%H"). AddArguments("--pretty=tformat:%H").
@@ -244,7 +245,7 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
defer stdoutReaderClose() defer stdoutReaderClose()
err := gitCmd.WithDir(repo.Path). err := gitCmd.WithDir(repo.Path).
WithPipelineFunc(func(context gitcmd.Context) error { WithPipelineFunc(func(context gitcmd.Context) error {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return err return err
} }
@@ -263,14 +264,14 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
if err != nil { if err != nil {
return err return err
} }
commit, err := repo.getCommit(objectID) commit, err := repo.getCommit(ctx, objectID)
if err != nil { if err != nil {
return err return err
} }
commits = append(commits, commit) commits = append(commits, commit)
} }
}). }).
RunWithStderr(repo.Ctx) RunWithStderr(ctx)
hasMore = len(commits) > limit hasMore = len(commits) > limit
if hasMore { if hasMore {
@@ -281,7 +282,7 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
// CommitsBetween returns a list that contains commits between [after, before). After is the first item in the slice. // CommitsBetween returns a list that contains commits between [after, before). After is the first item in the slice.
// If "before" and "after" are not related, it returns the all commits for the "after" commit. // If "before" and "after" are not related, it returns the all commits for the "after" commit.
func (repo *Repository) CommitsBetween(afterRef, beforeRef RefName, limit int, optSkip ...int) ([]*Commit, error) { func (repo *Repository) CommitsBetween(ctx context.Context, afterRef, beforeRef RefName, limit int, optSkip ...int) ([]*Commit, error) {
gitCmd := func() *gitcmd.Command { gitCmd := func() *gitcmd.Command {
cmd := gitcmd.NewCommand("rev-list").WithDir(repo.Path) cmd := gitcmd.NewCommand("rev-list").WithDir(repo.Path)
if limit >= 0 { if limit >= 0 {
@@ -295,42 +296,42 @@ func (repo *Repository) CommitsBetween(afterRef, beforeRef RefName, limit int, o
var stdout []byte var stdout []byte
var err error var err error
if beforeRef == "" { if beforeRef == "" {
stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(repo.Ctx) stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(ctx)
} else { } else {
stdout, _, err = gitCmd().AddDynamicArguments(beforeRef.String() + ".." + afterRef.String()).RunStdBytes(repo.Ctx) stdout, _, err = gitCmd().AddDynamicArguments(beforeRef.String() + ".." + afterRef.String()).RunStdBytes(ctx)
if gitcmd.IsStderr(err, gitcmd.StderrNoMergeBase) { if gitcmd.IsStderr(err, gitcmd.StderrNoMergeBase) {
// future versions of git >= 2.28 are likely to return an error if before and last have become unrelated. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
// if the beforeRef and afterRef are not related (no merge base), just get all commits pushed by afterRef // if the beforeRef and afterRef are not related (no merge base), just get all commits pushed by afterRef
stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(repo.Ctx) stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(ctx)
} }
} }
if err != nil { if err != nil {
return nil, err return nil, err
} }
return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) return repo.parsePrettyFormatLogToList(ctx, bytes.TrimSpace(stdout))
} }
// commitsBefore the limit is depth, not total number of returned commits. // commitsBefore the limit is depth, not total number of returned commits.
func (repo *Repository) commitsBefore(id ObjectID, limit int) ([]*Commit, error) { func (repo *Repository) commitsBefore(ctx context.Context, id ObjectID, limit int) ([]*Commit, error) {
cmd := gitcmd.NewCommand("log", prettyLogFormat) cmd := gitcmd.NewCommand("log", prettyLogFormat)
if limit > 0 { if limit > 0 {
cmd.AddOptionFormat("-%d", limit) cmd.AddOptionFormat("-%d", limit)
} }
cmd.AddDynamicArguments(id.String()) cmd.AddDynamicArguments(id.String())
stdout, _, runErr := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx) stdout, _, runErr := cmd.WithDir(repo.Path).RunStdBytes(ctx)
if runErr != nil { if runErr != nil {
return nil, runErr return nil, runErr
} }
formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) formattedLog, err := repo.parsePrettyFormatLogToList(ctx, bytes.TrimSpace(stdout))
if err != nil { if err != nil {
return nil, err return nil, err
} }
commits := make([]*Commit, 0, len(formattedLog)) commits := make([]*Commit, 0, len(formattedLog))
for _, commit := range formattedLog { for _, commit := range formattedLog {
branches, err := repo.getBranches(nil, commit.ID.String(), 2) branches, err := repo.getBranches(ctx, nil, commit.ID.String(), 2)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -345,22 +346,22 @@ func (repo *Repository) commitsBefore(id ObjectID, limit int) ([]*Commit, error)
return commits, nil return commits, nil
} }
func (repo *Repository) getCommitsBefore(id ObjectID) ([]*Commit, error) { func (repo *Repository) getCommitsBefore(ctx context.Context, id ObjectID) ([]*Commit, error) {
return repo.commitsBefore(id, 0) return repo.commitsBefore(ctx, id, 0)
} }
func (repo *Repository) getCommitsBeforeLimit(id ObjectID, num int) ([]*Commit, error) { func (repo *Repository) getCommitsBeforeLimit(ctx context.Context, id ObjectID, num int) ([]*Commit, error) {
return repo.commitsBefore(id, num) return repo.commitsBefore(ctx, id, num)
} }
func (repo *Repository) getBranches(env []string, commitID string, limit int) ([]string, error) { func (repo *Repository) getBranches(ctx context.Context, env []string, commitID string, limit int) ([]string, error) {
stdout, _, err := gitcmd.NewCommand("for-each-ref", "--format=%(refname:strip=2)"). stdout, _, err := gitcmd.NewCommand("for-each-ref", "--format=%(refname:strip=2)").
AddOptionFormat("--count=%d", limit). AddOptionFormat("--count=%d", limit).
AddOptionValues("--contains", commitID). AddOptionValues("--contains", commitID).
AddArguments(BranchPrefix). AddArguments(BranchPrefix).
WithEnv(env). WithEnv(env).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -368,11 +369,11 @@ func (repo *Repository) getBranches(env []string, commitID string, limit int) ([
} }
// GetCommitsFromIDs get commits from commit IDs // GetCommitsFromIDs get commits from commit IDs
func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit { func (repo *Repository) GetCommitsFromIDs(ctx context.Context, commitIDs []string) []*Commit {
commits := make([]*Commit, 0, len(commitIDs)) commits := make([]*Commit, 0, len(commitIDs))
for _, commitID := range commitIDs { for _, commitID := range commitIDs {
commit, err := repo.GetCommit(commitID) commit, err := repo.GetCommit(ctx, commitID)
if err == nil && commit != nil { if err == nil && commit != nil {
commits = append(commits, commit) commits = append(commits, commit)
} }
@@ -382,11 +383,11 @@ func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit {
} }
// IsCommitInBranch check if the commit is on the branch // IsCommitInBranch check if the commit is on the branch
func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) { func (repo *Repository) IsCommitInBranch(ctx context.Context, commitID, branch string) (r bool, err error) {
stdout, _, err := gitcmd.NewCommand("branch", "--contains"). stdout, _, err := gitcmd.NewCommand("branch", "--contains").
AddDynamicArguments(commitID, branch). AddDynamicArguments(commitID, branch).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
return false, err return false, err
} }
@@ -394,13 +395,13 @@ func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err e
} }
// GetCommitBranchStart returns the commit where the branch diverged // GetCommitBranchStart returns the commit where the branch diverged
func (repo *Repository) GetCommitBranchStart(env []string, branch, endCommitID string) (string, error) { func (repo *Repository) GetCommitBranchStart(ctx context.Context, env []string, branch, endCommitID string) (string, error) {
cmd := gitcmd.NewCommand("log", prettyLogFormat) cmd := gitcmd.NewCommand("log", prettyLogFormat)
cmd.AddDynamicArguments(endCommitID) cmd.AddDynamicArguments(endCommitID)
stdout, _, runErr := cmd.WithDir(repo.Path). stdout, _, runErr := cmd.WithDir(repo.Path).
WithEnv(env). WithEnv(env).
RunStdBytes(repo.Ctx) RunStdBytes(ctx)
if runErr != nil { if runErr != nil {
return "", runErr return "", runErr
} }
@@ -411,7 +412,7 @@ func (repo *Repository) GetCommitBranchStart(env []string, branch, endCommitID s
// and we think this commit is the divergence point // and we think this commit is the divergence point
for part := range parts { for part := range parts {
commitID := string(part) commitID := string(part)
branches, err := repo.getBranches(env, commitID, 2) branches, err := repo.getBranches(ctx, env, commitID, 2)
if err != nil { if err != nil {
return "", err return "", err
} }
+6 -5
View File
@@ -7,6 +7,7 @@
package git package git
import ( import (
"context"
"strings" "strings"
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/git/gitcmd"
@@ -17,7 +18,7 @@ import (
) )
// GetRefCommitID returns the last commit ID string of given reference. // GetRefCommitID returns the last commit ID string of given reference.
func (repo *Repository) GetRefCommitID(name string) (string, error) { func (repo *Repository) GetRefCommitID(_ context.Context, name string) (string, error) {
if plumbing.IsHash(name) { if plumbing.IsHash(name) {
return name, nil return name, nil
} }
@@ -42,8 +43,8 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) {
} }
// ConvertToHash returns a Hash object from a potential ID string // ConvertToHash returns a Hash object from a potential ID string
func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) { func (repo *Repository) ConvertToGitID(ctx context.Context, commitID string) (ObjectID, error) {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -57,7 +58,7 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
actualCommitID, _, err := gitcmd.NewCommand("rev-parse", "--verify"). actualCommitID, _, err := gitcmd.NewCommand("rev-parse", "--verify").
AddDynamicArguments(commitID). AddDynamicArguments(commitID).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
actualCommitID = strings.TrimSpace(actualCommitID) actualCommitID = strings.TrimSpace(actualCommitID)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "unknown revision or path") || if strings.Contains(err.Error(), "unknown revision or path") ||
@@ -70,7 +71,7 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
return NewIDFromString(actualCommitID) return NewIDFromString(actualCommitID)
} }
func (repo *Repository) getCommit(id ObjectID) (*Commit, error) { func (repo *Repository) getCommit(_ context.Context, id ObjectID) (*Commit, error) {
var tagObject *object.Tag var tagObject *object.Tag
commitID := plumbing.Hash(id.RawValue()) commitID := plumbing.Hash(id.RawValue())
+10 -9
View File
@@ -6,6 +6,7 @@
package git package git
import ( import (
"context"
"errors" "errors"
"io" "io"
"strings" "strings"
@@ -15,11 +16,11 @@ import (
) )
// ResolveReference resolves a name to a reference // ResolveReference resolves a name to a reference
func (repo *Repository) ResolveReference(name string) (string, error) { func (repo *Repository) ResolveReference(ctx context.Context, name string) (string, error) {
stdout, _, err := gitcmd.NewCommand("show-ref", "--hash"). stdout, _, err := gitcmd.NewCommand("show-ref", "--hash").
AddDynamicArguments(name). AddDynamicArguments(name).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "not a valid ref") { if strings.Contains(err.Error(), "not a valid ref") {
return "", ErrNotExist{name, ""} return "", ErrNotExist{name, ""}
@@ -35,8 +36,8 @@ func (repo *Repository) ResolveReference(name string) (string, error) {
} }
// GetRefCommitID returns the last commit ID string of given reference (branch or tag). // GetRefCommitID returns the last commit ID string of given reference (branch or tag).
func (repo *Repository) GetRefCommitID(name string) (string, error) { func (repo *Repository) GetRefCommitID(ctx context.Context, name string) (string, error) {
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -50,8 +51,8 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) {
return info.ID, nil return info.ID, nil
} }
func (repo *Repository) getCommit(id ObjectID) (*Commit, error) { func (repo *Repository) getCommit(ctx context.Context, id ObjectID) (*Commit, error) {
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -110,8 +111,8 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co
} }
// ConvertToGitID returns a git object ID from the git ref, it doesn't guarantee the returned ID really exists // ConvertToGitID returns a git object ID from the git ref, it doesn't guarantee the returned ID really exists
func (repo *Repository) ConvertToGitID(ref string) (ObjectID, error) { func (repo *Repository) ConvertToGitID(ctx context.Context, ref string) (ObjectID, error) {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -122,7 +123,7 @@ func (repo *Repository) ConvertToGitID(ref string) (ObjectID, error) {
} }
} }
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+20 -20
View File
@@ -18,7 +18,7 @@ import (
func TestRepository_GetCommitBranches(t *testing.T) { func TestRepository_GetCommitBranches(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
@@ -35,9 +35,9 @@ func TestRepository_GetCommitBranches(t *testing.T) {
{"master", []string{"master"}}, {"master", []string{"master"}},
} }
for _, testCase := range testCases { for _, testCase := range testCases {
commit, err := bareRepo1.GetCommit(testCase.CommitID) commit, err := bareRepo1.GetCommit(t.Context(), testCase.CommitID)
assert.NoError(t, err) assert.NoError(t, err)
branches, err := bareRepo1.getBranches(nil, commit.ID.String(), 2) branches, err := bareRepo1.getBranches(t.Context(), nil, commit.ID.String(), 2)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, testCase.ExpectedBranches, branches) assert.Equal(t, testCase.ExpectedBranches, branches)
} }
@@ -45,12 +45,12 @@ func TestRepository_GetCommitBranches(t *testing.T) {
func TestGetTagCommitWithSignature(t *testing.T) { func TestGetTagCommitWithSignature(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
// both the tag and the commit are signed here, this validates only the commit signature // both the tag and the commit are signed here, this validates only the commit signature
commit, err := bareRepo1.GetCommit("28b55526e7100924d864dd89e35c1ea62e7a5a32") commit, err := bareRepo1.GetCommit(t.Context(), "28b55526e7100924d864dd89e35c1ea62e7a5a32")
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, commit) assert.NotNil(t, commit)
assert.NotNil(t, commit.Signature) assert.NotNil(t, commit.Signature)
@@ -60,11 +60,11 @@ func TestGetTagCommitWithSignature(t *testing.T) {
func TestGetCommitWithBadCommitID(t *testing.T) { func TestGetCommitWithBadCommitID(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
commit, err := bareRepo1.GetCommit("bad_branch") commit, err := bareRepo1.GetCommit(t.Context(), "bad_branch")
assert.Nil(t, commit) assert.Nil(t, commit)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrNotExist(err)) assert.True(t, IsErrNotExist(err))
@@ -72,22 +72,22 @@ func TestGetCommitWithBadCommitID(t *testing.T) {
func TestIsCommitInBranch(t *testing.T) { func TestIsCommitInBranch(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
result, err := bareRepo1.IsCommitInBranch("2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1") result, err := bareRepo1.IsCommitInBranch(t.Context(), "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1")
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, result) assert.True(t, result)
result, err = bareRepo1.IsCommitInBranch("2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2") result, err = bareRepo1.IsCommitInBranch(t.Context(), "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2")
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, result) assert.False(t, result)
} }
func TestRepository_CommitsBetween(t *testing.T) { func TestRepository_CommitsBetween(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo4_commitsbetween") bareRepo1Path := filepath.Join(testReposDir, "repo4_commitsbetween")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
@@ -101,7 +101,7 @@ func TestRepository_CommitsBetween(t *testing.T) {
{"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, // com2 -> com2_new {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, // com2 -> com2_new
} }
for i, c := range cases { for i, c := range cases {
commits, err := bareRepo1.CommitsBetween(c.NewID, c.OldID, -1) commits, err := bareRepo1.CommitsBetween(t.Context(), c.NewID, c.OldID, -1)
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, commits, c.ExpectedCommits, "case %d", i) assert.Len(t, commits, c.ExpectedCommits, "case %d", i)
} }
@@ -109,7 +109,7 @@ func TestRepository_CommitsBetween(t *testing.T) {
func TestGetRefCommitID(t *testing.T) { func TestGetRefCommitID(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
@@ -125,7 +125,7 @@ func TestGetRefCommitID(t *testing.T) {
} }
for _, testCase := range testCases { for _, testCase := range testCases {
commitID, err := bareRepo1.GetRefCommitID(testCase.Ref) commitID, err := bareRepo1.GetRefCommitID(t.Context(), testCase.Ref)
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, testCase.ExpectedCommitID, commitID) assert.Equal(t, testCase.ExpectedCommitID, commitID)
} }
@@ -136,17 +136,17 @@ func TestCommitsByFileAndRange(t *testing.T) {
defer test.MockVariableValue(&setting.Git.CommitsRangeSize, 2)() defer test.MockVariableValue(&setting.Git.CommitsRangeSize, 2)()
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
require.NoError(t, err) require.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
// "foo" has 3 commits in "master" branch // "foo" has 3 commits in "master" branch
commits, hasMore, err := bareRepo1.CommitsByFileAndRange(CommitsByFileAndRangeOptions{Revision: "master", File: "foo", Page: 1}) commits, hasMore, err := bareRepo1.CommitsByFileAndRange(t.Context(), CommitsByFileAndRangeOptions{Revision: "master", File: "foo", Page: 1})
require.NoError(t, err) require.NoError(t, err)
assert.True(t, hasMore) assert.True(t, hasMore)
assert.Len(t, commits, 2) assert.Len(t, commits, 2)
commits, hasMore, err = bareRepo1.CommitsByFileAndRange(CommitsByFileAndRangeOptions{Revision: "master", File: "foo", Page: 2}) commits, hasMore, err = bareRepo1.CommitsByFileAndRange(t.Context(), CommitsByFileAndRangeOptions{Revision: "master", File: "foo", Page: 2})
require.NoError(t, err) require.NoError(t, err)
assert.Len(t, commits, 1) assert.Len(t, commits, 1)
assert.False(t, hasMore) assert.False(t, hasMore)
@@ -179,14 +179,14 @@ M 100644 :1 b.txt
`))).RunStdString(t.Context()) `))).RunStdString(t.Context())
require.NoError(t, runErr) require.NoError(t, runErr)
repoFollowRename, err := OpenRepository(t.Context(), repoFollowRenameDir) repoFollowRename, err := OpenRepository(repoFollowRenameDir)
require.NoError(t, err) require.NoError(t, err)
defer repoFollowRename.Close() defer repoFollowRename.Close()
commits, _, err = repoFollowRename.CommitsByFileAndRange(CommitsByFileAndRangeOptions{Revision: "master", File: "b.txt", Page: 1}) commits, _, err = repoFollowRename.CommitsByFileAndRange(t.Context(), CommitsByFileAndRangeOptions{Revision: "master", File: "b.txt", Page: 1})
require.NoError(t, err) require.NoError(t, err)
assert.Len(t, commits, 1) assert.Len(t, commits, 1)
commits, _, err = repoFollowRename.CommitsByFileAndRange(CommitsByFileAndRangeOptions{Revision: "master", File: "b.txt", Page: 1, FollowRename: true}) commits, _, err = repoFollowRename.CommitsByFileAndRange(t.Context(), CommitsByFileAndRangeOptions{Revision: "master", File: "b.txt", Page: 1, FollowRename: true})
require.NoError(t, err) require.NoError(t, err)
assert.Len(t, commits, 2) assert.Len(t, commits, 2)
} }
+12 -11
View File
@@ -7,6 +7,7 @@ package git
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@@ -31,7 +32,7 @@ func (l *lineCountWriter) Write(p []byte) (n int, err error) {
// GetDiffNumChangedFiles counts the number of changed files // GetDiffNumChangedFiles counts the number of changed files
// This is substantially quicker than shortstat but... // This is substantially quicker than shortstat but...
func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparison bool) (int, error) { func (repo *Repository) GetDiffNumChangedFiles(ctx context.Context, base, head string, directComparison bool) (int, error) {
// Now there is git diff --shortstat but this appears to be slower than simply iterating with --nameonly // Now there is git diff --shortstat but this appears to be slower than simply iterating with --nameonly
w := &lineCountWriter{} w := &lineCountWriter{}
@@ -45,7 +46,7 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
AddArguments("--"). AddArguments("--").
WithDir(repo.Path). WithDir(repo.Path).
WithStdoutCopy(w). WithStdoutCopy(w).
RunWithStderr(repo.Ctx); err != nil { RunWithStderr(ctx); err != nil {
if gitcmd.IsStderr(err, gitcmd.StderrNoMergeBase) { if gitcmd.IsStderr(err, gitcmd.StderrNoMergeBase) {
// git >= 2.28 now returns an error if base and head have become unrelated. // git >= 2.28 now returns an error if base and head have become unrelated.
// it doesn't make sense to count the changed files in this case because UI won't display such diff // it doesn't make sense to count the changed files in this case because UI won't display such diff
@@ -59,35 +60,35 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
var patchCommits = regexp.MustCompile(`^From\s(\w+)\s`) var patchCommits = regexp.MustCompile(`^From\s(\w+)\s`)
// GetDiff generates and returns patch data between given revisions, optimized for human readability // GetDiff generates and returns patch data between given revisions, optimized for human readability
func (repo *Repository) GetDiff(compareArg string, w io.Writer) error { func (repo *Repository) GetDiff(ctx context.Context, compareArg string, w io.Writer) error {
return gitcmd.NewCommand("diff", "-p").AddDynamicArguments(compareArg). return gitcmd.NewCommand("diff", "-p").AddDynamicArguments(compareArg).
WithDir(repo.Path). WithDir(repo.Path).
WithStdoutCopy(w). WithStdoutCopy(w).
Run(repo.Ctx) Run(ctx)
} }
// GetDiffBinary generates and returns patch data between given revisions, including binary diffs. // GetDiffBinary generates and returns patch data between given revisions, including binary diffs.
func (repo *Repository) GetDiffBinary(compareArg string, w io.Writer) error { func (repo *Repository) GetDiffBinary(ctx context.Context, compareArg string, w io.Writer) error {
return gitcmd.NewCommand("diff", "-p", "--binary", "--histogram"). return gitcmd.NewCommand("diff", "-p", "--binary", "--histogram").
AddDynamicArguments(compareArg). AddDynamicArguments(compareArg).
WithDir(repo.Path). WithDir(repo.Path).
WithStdoutCopy(w). WithStdoutCopy(w).
Run(repo.Ctx) Run(ctx)
} }
// GetPatch generates and returns format-patch data between given revisions, able to be used with `git apply` // GetPatch generates and returns format-patch data between given revisions, able to be used with `git apply`
func (repo *Repository) GetPatch(compareArg string, w io.Writer) error { func (repo *Repository) GetPatch(ctx context.Context, compareArg string, w io.Writer) error {
return gitcmd.NewCommand("format-patch", "--binary", "--stdout").AddDynamicArguments(compareArg). return gitcmd.NewCommand("format-patch", "--binary", "--stdout").AddDynamicArguments(compareArg).
WithDir(repo.Path). WithDir(repo.Path).
WithStdoutCopy(w). WithStdoutCopy(w).
Run(repo.Ctx) Run(ctx)
} }
// GetFilesChangedBetween returns a list of all files that have been changed between the given commits // GetFilesChangedBetween returns a list of all files that have been changed between the given commits
// If base is undefined empty SHA (zeros), it only returns the files changed in the head commit // If base is undefined empty SHA (zeros), it only returns the files changed in the head commit
// If base is the SHA of an empty tree (EmptyTreeSHA), it returns the files changes from the initial commit to the head commit // If base is the SHA of an empty tree (EmptyTreeSHA), it returns the files changes from the initial commit to the head commit
func (repo *Repository) GetFilesChangedBetween(base, head string) ([]string, error) { func (repo *Repository) GetFilesChangedBetween(ctx context.Context, base, head string) ([]string, error) {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -97,7 +98,7 @@ func (repo *Repository) GetFilesChangedBetween(base, head string) ([]string, err
} else { } else {
cmd.AddDynamicArguments(base, head) cmd.AddDynamicArguments(base, head)
} }
stdout, _, err := cmd.WithDir(repo.Path).RunStdString(repo.Ctx) stdout, _, err := cmd.WithDir(repo.Path).RunStdString(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+9 -9
View File
@@ -22,7 +22,7 @@ func TestGetFormatPatch(t *testing.T) {
return return
} }
repo, err := OpenRepository(t.Context(), clonedPath) repo, err := OpenRepository(clonedPath)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -30,7 +30,7 @@ func TestGetFormatPatch(t *testing.T) {
defer repo.Close() defer repo.Close()
rd := &bytes.Buffer{} rd := &bytes.Buffer{}
err = repo.GetPatch("8d92fc95^...8d92fc95", rd) err = repo.GetPatch(t.Context(), "8d92fc95^...8d92fc95", rd)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -50,7 +50,7 @@ func TestGetFormatPatch(t *testing.T) {
func TestReadPatch(t *testing.T) { func TestReadPatch(t *testing.T) {
// Ensure we can read the patch files // Ensure we can read the patch files
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(t.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -88,7 +88,7 @@ func TestReadWritePullHead(t *testing.T) {
return return
} }
repo, err := OpenRepository(t.Context(), clonedPath) repo, err := OpenRepository(clonedPath)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -96,7 +96,7 @@ func TestReadWritePullHead(t *testing.T) {
defer repo.Close() defer repo.Close()
// Try to open non-existing Pull // Try to open non-existing Pull
_, err = repo.GetRefCommitID(PullPrefix + "0/head") _, err = repo.GetRefCommitID(t.Context(), PullPrefix+"0/head")
assert.Error(t, err) assert.Error(t, err)
// Write a fake sha1 with only 40 zeros // Write a fake sha1 with only 40 zeros
@@ -111,7 +111,7 @@ func TestReadWritePullHead(t *testing.T) {
} }
// Read the file created // Read the file created
headContents, err := repo.GetRefCommitID(PullPrefix + "1/head") headContents, err := repo.GetRefCommitID(t.Context(), PullPrefix+"1/head")
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -130,11 +130,11 @@ func TestReadWritePullHead(t *testing.T) {
func TestGetCommitFilesChanged(t *testing.T) { func TestGetCommitFilesChanged(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(t.Context(), bareRepo1Path) repo, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
testCases := []struct { testCases := []struct {
@@ -164,7 +164,7 @@ func TestGetCommitFilesChanged(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
changedFiles, err := repo.GetFilesChangedBetween(tc.base, tc.head) changedFiles, err := repo.GetFilesChangedBetween(t.Context(), tc.base, tc.head)
assert.NoError(t, err) assert.NoError(t, err)
assert.ElementsMatch(t, tc.files, changedFiles) assert.ElementsMatch(t, tc.files, changedFiles)
} }
+21 -21
View File
@@ -15,14 +15,14 @@ import (
) )
// ReadTreeToIndex reads a treeish to the index // ReadTreeToIndex reads a treeish to the index
func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error { func (repo *Repository) ReadTreeToIndex(ctx context.Context, treeish string, indexFilename ...string) error {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return err return err
} }
if len(treeish) != objectFormat.FullLength() { if len(treeish) != objectFormat.FullLength() {
res, _, err := gitcmd.NewCommand("rev-parse", "--verify").AddDynamicArguments(treeish).WithDir(repo.Path).RunStdString(repo.Ctx) res, _, err := gitcmd.NewCommand("rev-parse", "--verify").AddDynamicArguments(treeish).WithDir(repo.Path).RunStdString(ctx)
if err != nil { if err != nil {
return err return err
} }
@@ -34,15 +34,15 @@ func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string)
if err != nil { if err != nil {
return err return err
} }
return repo.readTreeToIndex(id, indexFilename...) return repo.readTreeToIndex(ctx, id, indexFilename...)
} }
func (repo *Repository) readTreeToIndex(id ObjectID, indexFilename ...string) error { func (repo *Repository) readTreeToIndex(ctx context.Context, id ObjectID, indexFilename ...string) error {
var env []string var env []string
if len(indexFilename) > 0 { if len(indexFilename) > 0 {
env = append(os.Environ(), "GIT_INDEX_FILE="+indexFilename[0]) env = append(os.Environ(), "GIT_INDEX_FILE="+indexFilename[0])
} }
_, _, err := gitcmd.NewCommand("read-tree").AddDynamicArguments(id.String()).WithDir(repo.Path).WithEnv(env).RunStdString(repo.Ctx) _, _, err := gitcmd.NewCommand("read-tree").AddDynamicArguments(id.String()).WithDir(repo.Path).WithEnv(env).RunStdString(ctx)
if err != nil { if err != nil {
return err return err
} }
@@ -50,7 +50,7 @@ func (repo *Repository) readTreeToIndex(id ObjectID, indexFilename ...string) er
} }
// ReadTreeToTemporaryIndex reads a treeish to a temporary index file // ReadTreeToTemporaryIndex reads a treeish to a temporary index file
func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilename, tmpDir string, cancel context.CancelFunc, err error) { func (repo *Repository) ReadTreeToTemporaryIndex(ctx context.Context, treeish string) (tmpIndexFilename, tmpDir string, cancel context.CancelFunc, err error) {
defer func() { defer func() {
// if error happens and there is a cancel function, do clean up // if error happens and there is a cancel function, do clean up
if err != nil && cancel != nil { if err != nil && cancel != nil {
@@ -66,7 +66,7 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilena
tmpIndexFilename = filepath.Join(tmpDir, ".tmp-index") tmpIndexFilename = filepath.Join(tmpDir, ".tmp-index")
err = repo.ReadTreeToIndex(treeish, tmpIndexFilename) err = repo.ReadTreeToIndex(ctx, treeish, tmpIndexFilename)
if err != nil { if err != nil {
return "", "", cancel, err return "", "", cancel, err
} }
@@ -74,15 +74,15 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilena
} }
// EmptyIndex empties the index // EmptyIndex empties the index
func (repo *Repository) EmptyIndex() error { func (repo *Repository) EmptyIndex(ctx context.Context) error {
_, _, err := gitcmd.NewCommand("read-tree", "--empty").WithDir(repo.Path).RunStdString(repo.Ctx) _, _, err := gitcmd.NewCommand("read-tree", "--empty").WithDir(repo.Path).RunStdString(ctx)
return err return err
} }
// LsFiles checks if the given filenames are in the index // LsFiles checks if the given filenames are in the index
func (repo *Repository) LsFiles(filenames ...string) ([]string, error) { func (repo *Repository) LsFiles(ctx context.Context, filenames ...string) ([]string, error) {
cmd := gitcmd.NewCommand("ls-files", "-z").AddDashesAndList(filenames...) cmd := gitcmd.NewCommand("ls-files", "-z").AddDashesAndList(filenames...)
res, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx) res, _, err := cmd.WithDir(repo.Path).RunStdBytes(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -95,8 +95,8 @@ func (repo *Repository) LsFiles(filenames ...string) ([]string, error) {
} }
// RemoveFilesFromIndex removes given filenames from the index - it does not check whether they are present. // RemoveFilesFromIndex removes given filenames from the index - it does not check whether they are present.
func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error { func (repo *Repository) RemoveFilesFromIndex(ctx context.Context, filenames ...string) error {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return err return err
} }
@@ -111,7 +111,7 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error {
return cmd. return cmd.
WithDir(repo.Path). WithDir(repo.Path).
WithStdinBytes(input.Bytes()). WithStdinBytes(input.Bytes()).
RunWithStderr(repo.Ctx) RunWithStderr(ctx)
} }
type IndexObjectInfo struct { type IndexObjectInfo struct {
@@ -121,7 +121,7 @@ type IndexObjectInfo struct {
} }
// AddObjectsToIndex adds the provided object hashes to the index at the provided filenames // AddObjectsToIndex adds the provided object hashes to the index at the provided filenames
func (repo *Repository) AddObjectsToIndex(objects ...IndexObjectInfo) error { func (repo *Repository) AddObjectsToIndex(ctx context.Context, objects ...IndexObjectInfo) error {
cmd := gitcmd.NewCommand("update-index", "--add", "--replace", "-z", "--index-info") cmd := gitcmd.NewCommand("update-index", "--add", "--replace", "-z", "--index-info")
input := new(bytes.Buffer) input := new(bytes.Buffer)
for _, object := range objects { for _, object := range objects {
@@ -131,17 +131,17 @@ func (repo *Repository) AddObjectsToIndex(objects ...IndexObjectInfo) error {
return cmd. return cmd.
WithDir(repo.Path). WithDir(repo.Path).
WithStdinBytes(input.Bytes()). WithStdinBytes(input.Bytes()).
RunWithStderr(repo.Ctx) RunWithStderr(ctx)
} }
// AddObjectToIndex adds the provided object hash to the index at the provided filename // AddObjectToIndex adds the provided object hash to the index at the provided filename
func (repo *Repository) AddObjectToIndex(mode string, object ObjectID, filename string) error { func (repo *Repository) AddObjectToIndex(ctx context.Context, mode string, object ObjectID, filename string) error {
return repo.AddObjectsToIndex(IndexObjectInfo{Mode: mode, Object: object, Filename: filename}) return repo.AddObjectsToIndex(ctx, IndexObjectInfo{Mode: mode, Object: object, Filename: filename})
} }
// WriteTree writes the current index as a tree to the object db and returns its hash // WriteTree writes the current index as a tree to the object db and returns its hash
func (repo *Repository) WriteTree() (*Tree, error) { func (repo *Repository) WriteTree(ctx context.Context) (*Tree, error) {
stdout, _, runErr := gitcmd.NewCommand("write-tree").WithDir(repo.Path).RunStdString(repo.Ctx) stdout, _, runErr := gitcmd.NewCommand("write-tree").WithDir(repo.Path).RunStdString(ctx)
if runErr != nil { if runErr != nil {
return nil, runErr return nil, runErr
} }
+11 -10
View File
@@ -5,6 +5,7 @@
package git package git
import ( import (
"context"
"strings" "strings"
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/git/gitcmd"
@@ -31,12 +32,12 @@ func (o ObjectType) Bytes() []byte {
return []byte(o) return []byte(o)
} }
func (repo *Repository) GetObjectFormat() (ObjectFormat, error) { func (repo *Repository) GetObjectFormat(ctx context.Context) (ObjectFormat, error) {
if repo != nil && repo.objectFormat != nil { if repo.objectFormatCache != nil {
return repo.objectFormat, nil return repo.objectFormatCache, nil
} }
str, err := repo.hashObjectBytes(nil, false) str, err := repo.hashObjectBytes(ctx, nil, false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -45,21 +46,21 @@ func (repo *Repository) GetObjectFormat() (ObjectFormat, error) {
return nil, err return nil, err
} }
repo.objectFormat = hash.Type() repo.objectFormatCache = hash.Type()
return repo.objectFormat, nil return repo.objectFormatCache, nil
} }
// HashObjectBytes returns hash for the content // HashObjectBytes returns hash for the content
func (repo *Repository) HashObjectBytes(buf []byte) (ObjectID, error) { func (repo *Repository) HashObjectBytes(ctx context.Context, buf []byte) (ObjectID, error) {
idStr, err := repo.hashObjectBytes(buf, true) idStr, err := repo.hashObjectBytes(ctx, buf, true)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return NewIDFromString(idStr) return NewIDFromString(idStr)
} }
func (repo *Repository) hashObjectBytes(buf []byte, save bool) (string, error) { func (repo *Repository) hashObjectBytes(ctx context.Context, buf []byte, save bool) (string, error) {
var cmd *gitcmd.Command var cmd *gitcmd.Command
if save { if save {
cmd = gitcmd.NewCommand("hash-object", "-w", "--stdin") cmd = gitcmd.NewCommand("hash-object", "-w", "--stdin")
@@ -69,7 +70,7 @@ func (repo *Repository) hashObjectBytes(buf []byte, save bool) (string, error) {
stdout, _, err := cmd. stdout, _, err := cmd.
WithDir(repo.Path). WithDir(repo.Path).
WithStdinBytes(buf). WithStdinBytes(buf).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
+7 -7
View File
@@ -13,8 +13,8 @@ import (
) )
// GetRefs returns all references of the repository. // GetRefs returns all references of the repository.
func (repo *Repository) GetRefs() ([]*Reference, error) { func (repo *Repository) GetRefs(ctx context.Context) ([]*Reference, error) {
return repo.GetRefsFiltered("") return repo.GetRefsFiltered(ctx, "")
} }
// ListOccurrences lists all refs of the given refType the given commit appears in sorted by creation date DESC // ListOccurrences lists all refs of the given refType the given commit appears in sorted by creation date DESC
@@ -72,19 +72,19 @@ func parseTags(refs []string) []string {
// * "refs/tags/1234567890" vs commit "1234567890" // * "refs/tags/1234567890" vs commit "1234567890"
// In most cases, it SHOULD AVOID using this function, unless there is an irresistible reason (eg: make API friendly to end users) // In most cases, it SHOULD AVOID using this function, unless there is an irresistible reason (eg: make API friendly to end users)
// If the function is used, the caller SHOULD CHECK the ref type carefully. // If the function is used, the caller SHOULD CHECK the ref type carefully.
func (repo *Repository) UnstableGuessRefByShortName(shortName string) RefName { func (repo *Repository) UnstableGuessRefByShortName(ctx context.Context, shortName string) RefName {
if repo.IsBranchExist(shortName) { if repo.IsBranchExist(ctx, shortName) {
return RefNameFromBranch(shortName) return RefNameFromBranch(shortName)
} }
if repo.IsTagExist(shortName) { if repo.IsTagExist(ctx, shortName) {
return RefNameFromTag(shortName) return RefNameFromTag(shortName)
} }
if strings.HasPrefix(shortName, "refs/") { if strings.HasPrefix(shortName, "refs/") {
if repo.IsReferenceExist(shortName) { if repo.IsReferenceExist(ctx, shortName) {
return RefName(shortName) return RefName(shortName)
} }
} }
commit, err := repo.GetCommit(shortName) commit, err := repo.GetCommit(ctx, shortName)
if err == nil { if err == nil {
commitIDString := commit.ID.String() commitIDString := commit.ID.String()
// make sure the "shortName" is either partial commit ID, or it is HEAD // make sure the "shortName" is either partial commit ID, or it is HEAD
+3 -2
View File
@@ -6,6 +6,7 @@
package git package git
import ( import (
"context"
"strings" "strings"
"github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5"
@@ -13,7 +14,7 @@ import (
) )
// GetRefsFiltered returns all references of the repository that matches patterm exactly or starting with. // GetRefsFiltered returns all references of the repository that matches patterm exactly or starting with.
func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) { func (repo *Repository) GetRefsFiltered(ctx context.Context, pattern string) ([]*Reference, error) {
r, err := git.PlainOpen(repo.Path) r, err := git.PlainOpen(repo.Path)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -30,7 +31,7 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
refType := string(ObjectCommit) refType := string(ObjectCommit)
if ref.Name().IsTag() { if ref.Name().IsTag() {
// tags can be of type `commit` (lightweight) or `tag` (annotated) // tags can be of type `commit` (lightweight) or `tag` (annotated)
if tagType, _ := repo.GetTagType(ParseGogitHash(ref.Hash())); err == nil { if tagType, _ := repo.GetTagType(ctx, ParseGogitHash(ref.Hash())); err == nil {
refType = tagType refType = tagType
} }
} }
+3 -2
View File
@@ -7,6 +7,7 @@ package git
import ( import (
"bufio" "bufio"
"context"
"io" "io"
"strings" "strings"
@@ -14,7 +15,7 @@ import (
) )
// GetRefsFiltered returns all references of the repository that matches patterm exactly or starting with. // GetRefsFiltered returns all references of the repository that matches patterm exactly or starting with.
func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) { func (repo *Repository) GetRefsFiltered(ctx context.Context, pattern string) ([]*Reference, error) {
refs := make([]*Reference, 0) refs := make([]*Reference, 0)
cmd := gitcmd.NewCommand("for-each-ref") cmd := gitcmd.NewCommand("for-each-ref")
stdoutReader, stdoutReaderClose := cmd.MakeStdoutPipe() stdoutReader, stdoutReaderClose := cmd.MakeStdoutPipe()
@@ -70,6 +71,6 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
} }
} }
return nil return nil
}).RunWithStderr(repo.Ctx) }).RunWithStderr(ctx)
return refs, err return refs, err
} }
+4 -4
View File
@@ -12,11 +12,11 @@ import (
func TestRepository_GetRefs(t *testing.T) { func TestRepository_GetRefs(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
refs, err := bareRepo1.GetRefs() refs, err := bareRepo1.GetRefs(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, refs, 6) assert.Len(t, refs, 6)
@@ -37,11 +37,11 @@ func TestRepository_GetRefs(t *testing.T) {
func TestRepository_GetRefsFiltered(t *testing.T) { func TestRepository_GetRefsFiltered(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
refs, err := bareRepo1.GetRefsFiltered(TagPrefix) refs, err := bareRepo1.GetRefsFiltered(t.Context(), TagPrefix)
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, refs, 2) { if assert.Len(t, refs, 2) {
+4 -3
View File
@@ -5,6 +5,7 @@ package git
import ( import (
"bufio" "bufio"
"context"
"fmt" "fmt"
"sort" "sort"
"strconv" "strconv"
@@ -34,7 +35,7 @@ type CodeActivityAuthor struct {
} }
// GetCodeActivityStats returns code statistics for activity page // GetCodeActivityStats returns code statistics for activity page
func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string) (*CodeActivityStats, error) { func (repo *Repository) GetCodeActivityStats(ctx context.Context, fromTime time.Time, branch string) (*CodeActivityStats, error) {
stats := &CodeActivityStats{} stats := &CodeActivityStats{}
since := fromTime.Format(time.RFC3339) since := fromTime.Format(time.RFC3339)
@@ -42,7 +43,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
stdout, _, runErr := gitcmd.NewCommand("rev-list", "--count", "--no-merges", "--branches=*", "--date=iso"). stdout, _, runErr := gitcmd.NewCommand("rev-list", "--count", "--no-merges", "--branches=*", "--date=iso").
AddOptionFormat("--since=%s", since). AddOptionFormat("--since=%s", since).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if runErr != nil { if runErr != nil {
return nil, runErr return nil, runErr
} }
@@ -131,7 +132,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
stats.Authors = a stats.Authors = a
return nil return nil
}). }).
RunWithStderr(repo.Ctx) RunWithStderr(ctx)
if err != nil { if err != nil {
return nil, fmt.Errorf("GetCodeActivityStats: %w", err) return nil, fmt.Errorf("GetCodeActivityStats: %w", err)
} }
+2 -2
View File
@@ -13,14 +13,14 @@ import (
func TestRepository_GetCodeActivityStats(t *testing.T) { func TestRepository_GetCodeActivityStats(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
assert.NoError(t, err) assert.NoError(t, err)
defer bareRepo1.Close() defer bareRepo1.Close()
timeFrom, err := time.Parse(time.RFC3339, "2016-01-01T00:00:00+00:00") timeFrom, err := time.Parse(time.RFC3339, "2016-01-01T00:00:00+00:00")
assert.NoError(t, err) assert.NoError(t, err)
code, err := bareRepo1.GetCodeActivityStats(timeFrom, "") code, err := bareRepo1.GetCodeActivityStats(t.Context(), timeFrom, "")
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, code) assert.NotNil(t, code)
+20 -19
View File
@@ -5,6 +5,7 @@
package git package git
import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
@@ -17,28 +18,28 @@ import (
const TagPrefix = "refs/tags/" const TagPrefix = "refs/tags/"
// CreateTag create one tag in the repository // CreateTag create one tag in the repository
func (repo *Repository) CreateTag(name, revision string) error { func (repo *Repository) CreateTag(ctx context.Context, name, revision string) error {
_, _, err := gitcmd.NewCommand("tag").AddDashesAndList(name, revision).WithDir(repo.Path).RunStdString(repo.Ctx) _, _, err := gitcmd.NewCommand("tag").AddDashesAndList(name, revision).WithDir(repo.Path).RunStdString(ctx)
return err return err
} }
// CreateAnnotatedTag create one annotated tag in the repository // CreateAnnotatedTag create one annotated tag in the repository
func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error { func (repo *Repository) CreateAnnotatedTag(ctx context.Context, name, message, revision string) error {
_, _, err := gitcmd.NewCommand("tag", "-a", "-m"). _, _, err := gitcmd.NewCommand("tag", "-a", "-m").
AddDynamicArguments(message). AddDynamicArguments(message).
AddDashesAndList(name, revision). AddDashesAndList(name, revision).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
return err return err
} }
// GetTagNameBySHA returns the name of a tag from its tag object SHA or commit SHA // GetTagNameBySHA returns the name of a tag from its tag object SHA or commit SHA
func (repo *Repository) GetTagNameBySHA(sha string) (string, error) { func (repo *Repository) GetTagNameBySHA(ctx context.Context, sha string) (string, error) {
if len(sha) < 5 { if len(sha) < 5 {
return "", fmt.Errorf("SHA is too short: %s", sha) return "", fmt.Errorf("SHA is too short: %s", sha)
} }
stdout, _, err := gitcmd.NewCommand("show-ref", "--tags", "-d").WithDir(repo.Path).RunStdString(repo.Ctx) stdout, _, err := gitcmd.NewCommand("show-ref", "--tags", "-d").WithDir(repo.Path).RunStdString(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -60,8 +61,8 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) {
} }
// GetTagID returns the object ID for a tag (annotated tags have both an object SHA AND a commit SHA) // GetTagID returns the object ID for a tag (annotated tags have both an object SHA AND a commit SHA)
func (repo *Repository) GetTagID(name string) (string, error) { func (repo *Repository) GetTagID(ctx context.Context, name string) (string, error) {
stdout, _, err := gitcmd.NewCommand("show-ref", "--tags").AddDashesAndList(name).WithDir(repo.Path).RunStdString(repo.Ctx) stdout, _, err := gitcmd.NewCommand("show-ref", "--tags").AddDashesAndList(name).WithDir(repo.Path).RunStdString(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -76,8 +77,8 @@ func (repo *Repository) GetTagID(name string) (string, error) {
} }
// GetTag returns a Git tag by given name. // GetTag returns a Git tag by given name.
func (repo *Repository) GetTag(name string) (*Tag, error) { func (repo *Repository) GetTag(ctx context.Context, name string) (*Tag, error) {
idStr, err := repo.GetTagID(name) idStr, err := repo.GetTagID(ctx, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -87,7 +88,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) {
return nil, err return nil, err
} }
tag, err := repo.getTag(id, name) tag, err := repo.getTag(ctx, id, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -95,13 +96,13 @@ 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(ctx context.Context, idStr, name string) (*Tag, error) {
id, err := NewIDFromString(idStr) id, err := NewIDFromString(idStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
tag, err := repo.getTag(id, name) tag, err := repo.getTag(ctx, id, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -109,7 +110,7 @@ func (repo *Repository) GetTagWithID(idStr, name string) (*Tag, error) {
} }
// GetTagInfos returns all tag infos of the repository. // GetTagInfos returns all tag infos of the repository.
func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { func (repo *Repository) GetTagInfos(ctx context.Context, page, pageSize int) ([]*Tag, int, error) {
// Generally, refname:short should be equal to refname:lstrip=2 except core.warnAmbiguousRefs is used to select the strict abbreviation mode. // Generally, refname:short should be equal to refname:lstrip=2 except core.warnAmbiguousRefs is used to select the strict abbreviation mode.
// https://git-scm.com/docs/git-for-each-ref#Documentation/git-for-each-ref.txt-refname // https://git-scm.com/docs/git-for-each-ref#Documentation/git-for-each-ref.txt-refname
forEachRefFmt := foreachref.NewFormat("objecttype", "refname:lstrip=2", "object", "objectname", "creator", "contents", "contents:signature") forEachRefFmt := foreachref.NewFormat("objecttype", "refname:lstrip=2", "object", "objectname", "creator", "contents", "contents:signature")
@@ -147,7 +148,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) {
} }
return nil return nil
}). }).
RunWithStderr(repo.Ctx) RunWithStderr(ctx)
return tags, tagsTotal, err return tags, tagsTotal, err
} }
@@ -194,14 +195,14 @@ func parseTagRef(ref map[string]string) (tag *Tag, err error) {
} }
// 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(ctx context.Context, sha string) (*Tag, error) {
id, err := NewIDFromString(sha) id, err := NewIDFromString(sha)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Tag type must be "tag" (annotated) and not a "commit" (lightweight) tag // Tag type must be "tag" (annotated) and not a "commit" (lightweight) tag
if tagType, err := repo.GetTagType(id); err != nil { if tagType, err := repo.GetTagType(ctx, id); err != nil {
return nil, err return nil, err
} else if ObjectType(tagType) != ObjectTag { } else if ObjectType(tagType) != ObjectTag {
// not an annotated tag // not an annotated tag
@@ -209,12 +210,12 @@ func (repo *Repository) GetAnnotatedTag(sha string) (*Tag, error) {
} }
// Get tag name // Get tag name
name, err := repo.GetTagNameBySHA(id.String()) name, err := repo.GetTagNameBySHA(ctx, id.String())
if err != nil { if err != nil {
return nil, err return nil, err
} }
tag, err := repo.getTag(id, name) tag, err := repo.getTag(ctx, id, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+8 -6
View File
@@ -7,19 +7,21 @@
package git package git
import ( import (
"context"
"gitea.dev/modules/log" "gitea.dev/modules/log"
"github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing"
) )
// IsTagExist returns true if given tag exists in the repository. // IsTagExist returns true if given tag exists in the repository.
func (repo *Repository) IsTagExist(name string) bool { func (repo *Repository) IsTagExist(_ context.Context, name string) bool {
_, err := repo.gogitRepo.Reference(plumbing.ReferenceName(TagPrefix+name), true) _, err := repo.gogitRepo.Reference(plumbing.ReferenceName(TagPrefix+name), true)
return err == nil return err == nil
} }
// GetTagType gets the type of the tag, either commit (simple) or tag (annotated) // GetTagType gets the type of the tag, either commit (simple) or tag (annotated)
func (repo *Repository) GetTagType(id ObjectID) (string, error) { func (repo *Repository) GetTagType(_ context.Context, id ObjectID) (string, error) {
// Get tag type // Get tag type
obj, err := repo.gogitRepo.Object(plumbing.AnyObject, plumbing.Hash(id.RawValue())) obj, err := repo.gogitRepo.Object(plumbing.AnyObject, plumbing.Hash(id.RawValue()))
if err != nil { if err != nil {
@@ -32,7 +34,7 @@ func (repo *Repository) GetTagType(id ObjectID) (string, error) {
return obj.Type().String(), nil return obj.Type().String(), nil
} }
func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) { func (repo *Repository) getTag(ctx context.Context, tagID ObjectID, name string) (*Tag, error) {
t, ok := repo.tagCache.Get(tagID.String()) t, ok := repo.tagCache.Get(tagID.String())
if ok { if ok {
log.Debug("Hit cache: %s", tagID) log.Debug("Hit cache: %s", tagID)
@@ -41,13 +43,13 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
return &tagClone, nil return &tagClone, nil
} }
tp, err := repo.GetTagType(tagID) tp, err := repo.GetTagType(ctx, tagID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Get the commit ID and tag ID (may be different for annotated tag) for the returned tag object // Get the commit ID and tag ID (may be different for annotated tag) for the returned tag object
commitIDStr, err := repo.GetTagCommitID(name) commitIDStr, err := repo.GetTagCommitID(ctx, name)
if err != nil { if err != nil {
// 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
@@ -59,7 +61,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
// If type is "commit, the tag is a lightweight tag // If type is "commit, the tag is a lightweight tag
if ObjectType(tp) == ObjectCommit { if ObjectType(tp) == ObjectCommit {
commit, err := repo.GetCommit(commitIDStr) commit, err := repo.GetCommit(ctx, commitIDStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+10 -9
View File
@@ -7,6 +7,7 @@
package git package git
import ( import (
"context"
"errors" "errors"
"io" "io"
@@ -14,17 +15,17 @@ import (
) )
// IsTagExist returns true if given tag exists in the repository. // IsTagExist returns true if given tag exists in the repository.
func (repo *Repository) IsTagExist(name string) bool { func (repo *Repository) IsTagExist(ctx context.Context, name string) bool {
if repo == nil || name == "" { if repo == nil || name == "" {
return false return false
} }
return repo.IsReferenceExist(TagPrefix + name) return repo.IsReferenceExist(ctx, TagPrefix+name)
} }
// GetTagType gets the type of the tag, either commit (simple) or tag (annotated) // GetTagType gets the type of the tag, either commit (simple) or tag (annotated)
func (repo *Repository) GetTagType(id ObjectID) (string, error) { func (repo *Repository) GetTagType(ctx context.Context, id ObjectID) (string, error) {
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -39,7 +40,7 @@ func (repo *Repository) GetTagType(id ObjectID) (string, error) {
return info.Type, nil return info.Type, nil
} }
func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) { func (repo *Repository) getTag(ctx context.Context, tagID ObjectID, name string) (*Tag, error) {
t, ok := repo.tagCache.Get(tagID.String()) t, ok := repo.tagCache.Get(tagID.String())
if ok { if ok {
log.Debug("Hit cache: %s", tagID) log.Debug("Hit cache: %s", tagID)
@@ -48,13 +49,13 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
return &tagClone, nil return &tagClone, nil
} }
tp, err := repo.GetTagType(tagID) tp, err := repo.GetTagType(ctx, tagID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Get the commit ID and tag ID (may be different for annotated tag) for the returned tag object // Get the commit ID and tag ID (may be different for annotated tag) for the returned tag object
commitIDStr, err := repo.GetTagCommitID(name) commitIDStr, err := repo.GetTagCommitID(ctx, name)
if err != nil { if err != nil {
// 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
@@ -66,7 +67,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
// If type is "commit, the tag is a lightweight tag // If type is "commit, the tag is a lightweight tag
if ObjectType(tp) == ObjectCommit { if ObjectType(tp) == ObjectCommit {
commit, err := repo.GetCommit(commitIDStr) commit, err := repo.GetCommit(ctx, commitIDStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -84,7 +85,7 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
} }
// The tag is an annotated tag with a message. // The tag is an annotated tag with a message.
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+19 -19
View File
@@ -13,14 +13,14 @@ import (
func TestRepository_GetTagInfos(t *testing.T) { func TestRepository_GetTagInfos(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path) bareRepo1, err := OpenRepository(bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
defer bareRepo1.Close() defer bareRepo1.Close()
tags, total, err := bareRepo1.GetTagInfos(0, 0) tags, total, err := bareRepo1.GetTagInfos(t.Context(), 0, 0)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -44,7 +44,7 @@ func TestRepository_GetTag(t *testing.T) {
return return
} }
bareRepo1, err := OpenRepository(t.Context(), clonedPath) bareRepo1, err := OpenRepository(clonedPath)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -56,14 +56,14 @@ func TestRepository_GetTag(t *testing.T) {
lTagName := "lightweightTag" lTagName := "lightweightTag"
// Create the lightweight tag // Create the lightweight tag
err = bareRepo1.CreateTag(lTagName, lTagCommitID) err = bareRepo1.CreateTag(t.Context(), lTagName, lTagCommitID)
if err != nil { if err != nil {
assert.NoError(t, err, "Unable to create the lightweight tag: %s for ID: %s. Error: %v", lTagName, lTagCommitID, err) assert.NoError(t, err, "Unable to create the lightweight tag: %s for ID: %s. Error: %v", lTagName, lTagCommitID, err)
return return
} }
// and try to get the Tag for lightweight tag // and try to get the Tag for lightweight tag
lTag, err := bareRepo1.GetTag(lTagName) lTag, err := bareRepo1.GetTag(t.Context(), lTagName)
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, lTag, "nil lTag: %s", lTagName) require.NotNil(t, lTag, "nil lTag: %s", lTagName)
@@ -78,20 +78,20 @@ func TestRepository_GetTag(t *testing.T) {
aTagMessage := "my annotated message \n - test two line" aTagMessage := "my annotated message \n - test two line"
// Create the annotated tag // Create the annotated tag
err = bareRepo1.CreateAnnotatedTag(aTagName, aTagMessage, aTagCommitID) err = bareRepo1.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, aTagCommitID)
if err != nil { if err != nil {
assert.NoError(t, err, "Unable to create the annotated tag: %s for ID: %s. Error: %v", aTagName, aTagCommitID, err) assert.NoError(t, err, "Unable to create the annotated tag: %s for ID: %s. Error: %v", aTagName, aTagCommitID, err)
return return
} }
// Now try to get the tag for the annotated Tag // Now try to get the tag for the annotated Tag
aTagID, err := bareRepo1.GetTagID(aTagName) aTagID, err := bareRepo1.GetTagID(t.Context(), aTagName)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
aTag, err := bareRepo1.GetTag(aTagName) aTag, err := bareRepo1.GetTag(t.Context(), aTagName)
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, aTag, "nil aTag: %s", aTagName) require.NotNil(t, aTag, "nil aTag: %s", aTagName)
@@ -106,20 +106,20 @@ func TestRepository_GetTag(t *testing.T) {
rTagCommitID := "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0" rTagCommitID := "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"
rTagName := "release/" + lTagName rTagName := "release/" + lTagName
err = bareRepo1.CreateTag(rTagName, rTagCommitID) err = bareRepo1.CreateTag(t.Context(), rTagName, rTagCommitID)
if err != nil { if err != nil {
assert.NoError(t, err, "Unable to create the tag: %s for ID: %s. Error: %v", rTagName, rTagCommitID, err) assert.NoError(t, err, "Unable to create the tag: %s for ID: %s. Error: %v", rTagName, rTagCommitID, err)
return return
} }
rTagID, err := bareRepo1.GetTagID(rTagName) rTagID, err := bareRepo1.GetTagID(t.Context(), rTagName)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
assert.Equal(t, rTagCommitID, rTagID) assert.Equal(t, rTagCommitID, rTagID)
oTagID, err := bareRepo1.GetTagID(lTagName) oTagID, err := bareRepo1.GetTagID(t.Context(), lTagName)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -136,7 +136,7 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
return return
} }
bareRepo1, err := OpenRepository(t.Context(), clonedPath) bareRepo1, err := OpenRepository(clonedPath)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -145,16 +145,16 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
lTagCommitID := "6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1" lTagCommitID := "6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1"
lTagName := "lightweightTag" lTagName := "lightweightTag"
bareRepo1.CreateTag(lTagName, lTagCommitID) bareRepo1.CreateTag(t.Context(), lTagName, lTagCommitID)
aTagCommitID := "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0" aTagCommitID := "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"
aTagName := "annotatedTag" aTagName := "annotatedTag"
aTagMessage := "my annotated message" aTagMessage := "my annotated message"
bareRepo1.CreateAnnotatedTag(aTagName, aTagMessage, aTagCommitID) bareRepo1.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, aTagCommitID)
aTagID, _ := bareRepo1.GetTagID(aTagName) aTagID, _ := bareRepo1.GetTagID(t.Context(), aTagName)
// Try an annotated tag // Try an annotated tag
tag, err := bareRepo1.GetAnnotatedTag(aTagID) tag, err := bareRepo1.GetAnnotatedTag(t.Context(), aTagID)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
@@ -165,18 +165,18 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
assert.Equal(t, "tag", tag.Type) assert.Equal(t, "tag", tag.Type)
// Annotated tag's Commit ID should fail // Annotated tag's Commit ID should fail
tag2, err := bareRepo1.GetAnnotatedTag(aTagCommitID) tag2, err := bareRepo1.GetAnnotatedTag(t.Context(), aTagCommitID)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrNotExist(err)) assert.True(t, IsErrNotExist(err))
assert.Nil(t, tag2) assert.Nil(t, tag2)
// Annotated tag's name should fail // Annotated tag's name should fail
tag3, err := bareRepo1.GetAnnotatedTag(aTagName) tag3, err := bareRepo1.GetAnnotatedTag(t.Context(), aTagName)
assert.Errorf(t, err, "Length must be 40: %d", len(aTagName)) assert.Errorf(t, err, "Length must be 40: %d", len(aTagName))
assert.Nil(t, tag3) assert.Nil(t, tag3)
// Lightweight Tag should fail // Lightweight Tag should fail
tag4, err := bareRepo1.GetAnnotatedTag(lTagCommitID) tag4, err := bareRepo1.GetAnnotatedTag(t.Context(), lTagCommitID)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, IsErrNotExist(err)) assert.True(t, IsErrNotExist(err))
assert.Nil(t, tag4) assert.Nil(t, tag4)
+2 -2
View File
@@ -15,10 +15,10 @@ import (
func TestRepoIsEmpty(t *testing.T) { func TestRepoIsEmpty(t *testing.T) {
emptyRepo2Path := filepath.Join(testReposDir, "repo2_empty") emptyRepo2Path := filepath.Join(testReposDir, "repo2_empty")
repo, err := OpenRepository(t.Context(), emptyRepo2Path) repo, err := OpenRepository(emptyRepo2Path)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
isEmpty, err := repo.IsEmpty() isEmpty, err := repo.IsEmpty(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, isEmpty) assert.True(t, isEmpty)
} }
+3 -2
View File
@@ -6,6 +6,7 @@ package git
import ( import (
"bytes" "bytes"
"context"
"os" "os"
"strings" "strings"
"time" "time"
@@ -23,7 +24,7 @@ type CommitTreeOpts struct {
} }
// CommitTree creates a commit from a given tree id for the user with provided message // CommitTree creates a commit from a given tree id for the user with provided message
func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opts CommitTreeOpts) (ObjectID, error) { func (repo *Repository) CommitTree(ctx context.Context, author, committer *Signature, tree *Tree, opts CommitTreeOpts) (ObjectID, error) {
commitTimeStr := time.Now().Format(time.RFC3339) commitTimeStr := time.Now().Format(time.RFC3339)
// Because this may call hooks we should pass in the environment // Because this may call hooks we should pass in the environment
@@ -61,7 +62,7 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt
stdout, _, err := cmd.WithEnv(env). stdout, _, err := cmd.WithEnv(env).
WithDir(repo.Path). WithDir(repo.Path).
WithStdinBytes(messageBytes.Bytes()). WithStdinBytes(messageBytes.Bytes()).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+6 -5
View File
@@ -7,6 +7,7 @@
package git package git
import ( import (
"context"
"errors" "errors"
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/git/gitcmd"
@@ -14,7 +15,7 @@ import (
"github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing"
) )
func (repo *Repository) getTree(id ObjectID) (*Tree, error) { func (repo *Repository) getTree(_ context.Context, id ObjectID) (*Tree, error) {
gogitTree, err := repo.gogitRepo.TreeObject(plumbing.Hash(id.RawValue())) gogitTree, err := repo.gogitRepo.TreeObject(plumbing.Hash(id.RawValue()))
if err != nil { if err != nil {
if errors.Is(err, plumbing.ErrObjectNotFound) { if errors.Is(err, plumbing.ErrObjectNotFound) {
@@ -31,8 +32,8 @@ func (repo *Repository) getTree(id ObjectID) (*Tree, error) {
} }
// GetTree find the tree object in the repository. // GetTree find the tree object in the repository.
func (repo *Repository) GetTree(idStr string) (*Tree, error) { func (repo *Repository) GetTree(ctx context.Context, idStr string) (*Tree, error) {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -41,7 +42,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
res, _, err := gitcmd.NewCommand("rev-parse", "--verify"). res, _, err := gitcmd.NewCommand("rev-parse", "--verify").
AddDynamicArguments(idStr). AddDynamicArguments(idStr).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -57,7 +58,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
if err == nil { if err == nil {
id = ParseGogitHash(commitObject.TreeHash) id = ParseGogitHash(commitObject.TreeHash)
} }
treeObject, err := repo.getTree(id) treeObject, err := repo.getTree(ctx, id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+8 -7
View File
@@ -6,11 +6,12 @@
package git package git
import ( import (
"context"
"io" "io"
) )
func (repo *Repository) getTree(id ObjectID) (*Tree, error) { func (repo *Repository) getTree(ctx context.Context, id ObjectID) (*Tree, error) {
batch, cancel, err := repo.CatFileBatch(repo.Ctx) batch, cancel, err := repo.CatFileBatch(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -50,7 +51,7 @@ func (repo *Repository) getTree(id ObjectID) (*Tree, error) {
return tree, nil return tree, nil
case "tree": case "tree":
tree := newTree(id) tree := newTree(id)
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -71,13 +72,13 @@ func (repo *Repository) getTree(id ObjectID) (*Tree, error) {
} }
// GetTree find the tree object in the repository. // GetTree find the tree object in the repository.
func (repo *Repository) GetTree(idStr string) (*Tree, error) { func (repo *Repository) GetTree(ctx context.Context, idStr string) (*Tree, error) {
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if len(idStr) != objectFormat.FullLength() { if len(idStr) != objectFormat.FullLength() {
res, err := repo.GetRefCommitID(idStr) res, err := repo.GetRefCommitID(ctx, idStr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -90,5 +91,5 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
return nil, err return nil, err
} }
return repo.getTree(id) return repo.getTree(ctx, id)
} }
+6 -6
View File
@@ -39,7 +39,7 @@ func (t *Tree) SubTree(ctx context.Context, gitRepo *Repository, rpath string) (
return nil, err return nil, err
} }
g, err = gitRepo.getTree(te.ID) g, err = gitRepo.getTree(ctx, te.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -49,11 +49,11 @@ func (t *Tree) SubTree(ctx context.Context, gitRepo *Repository, rpath string) (
} }
// LsTree checks if the given filenames are in the tree // LsTree checks if the given filenames are in the tree
func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error) { func (repo *Repository) LsTree(ctx context.Context, ref string, filenames ...string) ([]string, error) {
cmd := gitcmd.NewCommand("ls-tree", "-z", "--name-only"). cmd := gitcmd.NewCommand("ls-tree", "-z", "--name-only").
AddDashesAndList(append([]string{ref}, filenames...)...) AddDashesAndList(append([]string{ref}, filenames...)...)
res, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx) res, _, err := cmd.WithDir(repo.Path).RunStdBytes(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -66,13 +66,13 @@ func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error
} }
// GetTreePathLatestCommit returns the latest commit of a tree path // GetTreePathLatestCommit returns the latest commit of a tree path
func (repo *Repository) GetTreePathLatestCommit(refName, treePath string) (*Commit, error) { func (repo *Repository) GetTreePathLatestCommit(ctx context.Context, refName, treePath string) (*Commit, error) {
stdout, _, err := gitcmd.NewCommand("rev-list", "-1"). stdout, _, err := gitcmd.NewCommand("rev-list", "-1").
AddDynamicArguments(refName).AddDashesAndList(treePath). AddDynamicArguments(refName).AddDashesAndList(treePath).
WithDir(repo.Path). WithDir(repo.Path).
RunStdString(repo.Ctx) RunStdString(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return repo.GetCommit(strings.TrimSpace(stdout)) return repo.GetCommit(ctx, strings.TrimSpace(stdout))
} }
+4 -4
View File
@@ -86,11 +86,11 @@ func EntryFollowLink(ctx context.Context, gitRepo *Repository, commit *Commit, f
// git's filename max length is 4096, hopefully a link won't be longer than multiple of that // git's filename max length is 4096, hopefully a link won't be longer than multiple of that
const maxSymlinkSize = 20 * 4096 const maxSymlinkSize = 20 * 4096
if te.Blob(gitRepo).Size() > maxSymlinkSize { if te.Blob(gitRepo).Size(ctx) > maxSymlinkSize {
return nil, util.ErrorWrap(util.ErrUnprocessableContent, "%q content exceeds symlink limit", fullPath) return nil, util.ErrorWrap(util.ErrUnprocessableContent, "%q content exceeds symlink limit", fullPath)
} }
link, err := te.Blob(gitRepo).GetBlobContent(maxSymlinkSize) link, err := te.Blob(gitRepo).GetBlobContent(ctx, maxSymlinkSize)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -126,8 +126,8 @@ func EntryFollowLinks(ctx context.Context, gitRepo *Repository, commit *Commit,
return res, nil return res, nil
} }
func (te *TreeEntry) Tree(gitRepo *Repository) *Tree { func (te *TreeEntry) Tree(ctx context.Context, gitRepo *Repository) *Tree {
t, err := gitRepo.getTree(te.ID) t, err := gitRepo.getTree(ctx, te.ID)
if err != nil { if err != nil {
return nil return nil
} }
+2 -2
View File
@@ -13,11 +13,11 @@ import (
) )
func TestFollowLink(t *testing.T) { func TestFollowLink(t *testing.T) {
r, err := OpenRepository(t.Context(), "tests/repos/repo1_bare") r, err := OpenRepository("tests/repos/repo1_bare")
require.NoError(t, err) require.NoError(t, err)
defer r.Close() defer r.Close()
commit, err := r.GetCommit("37991dec2c8e592043f47155ce4808d4580f9123") commit, err := r.GetCommit(t.Context(), "37991dec2c8e592043f47155ce4808d4580f9123")
require.NoError(t, err) require.NoError(t, err)
// get the symlink // get the symlink
+5 -5
View File
@@ -11,11 +11,11 @@ import (
) )
func TestSubTree_Issue29101(t *testing.T) { func TestSubTree_Issue29101(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare")) repo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetCommit("ce064814f4a0d337b333e646ece456cd39fab612") commit, err := repo.GetCommit(t.Context(), "ce064814f4a0d337b333e646ece456cd39fab612")
assert.NoError(t, err) assert.NoError(t, err)
// old code could produce a different error if called multiple times // old code could produce a different error if called multiple times
@@ -27,15 +27,15 @@ func TestSubTree_Issue29101(t *testing.T) {
} }
func Test_GetTreePathLatestCommit(t *testing.T) { func Test_GetTreePathLatestCommit(t *testing.T) {
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo6_blame")) repo, err := OpenRepository(filepath.Join(testReposDir, "repo6_blame"))
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commitID, err := repo.GetBranchCommitID("master") commitID, err := repo.GetBranchCommitID(t.Context(), "master")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7", commitID) assert.Equal(t, "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7", commitID)
commit, err := repo.GetTreePathLatestCommit("master", "blame.txt") commit, err := repo.GetTreePathLatestCommit(t.Context(), "master", "blame.txt")
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, commit) assert.NotNil(t, commit)
assert.Equal(t, "45fb6cbc12f970b04eacd5cd4165edd11c8d7376", commit.ID.String()) assert.Equal(t, "45fb6cbc12f970b04eacd5cd4165edd11c8d7376", commit.ID.String())
+1 -1
View File
@@ -186,7 +186,7 @@ func tryCreateBlameIgnoreRevsFile(ctx context.Context, gitRepo *git.Repository,
return "", nil, err return "", nil, err
} }
r, err := entry.Blob(gitRepo).DataAsync() r, err := entry.Blob(gitRepo).DataAsync(ctx)
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
+5 -5
View File
@@ -25,11 +25,11 @@ func TestReadingBlameOutputSha256(t *testing.T) {
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) { t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
storage := &mockRepository{path: "repo5_pulls_sha256"} storage := &mockRepository{path: "repo5_pulls_sha256"}
repo, err := OpenRepository(ctx, storage) repo, err := OpenRepository(storage)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetCommit("0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345") commit, err := repo.GetCommit(t.Context(), "0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345")
assert.NoError(t, err) assert.NoError(t, err)
parts := []*BlamePart{ parts := []*BlamePart{
@@ -71,7 +71,7 @@ func TestReadingBlameOutputSha256(t *testing.T) {
t.Run("With .git-blame-ignore-revs", func(t *testing.T) { t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
storage := &mockRepository{path: "repo6_blame_sha256"} storage := &mockRepository{path: "repo6_blame_sha256"}
repo, err := OpenRepository(ctx, storage) repo, err := OpenRepository(storage)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
@@ -129,10 +129,10 @@ func TestReadingBlameOutputSha256(t *testing.T) {
}, },
} }
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
for _, c := range cases { for _, c := range cases {
commit, err := repo.GetCommit(c.CommitID) commit, err := repo.GetCommit(t.Context(), c.CommitID)
assert.NoError(t, err) assert.NoError(t, err)
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass) blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
assert.NoError(t, err) assert.NoError(t, err)
+5 -5
View File
@@ -20,10 +20,10 @@ func TestReadingBlameOutput(t *testing.T) {
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) { t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
storage := &mockRepository{path: "repo5_pulls"} storage := &mockRepository{path: "repo5_pulls"}
repo, err := OpenRepository(ctx, storage) repo, err := OpenRepository(storage)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
commit, err := repo.GetCommit("f32b0a9dfd09a60f616f29158f772cedd89942d2") commit, err := repo.GetCommit(t.Context(), "f32b0a9dfd09a60f616f29158f772cedd89942d2")
assert.NoError(t, err) assert.NoError(t, err)
parts := []*BlamePart{ parts := []*BlamePart{
@@ -65,7 +65,7 @@ func TestReadingBlameOutput(t *testing.T) {
t.Run("With .git-blame-ignore-revs", func(t *testing.T) { t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
storage := &mockRepository{path: "repo6_blame"} storage := &mockRepository{path: "repo6_blame"}
repo, err := OpenRepository(ctx, storage) repo, err := OpenRepository(storage)
assert.NoError(t, err) assert.NoError(t, err)
defer repo.Close() defer repo.Close()
@@ -123,10 +123,10 @@ func TestReadingBlameOutput(t *testing.T) {
}, },
} }
objectFormat, err := repo.GetObjectFormat() objectFormat, err := repo.GetObjectFormat(t.Context())
assert.NoError(t, err) assert.NoError(t, err)
for _, c := range cases { for _, c := range cases {
commit, err := repo.GetCommit(c.CommitID) commit, err := repo.GetCommit(t.Context(), c.CommitID)
assert.NoError(t, err) assert.NoError(t, err)
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass) blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
+4 -4
View File
@@ -15,23 +15,23 @@ import (
// GetBranchesByPath returns a branch by its path // GetBranchesByPath returns a branch by its path
// if limit = 0 it will not limit // if limit = 0 it will not limit
func GetBranchesByPath(ctx context.Context, repo Repository, skip, limit int) ([]string, int, error) { func GetBranchesByPath(ctx context.Context, repo Repository, skip, limit int) ([]string, int, error) {
gitRepo, err := OpenRepository(ctx, repo) gitRepo, err := OpenRepository(repo)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
defer gitRepo.Close() defer gitRepo.Close()
return gitRepo.GetBranchNames(skip, limit) return gitRepo.GetBranchNames(ctx, skip, limit)
} }
func GetBranchCommitID(ctx context.Context, repo Repository, branch string) (string, error) { func GetBranchCommitID(ctx context.Context, repo Repository, branch string) (string, error) {
gitRepo, err := OpenRepository(ctx, repo) gitRepo, err := OpenRepository(repo)
if err != nil { if err != nil {
return "", err return "", err
} }
defer gitRepo.Close() defer gitRepo.Close()
return gitRepo.GetBranchCommitID(branch) return gitRepo.GetBranchCommitID(ctx, branch)
} }
// SetDefaultBranch sets default branch of repository. // SetDefaultBranch sets default branch of repository.
+5 -8
View File
@@ -18,10 +18,7 @@ import (
"gitea.dev/modules/util" "gitea.dev/modules/util"
) )
// Repository represents a git repository which stored in a disk type Repository = git.RepositoryFacade
type Repository interface {
RelativePath() string // We don't assume how the directory structure of the repository is, so we only need the relative path
}
// repoPath resolves the Repository.RelativePath (which is a unix-style path like "username/reponame.git") // repoPath resolves the Repository.RelativePath (which is a unix-style path like "username/reponame.git")
// to a local filesystem path according to setting.RepoRootPath // to a local filesystem path according to setting.RepoRootPath
@@ -30,8 +27,8 @@ var repoPath = func(repo Repository) string {
} }
// OpenRepository opens the repository at the given relative path with the provided context. // OpenRepository opens the repository at the given relative path with the provided context.
func OpenRepository(ctx context.Context, repo Repository) (*git.Repository, error) { func OpenRepository(repo Repository) (*git.Repository, error) {
return git.OpenRepository(ctx, repoPath(repo)) return git.OpenRepository(repoPath(repo))
} }
// contextKey is a value for use with context.WithValue. // contextKey is a value for use with context.WithValue.
@@ -47,7 +44,7 @@ func RepositoryFromContextOrOpen(ctx context.Context, repo Repository) (*git.Rep
gitRepo, err := RepositoryFromRequestContextOrOpen(reqCtx, repo) gitRepo, err := RepositoryFromRequestContextOrOpen(reqCtx, repo)
return gitRepo, util.NopCloser{}, err return gitRepo, util.NopCloser{}, err
} }
gitRepo, err := OpenRepository(ctx, repo) gitRepo, err := OpenRepository(repo)
return gitRepo, gitRepo, err return gitRepo, gitRepo, err
} }
@@ -58,7 +55,7 @@ func RepositoryFromRequestContextOrOpen(ctx reqctx.RequestContext, repo Reposito
if gitRepo, ok := ctx.Value(ck).(*git.Repository); ok { if gitRepo, ok := ctx.Value(ck).(*git.Repository); ok {
return gitRepo, nil return gitRepo, nil
} }
gitRepo, err := git.OpenRepository(ctx, ck.repoPath) gitRepo, err := git.OpenRepository(ck.repoPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
-14
View File
@@ -1,14 +0,0 @@
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package gitrepo
import (
"context"
"gitea.dev/modules/git"
)
func GetSigningKey(ctx context.Context) (*git.SigningKey, *git.Signature) {
return git.GetSigningKey(ctx)
}
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package gitrepo
func RepoGitURL(repo Repository) string {
return repoPath(repo)
}
-36
View File
@@ -1,36 +0,0 @@
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build gogit
package gitrepo
import (
"context"
"github.com/go-git/go-git/v5/plumbing"
)
// WalkReferences walks all the references from the repository
// refname is empty, ObjectTag or ObjectBranch. All other values should be treated as equivalent to empty.
func WalkReferences(ctx context.Context, repo Repository, walkfn func(sha1, refname string) error) (int, error) {
gitRepo, closer, err := RepositoryFromContextOrOpen(ctx, repo)
if err != nil {
return 0, err
}
defer closer.Close()
i := 0
iter, err := gitRepo.GoGitRepo().References()
if err != nil {
return i, err
}
defer iter.Close()
err = iter.ForEach(func(ref *plumbing.Reference) error {
err := walkfn(ref.Hash().String(), string(ref.Name()))
i++
return err
})
return i, err
}
-17
View File
@@ -1,17 +0,0 @@
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build !gogit
package gitrepo
import (
"context"
"gitea.dev/modules/git"
)
// WalkReferences walks all the references from the repository
func WalkReferences(ctx context.Context, repo Repository, walkfn func(sha1, refname string) error) (int, error) {
return git.WalkShowRef(ctx, repoPath(repo), nil, 0, 0, walkfn)
}
+1 -1
View File
@@ -42,7 +42,7 @@ func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Rep
// TODO: if no branch exists, it reports: exit status 128, fatal: this operation must be run in a work tree. // TODO: if no branch exists, it reports: exit status 128, fatal: this operation must be run in a work tree.
return nil, 0, fmt.Errorf("git.GrepSearch: %w", err) return nil, 0, fmt.Errorf("git.GrepSearch: %w", err)
} }
commitID, err := gitRepo.GetRefCommitID(ref.String()) commitID, err := gitRepo.GetRefCommitID(ctx, ref.String())
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("gitRepo.GetRefCommitID: %w", err) return nil, 0, fmt.Errorf("gitRepo.GetRefCommitID: %w", err)
} }
+2 -2
View File
@@ -37,7 +37,7 @@ func (db *DBIndexer) Index(id int64) error {
return err return err
} }
gitRepo, err := gitrepo.OpenRepository(ctx, repo) gitRepo, err := gitrepo.OpenRepository(repo)
if err != nil { if err != nil {
if err.Error() == "no such file or directory" { if err.Error() == "no such file or directory" {
return nil return nil
@@ -47,7 +47,7 @@ func (db *DBIndexer) Index(id int64) error {
defer gitRepo.Close() defer gitRepo.Close()
// Get latest commit for default branch // Get latest commit for default branch
commitID, err := gitRepo.GetBranchCommitID(repo.DefaultBranch) commitID, err := gitRepo.GetBranchCommitID(ctx, repo.DefaultBranch)
if err != nil { if err != nil {
if git.IsErrBranchNotExist(err) || git.IsErrNotExist(err) || setting.IsInTesting { if git.IsErrBranchNotExist(err) || git.IsErrNotExist(err) || setting.IsInTesting {
log.Debug("Unable to get commit ID for default branch %s in %s ... skipping this repository", repo.DefaultBranch, repo.FullName()) log.Debug("Unable to get commit ID for default branch %s in %s ... skipping this repository", repo.DefaultBranch, repo.FullName())
+7 -7
View File
@@ -42,8 +42,8 @@ func Unmarshal(filename string, content []byte) (*api.IssueTemplate, error) {
} }
// UnmarshalFromEntry parses out a valid template from the blob in entry // UnmarshalFromEntry parses out a valid template from the blob in entry
func UnmarshalFromEntry(gitRepo *git.Repository, entry *git.TreeEntry, dir string) (*api.IssueTemplate, error) { func UnmarshalFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry, dir string) (*api.IssueTemplate, error) {
return unmarshalFromEntry(gitRepo, entry, path.Join(dir, entry.Name())) // Filepaths in Git are ALWAYS '/' separated do not use filepath here return unmarshalFromEntry(ctx, gitRepo, entry, path.Join(dir, entry.Name())) // Filepaths in Git are ALWAYS '/' separated do not use filepath here
} }
// UnmarshalFromCommit parses out a valid template from the commit // UnmarshalFromCommit parses out a valid template from the commit
@@ -52,12 +52,12 @@ func UnmarshalFromCommit(ctx context.Context, gitRepo *git.Repository, commit *g
if err != nil { if err != nil {
return nil, fmt.Errorf("get entry for %q: %w", filename, err) return nil, fmt.Errorf("get entry for %q: %w", filename, err)
} }
return unmarshalFromEntry(gitRepo, entry, filename) return unmarshalFromEntry(ctx, gitRepo, entry, filename)
} }
// UnmarshalFromRepo parses out a valid template from the head commit of the branch // UnmarshalFromRepo parses out a valid template from the head commit of the branch
func UnmarshalFromRepo(ctx context.Context, repo *git.Repository, branch, filename string) (*api.IssueTemplate, error) { func UnmarshalFromRepo(ctx context.Context, repo *git.Repository, branch, filename string) (*api.IssueTemplate, error) {
commit, err := repo.GetBranchCommit(branch) commit, err := repo.GetBranchCommit(ctx, branch)
if err != nil { if err != nil {
return nil, fmt.Errorf("get commit on branch %q: %w", branch, err) return nil, fmt.Errorf("get commit on branch %q: %w", branch, err)
} }
@@ -65,12 +65,12 @@ func UnmarshalFromRepo(ctx context.Context, repo *git.Repository, branch, filena
return UnmarshalFromCommit(ctx, repo, commit, filename) return UnmarshalFromCommit(ctx, repo, commit, filename)
} }
func unmarshalFromEntry(gitRepo *git.Repository, entry *git.TreeEntry, filename string) (*api.IssueTemplate, error) { func unmarshalFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry, filename string) (*api.IssueTemplate, error) {
if size := entry.Blob(gitRepo).Size(); size > setting.UI.MaxDisplayFileSize { if size := entry.Blob(gitRepo).Size(ctx); size > setting.UI.MaxDisplayFileSize {
return nil, fmt.Errorf("too large: %v > MaxDisplayFileSize", size) return nil, fmt.Errorf("too large: %v > MaxDisplayFileSize", size)
} }
r, err := entry.Blob(gitRepo).DataAsync() r, err := entry.Blob(gitRepo).DataAsync(ctx)
if err != nil { if err != nil {
return nil, fmt.Errorf("data async: %w", err) return nil, fmt.Errorf("data async: %w", err)
} }
+4 -4
View File
@@ -33,7 +33,7 @@ func SyncRepoBranches(ctx context.Context, repoID, doerID int64) (int64, error)
log.Debug("SyncRepoBranches: in Repo[%d:%s]", repo.ID, repo.FullName()) log.Debug("SyncRepoBranches: in Repo[%d:%s]", repo.ID, repo.FullName())
gitRepo, err := gitrepo.OpenRepository(ctx, repo) gitRepo, err := gitrepo.OpenRepository(repo)
if err != nil { if err != nil {
log.Error("OpenRepository[%s]: %w", repo.FullName(), err) log.Error("OpenRepository[%s]: %w", repo.FullName(), err)
return 0, err return 0, err
@@ -45,7 +45,7 @@ func SyncRepoBranches(ctx context.Context, repoID, doerID int64) (int64, error)
} }
func SyncRepoBranchesWithRepo(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, doerID int64) (int64, []*SyncResult, error) { func SyncRepoBranchesWithRepo(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, doerID int64) (int64, []*SyncResult, error) {
objFmt, err := gitRepo.GetObjectFormat() objFmt, err := gitRepo.GetObjectFormat(ctx)
if err != nil { if err != nil {
return 0, nil, fmt.Errorf("GetObjectFormat: %w", err) return 0, nil, fmt.Errorf("GetObjectFormat: %w", err)
} }
@@ -58,7 +58,7 @@ func SyncRepoBranchesWithRepo(ctx context.Context, repo *repo_model.Repository,
allBranches := container.Set[string]{} allBranches := container.Set[string]{}
{ {
branches, _, err := gitRepo.GetBranchNames(0, 0) branches, _, err := gitRepo.GetBranchNames(ctx, 0, 0)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
} }
@@ -88,7 +88,7 @@ func SyncRepoBranchesWithRepo(ctx context.Context, repo *repo_model.Repository,
var syncResults []*SyncResult var syncResults []*SyncResult
for branch := range allBranches { for branch := range allBranches {
dbb := dbBranches[branch] dbb := dbBranches[branch]
commit, err := gitRepo.GetBranchCommit(branch) commit, err := gitRepo.GetBranchCommit(ctx, branch)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
} }
+2 -2
View File
@@ -47,7 +47,7 @@ func SyncRepoTags(ctx context.Context, repoID int64) error {
return err return err
} }
gitRepo, err := gitrepo.OpenRepository(ctx, repo) gitRepo, err := gitrepo.OpenRepository(repo)
if err != nil { if err != nil {
return err return err
} }
@@ -181,7 +181,7 @@ func (shortRelease) TableName() string {
// repositories like https://github.com/vim/vim (with over 13000 tags). // repositories like https://github.com/vim/vim (with over 13000 tags).
func SyncReleasesWithTags(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository) ([]*SyncResult, error) { func SyncReleasesWithTags(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository) ([]*SyncResult, error) {
log.Debug("SyncReleasesWithTags: in Repo[%d:%s/%s]", repo.ID, repo.OwnerName, repo.Name) log.Debug("SyncReleasesWithTags: in Repo[%d:%s/%s]", repo.ID, repo.OwnerName, repo.Name)
tags, _, err := gitRepo.GetTagInfos(0, 0) tags, _, err := gitRepo.GetTagInfos(ctx, 0, 0)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to GetTagInfos in pull-mirror Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err) return nil, fmt.Errorf("unable to GetTagInfos in pull-mirror Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err)
} }
+1 -1
View File
@@ -47,7 +47,7 @@ func GetBlob(ctx *context.APIContext) {
return return
} }
if blob, err := files_service.GetBlobBySHA(ctx.Repo.Repository, ctx.Repo.GitRepo, sha); err != nil { if blob, err := files_service.GetBlobBySHA(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, sha); err != nil {
ctx.APIError(http.StatusBadRequest, err.Error()) ctx.APIError(http.StatusBadRequest, err.Error())
} else { } else {
ctx.JSON(http.StatusOK, blob) ctx.JSON(http.StatusOK, blob)
+7 -7
View File
@@ -68,7 +68,7 @@ func GetBranch(ctx *context.APIContext) {
return return
} }
c, err := ctx.Repo.GitRepo.GetBranchCommit(branchName) c, err := ctx.Repo.GitRepo.GetBranchCommit(ctx, branchName)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -219,14 +219,14 @@ func CreateBranch(ctx *context.APIContext) {
var err error var err error
if len(opt.OldRefName) > 0 { if len(opt.OldRefName) > 0 {
oldCommit, err = ctx.Repo.GitRepo.GetCommit(opt.OldRefName) oldCommit, err = ctx.Repo.GitRepo.GetCommit(ctx, opt.OldRefName)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
} }
} else if len(opt.OldBranchName) > 0 { //nolint:staticcheck // deprecated field } else if len(opt.OldBranchName) > 0 { //nolint:staticcheck // deprecated field
if exist, _ := git_model.IsBranchExist(ctx, ctx.Repo.Repository.ID, opt.OldBranchName); exist { //nolint:staticcheck // deprecated field if exist, _ := git_model.IsBranchExist(ctx, ctx.Repo.Repository.ID, opt.OldBranchName); exist { //nolint:staticcheck // deprecated field
oldCommit, err = ctx.Repo.GitRepo.GetBranchCommit(opt.OldBranchName) //nolint:staticcheck // deprecated field oldCommit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx, opt.OldBranchName) //nolint:staticcheck // deprecated field
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -236,14 +236,14 @@ func CreateBranch(ctx *context.APIContext) {
return return
} }
} else { } else {
oldCommit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch) oldCommit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx, ctx.Repo.Repository.DefaultBranch)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
} }
} }
err = repo_service.CreateNewBranchFromCommit(ctx, ctx.Doer, ctx.Repo.Repository, oldCommit.ID.String(), opt.BranchName) err = repo_service.CreateNewBranchFromCommit(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, oldCommit.ID.String(), opt.BranchName)
if err != nil { if err != nil {
if git_model.IsErrBranchNotExist(err) { if git_model.IsErrBranchNotExist(err) {
ctx.APIError(http.StatusNotFound, "The old branch does not exist") ctx.APIError(http.StatusNotFound, "The old branch does not exist")
@@ -259,7 +259,7 @@ func CreateBranch(ctx *context.APIContext) {
return return
} }
commit, err := ctx.Repo.GitRepo.GetBranchCommit(opt.BranchName) commit, err := ctx.Repo.GitRepo.GetBranchCommit(ctx, opt.BranchName)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -360,7 +360,7 @@ func ListBranches(ctx *context.APIContext) {
apiBranches = make([]*api.Branch, 0, len(branches)) apiBranches = make([]*api.Branch, 0, len(branches))
for i := range branches { for i := range branches {
c, err := ctx.Repo.GitRepo.GetBranchCommit(branches[i].Name) c, err := ctx.Repo.GitRepo.GetBranchCommit(ctx, branches[i].Name)
if err != nil { if err != nil {
// Skip if this branch doesn't exist anymore. // Skip if this branch doesn't exist anymore.
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
+6 -6
View File
@@ -74,7 +74,7 @@ func GetSingleCommit(ctx *context.APIContext) {
} }
func getCommit(ctx *context.APIContext, identifier string, toCommitOpts convert.ToCommitOptions) { func getCommit(ctx *context.APIContext, identifier string, toCommitOpts convert.ToCommitOptions) {
commit, err := ctx.Repo.GitRepo.GetCommit(identifier) commit, err := ctx.Repo.GitRepo.GetCommit(ctx, identifier)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.APIErrorNotFound("commit doesn't exist: " + identifier) ctx.APIErrorNotFound("commit doesn't exist: " + identifier)
@@ -208,14 +208,14 @@ func GetAllCommits(ctx *context.APIContext) {
var baseCommit *git.Commit var baseCommit *git.Commit
if len(sha) == 0 { if len(sha) == 0 {
// no sha supplied - use default branch // no sha supplied - use default branch
baseCommit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch) baseCommit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx, ctx.Repo.Repository.DefaultBranch)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
} }
} else { } else {
// get commit specified by sha // get commit specified by sha
baseCommit, err = ctx.Repo.GitRepo.GetCommit(sha) baseCommit, err = ctx.Repo.GitRepo.GetCommit(ctx, sha)
if err != nil { if err != nil {
ctx.APIErrorAuto(err) ctx.APIErrorAuto(err)
return return
@@ -235,7 +235,7 @@ func GetAllCommits(ctx *context.APIContext) {
} }
// Query commits // Query commits
commits, err = baseCommit.CommitsByRange(ctx.Repo.GitRepo, listOptions.Page, listOptions.PageSize, not, since, until) commits, err = baseCommit.CommitsByRange(ctx, ctx.Repo.GitRepo, listOptions.Page, listOptions.PageSize, not, since, until)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -281,7 +281,7 @@ func GetAllCommits(ctx *context.APIContext) {
} }
} }
commits, _, err = ctx.Repo.GitRepo.CommitsByFileAndRange( commits, _, err = ctx.Repo.GitRepo.CommitsByFileAndRange(ctx,
git.CommitsByFileAndRangeOptions{ git.CommitsByFileAndRangeOptions{
Revision: sha, Revision: sha,
File: path, File: path,
@@ -360,7 +360,7 @@ func DownloadCommitDiffOrPatch(ctx *context.APIContext) {
sha := ctx.PathParam("sha") sha := ctx.PathParam("sha")
diffType := git.RawDiffType(ctx.PathParam("diffType")) diffType := git.RawDiffType(ctx.PathParam("diffType"))
if err := git.GetRawDiff(ctx.Repo.GitRepo, sha, diffType, ctx.Resp); err != nil { if err := git.GetRawDiff(ctx, ctx.Repo.GitRepo, sha, diffType, ctx.Resp); err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.APIErrorNotFound("commit doesn't exist: " + sha) ctx.APIErrorNotFound("commit doesn't exist: " + sha)
return return
+2 -2
View File
@@ -120,9 +120,9 @@ func downloadCompareDiffOrPatch(ctx *context.APIContext, compareInfo *git_servic
var err error var err error
if patch { if patch {
err = compareInfo.HeadGitRepo.GetPatch(compareArg, ctx.Resp) err = compareInfo.HeadGitRepo.GetPatch(ctx, compareArg, ctx.Resp)
} else { } else {
err = compareInfo.HeadGitRepo.GetDiff(compareArg, ctx.Resp) err = compareInfo.HeadGitRepo.GetDiff(ctx, compareArg, ctx.Resp)
} }
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
+1 -1
View File
@@ -14,7 +14,7 @@ import (
) )
func serveRepoArchive(ctx *context.APIContext, reqFileName string, paths []string) { func serveRepoArchive(ctx *context.APIContext, reqFileName string, paths []string) {
aReq, err := archiver_service.NewRequest(ctx.Repo.Repository, ctx.Repo.GitRepo, reqFileName, paths) aReq, err := archiver_service.NewRequest(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, reqFileName, paths)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.APIError(http.StatusBadRequest, err.Error()) ctx.APIError(http.StatusBadRequest, err.Error())
+3 -3
View File
@@ -136,7 +136,7 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
ctx.RespHeader().Set(giteaObjectTypeHeader, string(files_service.GetObjectTypeFromTreeEntry(entry))) ctx.RespHeader().Set(giteaObjectTypeHeader, string(files_service.GetObjectTypeFromTreeEntry(entry)))
// LFS Pointer files are at most 1024 bytes - so any blob greater than 1024 bytes cannot be an LFS file // LFS Pointer files are at most 1024 bytes - so any blob greater than 1024 bytes cannot be an LFS file
if blob.Size() > lfs.MetaFileMaxSize { if blob.Size(ctx) > lfs.MetaFileMaxSize {
// First handle caching for the blob // First handle caching for the blob
if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) { if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return return
@@ -151,7 +151,7 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
// OK, now the blob is known to have at most 1024 (lfs pointer max size) bytes, // OK, now the blob is known to have at most 1024 (lfs pointer max size) bytes,
// we can simply read this in one go (This saves reading it twice) // we can simply read this in one go (This saves reading it twice)
lfsPointerBuf, err := blob.GetBlobBytes(lfs.MetaFileMaxSize) lfsPointerBuf, err := blob.GetBlobBytes(ctx, lfs.MetaFileMaxSize)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -217,7 +217,7 @@ func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, entry *git.TreeEn
return nil, nil, nil return nil, nil, nil
} }
latestCommit, err := ctx.Repo.GitRepo.GetTreePathLatestCommit(ctx.Repo.Commit.ID.String(), ctx.Repo.TreePath) latestCommit, err := ctx.Repo.GitRepo.GetTreePathLatestCommit(ctx, ctx.Repo.Commit.ID.String(), ctx.Repo.TreePath)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return nil, nil, nil return nil, nil, nil
+1 -1
View File
@@ -66,7 +66,7 @@ func getNote(ctx *context.APIContext, identifier string) {
return return
} }
commitID, err := ctx.Repo.GitRepo.ConvertToGitID(identifier) commitID, err := ctx.Repo.GitRepo.ConvertToGitID(ctx, identifier)
if err != nil { if err != nil {
ctx.APIErrorAuto(err) ctx.APIErrorAuto(err)
return return
+4 -4
View File
@@ -1107,7 +1107,7 @@ func parseCompareInfo(ctx *context.APIContext, compareParam string) (result *git
headGitRepo = ctx.Repo.GitRepo headGitRepo = ctx.Repo.GitRepo
closer = func() {} // no need to close the head repo because it shares the base repo closer = func() {} // no need to close the head repo because it shares the base repo
} else { } else {
headGitRepo, err = gitrepo.OpenRepository(ctx, headRepo) headGitRepo, err = gitrepo.OpenRepository(headRepo)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return nil, nil return nil, nil
@@ -1146,12 +1146,12 @@ func parseCompareInfo(ctx *context.APIContext, compareParam string) (result *git
return nil, nil return nil, nil
} }
baseRef, err := common.ResolveRefWithSuffix(ctx.Repo.GitRepo, util.IfZero(compareReq.BaseOriRef, baseRepo.GetPullRequestTargetBranch(ctx)), compareReq.BaseOriRefSuffix) baseRef, err := common.ResolveRefWithSuffix(ctx, ctx.Repo.GitRepo, util.IfZero(compareReq.BaseOriRef, baseRepo.GetPullRequestTargetBranch(ctx)), compareReq.BaseOriRefSuffix)
if err != nil { if err != nil {
ctx.APIErrorAuto(err) ctx.APIErrorAuto(err)
return nil, nil return nil, nil
} }
headRef, err := common.ResolveRefWithSuffix(headGitRepo, util.IfZero(compareReq.HeadOriRef, headRepo.DefaultBranch), compareReq.HeadOriRefSuffix) headRef, err := common.ResolveRefWithSuffix(ctx, headGitRepo, util.IfZero(compareReq.HeadOriRef, headRepo.DefaultBranch), compareReq.HeadOriRefSuffix)
if err != nil { if err != nil {
ctx.APIErrorAuto(err) ctx.APIErrorAuto(err)
return nil, nil return nil, nil
@@ -1570,7 +1570,7 @@ func GetPullRequestFiles(ctx *context.APIContext) {
return return
} }
headCommitID, err := baseGitRepo.GetRefCommitID(pr.GetGitHeadRefName()) headCommitID, err := baseGitRepo.GetRefCommitID(ctx, pr.GetGitHeadRefName())
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
+2 -2
View File
@@ -526,7 +526,7 @@ func CreatePullReview(ctx *context.APIContext) {
} }
defer closer.Close() defer closer.Close()
headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitHeadRefName()) headCommitID, err := gitRepo.GetRefCommitID(ctx, pr.GetGitHeadRefName())
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -645,7 +645,7 @@ func SubmitPullReview(ctx *context.APIContext) {
return return
} }
headCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(pr.GetGitHeadRefName()) headCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(ctx, pr.GetGitHeadRefName())
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
+1 -1
View File
@@ -269,7 +269,7 @@ func CreateRelease(ctx *context.APIContext) {
} }
// GitHub doesn't have "tag_message", GitLab has: https://docs.gitlab.com/api/releases/#create-a-release // GitHub doesn't have "tag_message", GitLab has: https://docs.gitlab.com/api/releases/#create-a-release
// It doesn't need to be the same as the "release note" // It doesn't need to be the same as the "release note"
if err := release_service.CreateRelease(ctx.Repo.GitRepo, rel, nil, form.TagMessage); err != nil { if err := release_service.CreateRelease(ctx, ctx.Repo.GitRepo, rel, nil, form.TagMessage); err != nil {
if repo_model.IsErrReleaseAlreadyExist(err) { if repo_model.IsErrReleaseAlreadyExist(err) {
ctx.APIError(http.StatusConflict, err.Error()) ctx.APIError(http.StatusConflict, err.Error())
} else if release_service.IsErrProtectedTagName(err) { } else if release_service.IsErrProtectedTagName(err) {
+6 -6
View File
@@ -55,7 +55,7 @@ func ListTags(ctx *context.APIContext) {
listOpts := utils.GetListOptions(ctx) listOpts := utils.GetListOptions(ctx)
tags, total, err := ctx.Repo.GitRepo.GetTagInfos(listOpts.Page, listOpts.PageSize) tags, total, err := ctx.Repo.GitRepo.GetTagInfos(ctx, listOpts.Page, listOpts.PageSize)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return
@@ -107,13 +107,13 @@ func GetAnnotatedTag(ctx *context.APIContext) {
return return
} }
tag, err := ctx.Repo.GitRepo.GetAnnotatedTag(sha) tag, err := ctx.Repo.GitRepo.GetAnnotatedTag(ctx, sha)
if err != nil { if err != nil {
ctx.APIError(http.StatusBadRequest, err.Error()) ctx.APIError(http.StatusBadRequest, err.Error())
return return
} }
commit, err := ctx.Repo.GitRepo.GetTagCommit(tag.Name) commit, err := ctx.Repo.GitRepo.GetTagCommit(ctx, tag.Name)
if err != nil { if err != nil {
ctx.APIError(http.StatusBadRequest, err.Error()) ctx.APIError(http.StatusBadRequest, err.Error())
return return
@@ -151,7 +151,7 @@ func GetTag(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
tagName := ctx.PathParam("*") tagName := ctx.PathParam("*")
tag, err := ctx.Repo.GitRepo.GetTag(tagName) tag, err := ctx.Repo.GitRepo.GetTag(ctx, tagName)
if err != nil { if err != nil {
ctx.APIErrorNotFound("tag doesn't exist: " + tagName) ctx.APIErrorNotFound("tag doesn't exist: " + tagName)
return return
@@ -201,7 +201,7 @@ func CreateTag(ctx *context.APIContext) {
form.Target = ctx.Repo.Repository.DefaultBranch form.Target = ctx.Repo.Repository.DefaultBranch
} }
commit, err := ctx.Repo.GitRepo.GetCommit(form.Target) commit, err := ctx.Repo.GitRepo.GetCommit(ctx, form.Target)
if err != nil { if err != nil {
ctx.APIError(http.StatusNotFound, fmt.Sprintf("target not found: %v", err)) ctx.APIError(http.StatusNotFound, fmt.Sprintf("target not found: %v", err))
return return
@@ -221,7 +221,7 @@ func CreateTag(ctx *context.APIContext) {
return return
} }
tag, err := ctx.Repo.GitRepo.GetTag(form.TagName) tag, err := ctx.Repo.GitRepo.GetTag(ctx, form.TagName)
if err != nil { if err != nil {
ctx.APIErrorInternal(err) ctx.APIErrorInternal(err)
return return

Some files were not shown because too many files have changed in this diff Show More