mirror of
https://github.com/go-gitea/gitea.git
synced 2026-07-21 05:45:17 +02:00
refactor: remove Ctx field from git.Repository (#38500)
This commit is contained in:
@@ -129,7 +129,7 @@ func runRepoSyncReleases(ctx context.Context, _ *cli.Command) error {
|
||||
log.Trace("Processing next %d repos of %d", len(repos), count)
|
||||
for _, repo := range repos {
|
||||
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 {
|
||||
log.Warn("OpenRepository: %v", err)
|
||||
continue
|
||||
|
||||
@@ -73,7 +73,7 @@ func GetActivityStats(ctx context.Context, repo *repo_model.Repository, timeFrom
|
||||
}
|
||||
defer closer.Close()
|
||||
|
||||
code, err := gitRepo.GetCodeActivityStats(timeFrom, repo.DefaultBranch)
|
||||
code, err := gitRepo.GetCodeActivityStats(ctx, timeFrom, repo.DefaultBranch)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("FillFromGit: %w", err)
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository
|
||||
}
|
||||
defer closer.Close()
|
||||
|
||||
code, err := gitRepo.GetCodeActivityStats(timeFrom, "")
|
||||
code, err := gitRepo.GetCodeActivityStats(ctx, timeFrom, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("FillFromGit: %w", err)
|
||||
}
|
||||
|
||||
@@ -186,11 +186,11 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
|
||||
|
||||
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{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)
|
||||
defer gitRepo.Close()
|
||||
|
||||
commit, err := gitRepo.GetBranchCommit(repo2.DefaultBranch)
|
||||
commit, err := gitRepo.GetBranchCommit(t.Context(), repo2.DefaultBranch)
|
||||
assert.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
|
||||
@@ -108,14 +108,14 @@ func FixPublisherIDforTagReleases(ctx context.Context, x db.EngineMigration) 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 {
|
||||
log.Error("Error whilst opening git repo for [%d]%s/%s. Error: %v", repo.ID, repo.OwnerName, repo.Name, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
commit, err := gitRepo.GetTagCommit(release.TagName)
|
||||
commit, err := gitRepo.GetTagCommit(ctx, release.TagName)
|
||||
if err != nil {
|
||||
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)
|
||||
@@ -127,7 +127,7 @@ func FixPublisherIDforTagReleases(ctx context.Context, x db.EngineMigration) err
|
||||
|
||||
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)
|
||||
commit, err = gitRepo.GetCommit(commit.ID.String())
|
||||
commit, err = gitRepo.GetCommit(ctx, commit.ID.String())
|
||||
if err != nil {
|
||||
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)
|
||||
|
||||
@@ -87,7 +87,7 @@ func FixReleaseSha1OnReleaseTable(ctx context.Context, x db.EngineMigration) err
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func FixReleaseSha1OnReleaseTable(ctx context.Context, x db.EngineMigration) err
|
||||
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) {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -41,13 +41,13 @@ func (c *commitChecker) IsCommitIDExisting(commitID string) bool {
|
||||
if c.gitRepo == nil {
|
||||
r, closer, err := gitrepo.RepositoryFromContextOrOpen(c.ctx, c.gitRepoFacade)
|
||||
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
|
||||
}
|
||||
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
|
||||
return exist
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ func ParseScopedWorkflows(ctx context.Context, gitRepo *git.Repository, sourceCo
|
||||
|
||||
parsed := make([]*ParsedScopedWorkflow, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
content, err := GetContentFromEntry(gitRepo, entry)
|
||||
content, err := GetContentFromEntry(ctx, gitRepo, entry)
|
||||
if err != nil {
|
||||
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.
|
||||
// It returns the workflows whose `on:` matches, and those that matched the event but were excluded by a branch/paths filter (filtered).
|
||||
func MatchScopedWorkflows(
|
||||
ctx context.Context,
|
||||
parsed []*ParsedScopedWorkflow,
|
||||
consumerGitRepo *git.Repository,
|
||||
consumerCommit *git.Commit,
|
||||
@@ -77,7 +78,7 @@ func MatchScopedWorkflows(
|
||||
TriggerEvent: evt,
|
||||
Content: p.Content,
|
||||
}
|
||||
switch detectWorkflowMatch(consumerGitRepo, consumerCommit, triggedEvent, payload, evt) {
|
||||
switch detectWorkflowMatch(ctx, consumerGitRepo, consumerCommit, triggedEvent, payload, evt) {
|
||||
case detectMatched:
|
||||
matched = append(matched, dwf)
|
||||
case detectFilteredOut:
|
||||
|
||||
@@ -105,8 +105,8 @@ func listWorkflowsInDirs(ctx context.Context, gitRepo *git.Repository, commit *g
|
||||
return workflowDir, ret, nil
|
||||
}
|
||||
|
||||
func GetContentFromEntry(gitRepo *git.Repository, entry *git.TreeEntry) ([]byte, error) {
|
||||
f, err := entry.Blob(gitRepo).DataAsync()
|
||||
func GetContentFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry) ([]byte, error) {
|
||||
f, err := entry.Blob(gitRepo).DataAsync(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -189,7 +189,7 @@ func DetectWorkflows(
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
content, err := GetContentFromEntry(gitRepo, entry)
|
||||
content, err := GetContentFromEntry(ctx, gitRepo, entry)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
@@ -217,7 +217,7 @@ func DetectWorkflows(
|
||||
TriggerEvent: evt,
|
||||
Content: content,
|
||||
}
|
||||
switch detectWorkflowMatch(gitRepo, commit, triggedEvent, payload, evt) {
|
||||
switch detectWorkflowMatch(ctx, gitRepo, commit, triggedEvent, payload, evt) {
|
||||
case detectMatched:
|
||||
workflows = append(workflows, dwf)
|
||||
case detectFilteredOut:
|
||||
@@ -239,7 +239,7 @@ func DetectScheduledWorkflows(ctx context.Context, gitRepo *git.Repository, comm
|
||||
|
||||
wfs := make([]*DetectedWorkflow, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
content, err := GetContentFromEntry(gitRepo, entry)
|
||||
content, err := GetContentFromEntry(ctx, gitRepo, entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -266,7 +266,7 @@ func DetectScheduledWorkflows(ctx context.Context, gitRepo *git.Repository, comm
|
||||
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) {
|
||||
return detectNotApplicable
|
||||
}
|
||||
@@ -286,7 +286,7 @@ func detectWorkflowMatch(gitRepo *git.Repository, commit *git.Commit, triggedEve
|
||||
|
||||
case // push
|
||||
webhook_module.HookEventPush:
|
||||
return matchPushEvent(gitRepo, commit, payload.(*api.PushPayload), evt)
|
||||
return matchPushEvent(ctx, gitRepo, commit, payload.(*api.PushPayload), evt)
|
||||
|
||||
case // issues
|
||||
webhook_module.HookEventIssues,
|
||||
@@ -315,7 +315,7 @@ func detectWorkflowMatch(gitRepo *git.Repository, commit *git.Commit, triggedEve
|
||||
webhook_module.HookEventPullRequestLabel,
|
||||
webhook_module.HookEventPullRequestReviewRequest,
|
||||
webhook_module.HookEventPullRequestMilestone:
|
||||
return matchPullRequestEvent(gitRepo, commit, payload.(*api.PullRequestPayload), evt)
|
||||
return matchPullRequestEvent(ctx, gitRepo, commit, payload.(*api.PullRequestPayload), evt)
|
||||
|
||||
case // pull_request_review
|
||||
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
|
||||
if len(evt.Acts()) == 0 {
|
||||
return detectMatched
|
||||
@@ -425,7 +425,7 @@ func matchPushEvent(gitRepo *git.Repository, commit *git.Commit, pushPayload *ap
|
||||
matchTimes++
|
||||
break
|
||||
}
|
||||
filesChanged, err := commit.GetFilesChangedSinceCommit(gitRepo, pushPayload.Before)
|
||||
filesChanged, err := commit.GetFilesChangedSinceCommit(ctx, gitRepo, pushPayload.Before)
|
||||
if err != nil {
|
||||
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err)
|
||||
return detectNotApplicable
|
||||
@@ -442,7 +442,7 @@ func matchPushEvent(gitRepo *git.Repository, commit *git.Commit, pushPayload *ap
|
||||
matchTimes++
|
||||
break
|
||||
}
|
||||
filesChanged, err := commit.GetFilesChangedSinceCommit(gitRepo, pushPayload.Before)
|
||||
filesChanged, err := commit.GetFilesChangedSinceCommit(ctx, gitRepo, pushPayload.Before)
|
||||
if err != nil {
|
||||
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err)
|
||||
return detectNotApplicable
|
||||
@@ -516,7 +516,7 @@ func matchIssuesEvent(issuePayload *api.IssuePayload, evt *jobparser.Event) bool
|
||||
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()
|
||||
activityTypeMatched := false
|
||||
matchTimes := 0
|
||||
@@ -560,7 +560,7 @@ func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayloa
|
||||
err error
|
||||
)
|
||||
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 {
|
||||
log.Error("GetCommit [ref: %s]: %v", prPayload.PullRequest.Head.Sha, err)
|
||||
return detectNotApplicable
|
||||
@@ -592,7 +592,7 @@ func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayloa
|
||||
matchTimes++
|
||||
}
|
||||
case "paths":
|
||||
filesChanged, err := headCommit.GetFilesChangedSinceCommit(gitRepo, prPayload.PullRequest.MergeBase)
|
||||
filesChanged, err := headCommit.GetFilesChangedSinceCommit(ctx, gitRepo, prPayload.PullRequest.MergeBase)
|
||||
if err != nil {
|
||||
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err)
|
||||
return detectNotApplicable
|
||||
@@ -605,7 +605,7 @@ func matchPullRequestEvent(gitRepo *git.Repository, commit *git.Commit, prPayloa
|
||||
matchTimes++
|
||||
}
|
||||
case "paths-ignore":
|
||||
filesChanged, err := headCommit.GetFilesChangedSinceCommit(gitRepo, prPayload.PullRequest.MergeBase)
|
||||
filesChanged, err := headCommit.GetFilesChangedSinceCommit(ctx, gitRepo, prPayload.PullRequest.MergeBase)
|
||||
if err != nil {
|
||||
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err)
|
||||
return detectNotApplicable
|
||||
|
||||
@@ -243,7 +243,7 @@ func TestDetectMatched(t *testing.T) {
|
||||
evts, err := GetEventsFromContent(fullWorkflowContent(tc.yamlOn))
|
||||
assert.NoError(t, err)
|
||||
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]))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,15 +29,15 @@ type BatchChecker struct {
|
||||
|
||||
// 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
|
||||
func NewBatchChecker(repo *git.Repository, treeish string, attributes []string) (checker *BatchChecker, returnedErr error) {
|
||||
ctx, cancel := context.WithCancel(repo.Ctx)
|
||||
func NewBatchChecker(ctx context.Context, repo *git.Repository, treeish string, attributes []string) (checker *BatchChecker, returnedErr error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer func() {
|
||||
if returnedErr != nil {
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
|
||||
cmd, envs, cleanup, err := checkAttrCommand(repo, treeish, nil, attributes)
|
||||
cmd, envs, cleanup, err := checkAttrCommand(ctx, repo, treeish, nil, attributes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -118,7 +118,8 @@ func expectedAttrs() *Attributes {
|
||||
func Test_BatchChecker(t *testing.T) {
|
||||
setting.AppDataPath = t.TempDir()
|
||||
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)
|
||||
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) {
|
||||
defer test.MockVariableValue(&git.DefaultFeatures().SupportCheckAttrOnBare, false)()
|
||||
checker, err := NewBatchChecker(gitRepo, commitID, LinguistAttributes)
|
||||
checker, err := NewBatchChecker(ctx, gitRepo, commitID, LinguistAttributes)
|
||||
assert.NoError(t, err)
|
||||
defer checker.Close()
|
||||
attributes, err := checker.CheckPath("i-am-a-python.p")
|
||||
@@ -143,11 +144,11 @@ func Test_BatchChecker(t *testing.T) {
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
tempRepo, err := git.OpenRepository(t.Context(), dir)
|
||||
tempRepo, err := git.OpenRepository(dir)
|
||||
assert.NoError(t, err)
|
||||
defer tempRepo.Close()
|
||||
|
||||
checker, err := NewBatchChecker(tempRepo, "", LinguistAttributes)
|
||||
checker, err := NewBatchChecker(t.Context(), tempRepo, "", LinguistAttributes)
|
||||
assert.NoError(t, err)
|
||||
defer checker.Close()
|
||||
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) {
|
||||
checker, err := NewBatchChecker(gitRepo, commitID, LinguistAttributes)
|
||||
checker, err := NewBatchChecker(ctx, gitRepo, commitID, LinguistAttributes)
|
||||
assert.NoError(t, err)
|
||||
defer checker.Close()
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"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() {}
|
||||
envs := []string{"GIT_FLUSH=1"}
|
||||
cmd := gitcmd.NewCommand("check-attr", "-z")
|
||||
@@ -28,7 +28,7 @@ func checkAttrCommand(gitRepo *git.Repository, treeish string, filenames, attrib
|
||||
cmd.AddArguments("--source")
|
||||
cmd.AddDynamicArguments(treeish)
|
||||
} else {
|
||||
indexFilename, worktree, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(treeish)
|
||||
indexFilename, worktree, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(ctx, treeish)
|
||||
if err != nil {
|
||||
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.
|
||||
// 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) {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
func Test_Checker(t *testing.T) {
|
||||
setting.AppDataPath = t.TempDir()
|
||||
repoPath := "../tests/repos/language_stats_repo"
|
||||
gitRepo, err := git.OpenRepository(t.Context(), repoPath)
|
||||
gitRepo, err := git.OpenRepository(repoPath)
|
||||
require.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
|
||||
@@ -44,7 +44,7 @@ func Test_Checker(t *testing.T) {
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
tempRepo, err := git.OpenRepository(t.Context(), dir)
|
||||
tempRepo, err := git.OpenRepository(dir)
|
||||
assert.NoError(t, err)
|
||||
defer tempRepo.Close()
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ package git
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -23,11 +24,11 @@ func (b *Blob) Name() string {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return nil, nil
|
||||
}
|
||||
dataRc, err := b.DataAsync()
|
||||
dataRc, err := b.DataAsync(ctx)
|
||||
if err != nil {
|
||||
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
|
||||
func (b *Blob) GetBlobContent(limit int64) (string, error) {
|
||||
buf, err := b.GetBlobBytes(limit)
|
||||
func (b *Blob) GetBlobContent(ctx context.Context, limit int64) (string, error) {
|
||||
buf, err := b.GetBlobBytes(ctx, limit)
|
||||
return string(buf), err
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (b *Blob) GetBlobLineCount(w io.Writer) (int, error) {
|
||||
reader, err := b.DataAsync()
|
||||
func (b *Blob) GetBlobLineCount(ctx context.Context, w io.Writer) (int, error) {
|
||||
reader, err := b.DataAsync(ctx)
|
||||
if err != nil {
|
||||
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
|
||||
func (b *Blob) GetBlobContentBase64(originContent *strings.Builder) (string, error) {
|
||||
dataRc, err := b.DataAsync()
|
||||
func (b *Blob) GetBlobContentBase64(ctx context.Context, originContent *strings.Builder) (string, error) {
|
||||
dataRc, err := b.DataAsync(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -103,8 +104,8 @@ loop:
|
||||
}
|
||||
|
||||
// GuessContentType guesses the content type of the blob.
|
||||
func (b *Blob) GuessContentType() (typesniffer.SniffedType, error) {
|
||||
buf, err := b.GetBlobBytes(typesniffer.SniffContentSize)
|
||||
func (b *Blob) GuessContentType(ctx context.Context) (typesniffer.SniffedType, error) {
|
||||
buf, err := b.GetBlobBytes(ctx, typesniffer.SniffContentSize)
|
||||
if err != nil {
|
||||
return typesniffer.SniffedType{}, err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"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.
|
||||
// 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()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -36,7 +37,7 @@ func (b *Blob) DataAsync() (io.ReadCloser, error) {
|
||||
}
|
||||
|
||||
// Size returns the uncompressed size of the blob
|
||||
func (b *Blob) Size() int64 {
|
||||
func (b *Blob) Size(_ context.Context) int64 {
|
||||
obj, err := b.gogitEncodedObj()
|
||||
if err != nil {
|
||||
log.Error("Error getting gogit encoded object for blob %s(%s): %v", b.name, b.ID.String(), err)
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"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.
|
||||
// Calling the Close function on the result will discard all unread output.
|
||||
func (b *Blob) DataAsync() (_ io.ReadCloser, retErr error) {
|
||||
batch, cancel, err := b.repo.CatFileBatch(b.repo.Ctx)
|
||||
func (b *Blob) DataAsync(ctx context.Context) (_ io.ReadCloser, retErr error) {
|
||||
batch, cancel, err := b.repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -50,12 +51,12 @@ func (b *Blob) DataAsync() (_ io.ReadCloser, retErr error) {
|
||||
}
|
||||
|
||||
// Size returns the uncompressed size of the blob
|
||||
func (b *Blob) Size() int64 {
|
||||
func (b *Blob) Size(ctx context.Context) int64 {
|
||||
if b.gotSize {
|
||||
return b.size
|
||||
}
|
||||
|
||||
batch, cancel, err := b.repo.CatFileBatch(b.repo.Ctx)
|
||||
batch, cancel, err := b.repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
log.Debug("error whilst reading size for %s in %s. Error: %v", b.ID.String(), b.repo.Path, err)
|
||||
return 0
|
||||
|
||||
@@ -16,14 +16,14 @@ import (
|
||||
func TestBlob_Data(t *testing.T) {
|
||||
output := "file2\n"
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
repo, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
testBlob, err := repo.GetBlob("6c493ff740f9380390d5c9ddef4af18697ac9375")
|
||||
assert.NoError(t, err)
|
||||
|
||||
r, err := testBlob.DataAsync()
|
||||
r, err := testBlob.DataAsync(t.Context())
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, r)
|
||||
|
||||
@@ -36,7 +36,7 @@ func TestBlob_Data(t *testing.T) {
|
||||
|
||||
func Benchmark_Blob_Data(b *testing.B) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
repo, err := OpenRepository(b.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func Benchmark_Blob_Data(b *testing.B) {
|
||||
}
|
||||
|
||||
for b.Loop() {
|
||||
r, err := testBlob.DataAsync()
|
||||
r, err := testBlob.DataAsync(b.Context())
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ type CatFileBatch interface {
|
||||
|
||||
type CatFileBatchCloser interface {
|
||||
CatFileBatch
|
||||
Context() context.Context
|
||||
Close()
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ func (b *catFileBatchCommand) getBatch() *catFileBatchCommunicator {
|
||||
return b.batch
|
||||
}
|
||||
|
||||
func (b *catFileBatchCommand) Context() context.Context {
|
||||
return b.ctx
|
||||
}
|
||||
|
||||
func (b *catFileBatchCommand) QueryContent(obj string) (*CatFileObject, BufferedReader, error) {
|
||||
if strings.Contains(obj, "\n") {
|
||||
setting.PanicInDevOrTesting("invalid object name with newline: %q", obj)
|
||||
|
||||
@@ -51,6 +51,10 @@ func (b *catFileBatchLegacy) getBatchCheck() *catFileBatchCommunicator {
|
||||
return b.batchCheck
|
||||
}
|
||||
|
||||
func (b *catFileBatchLegacy) Context() context.Context {
|
||||
return b.ctx
|
||||
}
|
||||
|
||||
func (b *catFileBatchLegacy) QueryContent(obj string) (*CatFileObject, BufferedReader, error) {
|
||||
if strings.Contains(obj, "\n") {
|
||||
setting.PanicInDevOrTesting("invalid object name with newline: %q", obj)
|
||||
|
||||
@@ -46,12 +46,12 @@ func (c *Commit) ParentID(n int) (ObjectID, error) {
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parent, err := gitRepo.getCommit(id)
|
||||
parent, err := gitRepo.getCommit(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -65,11 +65,11 @@ func (c *Commit) ParentCount() int {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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 {
|
||||
@@ -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
|
||||
func (c *Commit) CommitsByRange(gitRepo *Repository, page, pageSize int, not, since, until string) ([]*Commit, error) {
|
||||
return gitRepo.commitsByRangeWithTime(c.ID, page, pageSize, not, since, until)
|
||||
func (c *Commit) CommitsByRange(ctx context.Context, gitRepo *Repository, page, pageSize int, not, since, until string) ([]*Commit, error) {
|
||||
return gitRepo.commitsByRangeWithTime(ctx, c.ID, page, pageSize, not, since, until)
|
||||
}
|
||||
|
||||
// CommitsBefore returns all the commits before current revision
|
||||
func (c *Commit) CommitsBefore(gitRepo *Repository) ([]*Commit, error) {
|
||||
return gitRepo.getCommitsBefore(c.ID)
|
||||
func (c *Commit) CommitsBefore(ctx context.Context, gitRepo *Repository) ([]*Commit, error) {
|
||||
return gitRepo.getCommitsBefore(ctx, c.ID)
|
||||
}
|
||||
|
||||
// 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
|
||||
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 {
|
||||
return false, err
|
||||
}
|
||||
@@ -136,7 +136,7 @@ func (c *Commit) IsForcePush(ctx context.Context, gitRepo *Repository, oldCommit
|
||||
return false, nil
|
||||
}
|
||||
|
||||
oldCommit, err := gitRepo.GetCommit(oldCommitID)
|
||||
oldCommit, err := gitRepo.GetCommit(ctx, oldCommitID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -145,13 +145,13 @@ func (c *Commit) IsForcePush(ctx context.Context, gitRepo *Repository, oldCommit
|
||||
}
|
||||
|
||||
// CommitsBeforeLimit returns num commits before current revision
|
||||
func (c *Commit) CommitsBeforeLimit(gitRepo *Repository, num int) ([]*Commit, error) {
|
||||
return gitRepo.getCommitsBeforeLimit(c.ID, num)
|
||||
func (c *Commit) CommitsBeforeLimit(ctx context.Context, gitRepo *Repository, num int) ([]*Commit, error) {
|
||||
return gitRepo.getCommitsBeforeLimit(ctx, c.ID, num)
|
||||
}
|
||||
|
||||
// CommitsBeforeUntil returns the commits in range "[cur, ref)"
|
||||
func (c *Commit) CommitsBeforeUntil(gitRepo *Repository, ref RefName) ([]*Commit, error) {
|
||||
return gitRepo.CommitsBetween(c.ID.RefName(), ref, -1)
|
||||
func (c *Commit) CommitsBeforeUntil(ctx context.Context, gitRepo *Repository, ref RefName) ([]*Commit, error) {
|
||||
return gitRepo.CommitsBetween(ctx, c.ID.RefName(), ref, -1)
|
||||
}
|
||||
|
||||
// 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
|
||||
func (c *Commit) SearchCommits(gitRepo *Repository, opts SearchCommitsOptions) ([]*Commit, error) {
|
||||
return gitRepo.searchCommits(c.ID, opts)
|
||||
func (c *Commit) SearchCommits(ctx context.Context, gitRepo *Repository, opts SearchCommitsOptions) ([]*Commit, error) {
|
||||
return gitRepo.searchCommits(ctx, c.ID, opts)
|
||||
}
|
||||
|
||||
// GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
|
||||
func (c *Commit) GetFilesChangedSinceCommit(gitRepo *Repository, pastCommit string) ([]string, error) {
|
||||
return gitRepo.GetFilesChangedBetween(pastCommit, c.ID.String())
|
||||
func (c *Commit) GetFilesChangedSinceCommit(ctx context.Context, gitRepo *Repository, pastCommit string) ([]string, error) {
|
||||
return gitRepo.GetFilesChangedBetween(ctx, pastCommit, c.ID.String())
|
||||
}
|
||||
|
||||
// FileChangedSinceCommit Returns true if the file given has changed since the past commit
|
||||
// YOU MUST ENSURE THAT pastCommit is a valid commit ID.
|
||||
func (c *Commit) FileChangedSinceCommit(gitRepo *Repository, filename, pastCommit string) (bool, error) {
|
||||
return gitRepo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
|
||||
func (c *Commit) FileChangedSinceCommit(ctx context.Context, gitRepo *Repository, filename, pastCommit string) (bool, error) {
|
||||
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
|
||||
@@ -216,7 +216,7 @@ func (c *Commit) GetFileContent(ctx context.Context, gitRepo *Repository, filena
|
||||
return "", err
|
||||
}
|
||||
|
||||
r, err := entry.Blob(gitRepo).DataAsync()
|
||||
r, err := entry.Blob(gitRepo).DataAsync(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, repoLink string, gitRepo
|
||||
var err error
|
||||
if gitRepo.LastCommitCache != nil {
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -132,11 +132,11 @@ func getFileHashes(c cgobject.CommitNode, treePath string, paths []string) (map[
|
||||
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
|
||||
results := make(map[string]*Commit)
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, repoLink string, gitRepo
|
||||
var revs map[string]*Commit
|
||||
if gitRepo.LastCommitCache != nil {
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -83,11 +83,11 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, repoLink string, gitRepo
|
||||
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
|
||||
results := make(map[string]*Commit)
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -125,7 +125,7 @@ func GetLastCommitForPaths(ctx context.Context, gitRepo *Repository, commit *Com
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -18,11 +18,11 @@ import (
|
||||
)
|
||||
|
||||
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)
|
||||
defer repo.Close()
|
||||
|
||||
commit, err := repo.GetCommit("feaf4ba6bc635fec442f46ddd4512416ec43c2c2")
|
||||
commit, err := repo.GetCommit(t.Context(), "feaf4ba6bc635fec442f46ddd4512416ec43c2c2")
|
||||
require.NoError(t, err)
|
||||
entries, err := commit.Tree().ListEntries(t.Context(), repo)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -84,7 +84,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) {
|
||||
}, "feaf4ba6bc635fec442f46ddd4512416ec43c2c2"},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
commit, err := repo1.GetCommit(testCase.CommitID)
|
||||
commit, err := repo1.GetCommit(t.Context(), testCase.CommitID)
|
||||
if err != nil {
|
||||
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.
|
||||
@@ -132,7 +132,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) {
|
||||
|
||||
func TestEntries_GetCommitsInfo(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
@@ -142,7 +142,7 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
clonedRepo1, err := OpenRepository(t.Context(), clonedPath)
|
||||
clonedRepo1, err := OpenRepository(clonedPath)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -151,7 +151,7 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
|
||||
testGetCommitsInfo(t, clonedRepo1)
|
||||
|
||||
t.Run("NonExistingSubmoduleAsNil", func(t *testing.T) {
|
||||
commit, err := bareRepo1.GetCommit("HEAD")
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), "HEAD")
|
||||
require.NoError(t, err)
|
||||
treeEntry, err := commit.GetTreeEntryByPath(t.Context(), bareRepo1, "file1.txt")
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -60,7 +60,7 @@ signed commit`
|
||||
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,
|
||||
}
|
||||
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.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
@@ -103,14 +103,14 @@ signed commit`, commitFromReader.Signature.Payload)
|
||||
func TestHasPreviousCommitSha256(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
|
||||
|
||||
repo, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
commit, err := repo.GetCommit("f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc")
|
||||
commit, err := repo.GetCommit(t.Context(), "f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc")
|
||||
assert.NoError(t, err)
|
||||
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
objectFormat, err := repo.GetObjectFormat(t.Context())
|
||||
assert.NoError(t, err)
|
||||
|
||||
parentSHA := MustIDFromString("b0ec7af4547047f12d5093e37ef8f1b3b5415ed8ee17894d43a34d7d34212e9c")
|
||||
|
||||
@@ -23,7 +23,7 @@ func (c *Commit) GetSubModules(ctx context.Context, gitRepo *Repository) (*Objec
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rd, err := entry.Blob(gitRepo).DataAsync()
|
||||
rd, err := entry.Blob(gitRepo).DataAsync(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ gpgsig -----BEGIN PGP SIGNATURE-----
|
||||
empty commit`
|
||||
|
||||
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.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
@@ -120,7 +120,7 @@ gpgsig -----BEGIN PGP SIGNATURE-----
|
||||
ISO-8859-1`
|
||||
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}
|
||||
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
|
||||
gitRepo, err := OpenRepository(filepath.Join(testReposDir, "repo1_bare"))
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
@@ -162,11 +162,11 @@ ISO-8859-1`, commitFromReader.Signature.Payload)
|
||||
func TestHasPreviousCommit(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
|
||||
repo, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
commit, err := repo.GetCommit("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0")
|
||||
commit, err := repo.GetCommit(t.Context(), "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0")
|
||||
assert.NoError(t, err)
|
||||
|
||||
parentSHA := MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2")
|
||||
@@ -187,14 +187,14 @@ func TestHasPreviousCommit(t *testing.T) {
|
||||
|
||||
func Test_GetCommitBranchStart(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
repo, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
commit, err := repo.GetBranchCommit("branch1")
|
||||
commit, err := repo.GetBranchCommit(t.Context(), "branch1")
|
||||
assert.NoError(t, err)
|
||||
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.NotEmpty(t, startCommitID)
|
||||
assert.Equal(t, "95bb4d39648ee7e325106df01a621c530863a653", startCommitID)
|
||||
|
||||
@@ -27,20 +27,20 @@ const (
|
||||
)
|
||||
|
||||
// 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) {
|
||||
cmd, err := getRepoRawDiffForFileCmd(repo.Ctx, repo, "", commitID, diffType, "")
|
||||
func GetRawDiff(ctx context.Context, repo *Repository, commitID string, diffType RawDiffType, writer io.Writer) (retErr error) {
|
||||
cmd, err := getRepoRawDiffForFileCmd(ctx, repo, "", commitID, diffType, "")
|
||||
if err != nil {
|
||||
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
|
||||
func GetFileDiffCutAroundLine(
|
||||
repo *Repository, startCommit, endCommit, treePath string,
|
||||
ctx context.Context, repo *Repository, startCommit, endCommit, treePath string,
|
||||
line int64, old bool, numbersOfLine int,
|
||||
) (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 {
|
||||
return "", fmt.Errorf("getRepoRawDiffForFileCmd: %w", err)
|
||||
}
|
||||
@@ -50,13 +50,13 @@ func GetFileDiffCutAroundLine(
|
||||
ret, err = CutDiffAroundLine(stdoutReader, line, old, numbersOfLine)
|
||||
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
|
||||
// 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) {
|
||||
commit, err := repo.GetCommit(endCommit)
|
||||
func getRepoRawDiffForFileCmd(ctx context.Context, repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string) (*gitcmd.Command, error) {
|
||||
commit, err := repo.GetCommit(ctx, endCommit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -75,7 +75,7 @@ func getRepoRawDiffForFileCmd(_ context.Context, repo *Repository, startCommit,
|
||||
} else if commit.ParentCount() == 0 {
|
||||
cmd.AddArguments("show").AddDynamicArguments(endCommit).AddDashesAndList(files...)
|
||||
} else {
|
||||
c, err := commit.Parent(repo, 0)
|
||||
c, err := commit.Parent(ctx, repo, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func getRepoRawDiffForFileCmd(_ context.Context, repo *Repository, startCommit,
|
||||
} else if commit.ParentCount() == 0 {
|
||||
cmd.AddArguments("format-patch", "--no-signature", "--stdout", "--root").AddDynamicArguments(endCommit).AddDashesAndList(files...)
|
||||
} else {
|
||||
c, err := commit.Parent(repo, 0)
|
||||
c, err := commit.Parent(ctx, repo, 0)
|
||||
if err != nil {
|
||||
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
|
||||
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() {
|
||||
startCommitID, err := repo.GetCommitBranchStart(env, branchName, newCommitID)
|
||||
startCommitID, err := repo.GetCommitBranchStart(ctx, env, branchName, newCommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -323,7 +323,7 @@ func GetAffectedFiles(repo *Repository, branchName, oldCommitID, newCommitID str
|
||||
}
|
||||
return scanner.Err()
|
||||
}).
|
||||
Run(repo.Ctx)
|
||||
Run(ctx)
|
||||
if err != nil {
|
||||
log.Error("Unable to get affected files for commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
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)
|
||||
defer repo.Close()
|
||||
|
||||
@@ -74,7 +74,7 @@ func TestGrepSearch(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
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.Empty(t, res)
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
)
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -43,7 +43,7 @@ func GetLanguageStats(_ context.Context, repo *git_module.Repository, commitID s
|
||||
return nil, err
|
||||
}
|
||||
|
||||
checker, err := attribute.NewBatchChecker(repo, commitID, attribute.LinguistAttributes)
|
||||
checker, err := attribute.NewBatchChecker(ctx, repo, commitID, attribute.LinguistAttributes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ func GetLanguageStats(ctx context.Context, repo *git.Repository, commitID string
|
||||
return nil, err
|
||||
}
|
||||
|
||||
checker, err := attribute.NewBatchChecker(repo, commitID, attribute.LinguistAttributes)
|
||||
checker, err := attribute.NewBatchChecker(ctx, repo, commitID, attribute.LinguistAttributes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -78,8 +78,6 @@ func GetLanguageStats(ctx context.Context, repo *git.Repository, commitID string
|
||||
|
||||
for _, f := range entries {
|
||||
select {
|
||||
case <-repo.Ctx.Done():
|
||||
return sizes, repo.Ctx.Err()
|
||||
case <-ctx.Done():
|
||||
return sizes, ctx.Err()
|
||||
default:
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
func TestRepository_GetLanguageStats(t *testing.T) {
|
||||
setting.AppDataPath = t.TempDir()
|
||||
repoPath := "../tests/repos/language_stats_repo"
|
||||
gitRepo, err := git.OpenRepository(t.Context(), repoPath)
|
||||
gitRepo, err := git.OpenRepository(repoPath)
|
||||
require.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"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
|
||||
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 {
|
||||
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 {
|
||||
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
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lastCommit, err := c.Get(sha.String(), entryPath)
|
||||
lastCommit, err := c.Get(ctx, sha.String(), entryPath)
|
||||
if err != nil || lastCommit != nil {
|
||||
return lastCommit, err
|
||||
}
|
||||
|
||||
lastCommit, err = c.repo.getCommitByPathWithID(sha, entryPath)
|
||||
lastCommit, err = c.repo.getCommitByPathWithID(ctx, sha, entryPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ type Note struct {
|
||||
// FIXME: Add LastCommitCache support
|
||||
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)
|
||||
notes, err := repo.GetCommit(NotesRef)
|
||||
notes, err := repo.GetCommit(ctx, NotesRef)
|
||||
if err != nil {
|
||||
if IsErrNotExist(err) {
|
||||
return err
|
||||
@@ -62,7 +62,7 @@ func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note)
|
||||
}
|
||||
|
||||
blob := entry.Blob(repo)
|
||||
dataRc, err := blob.DataAsync()
|
||||
dataRc, err := blob.DataAsync(ctx)
|
||||
if err != nil {
|
||||
log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err)
|
||||
return err
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
func TestGetNotes(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
@@ -25,7 +25,7 @@ func TestGetNotes(t *testing.T) {
|
||||
|
||||
func TestGetNestedNotes(t *testing.T) {
|
||||
repoPath := filepath.Join(testReposDir, "repo3_notes")
|
||||
repo, err := OpenRepository(t.Context(), repoPath)
|
||||
repo, err := OpenRepository(repoPath)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestGetNestedNotes(t *testing.T) {
|
||||
|
||||
func TestGetNonExistentNotes(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
@@ -19,7 +20,7 @@ import (
|
||||
)
|
||||
|
||||
// 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{}
|
||||
results := make([]*LFSResult, 0)
|
||||
|
||||
@@ -80,6 +81,6 @@ func FindLFSFile(repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, err
|
||||
}
|
||||
|
||||
sort.Sort(lfsResultSlice(results))
|
||||
err = fillResultNameRev(repo.Ctx, repo.Path, results)
|
||||
err = fillResultNameRev(ctx, repo.Path, results)
|
||||
return results, err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package pipeline
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sort"
|
||||
|
||||
@@ -16,24 +17,24 @@ import (
|
||||
)
|
||||
|
||||
// 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")
|
||||
revListReader, revListReaderClose := cmd.MakeStdoutPipe()
|
||||
defer revListReaderClose()
|
||||
err := cmd.WithDir(repo.Path).
|
||||
WithPipelineFunc(func(context gitcmd.Context) (err error) {
|
||||
results, err = findLFSFileFunc(repo, objectID, revListReader)
|
||||
results, err = findLFSFileFunc(ctx, repo, objectID, revListReader)
|
||||
return err
|
||||
}).RunWithStderr(repo.Ctx)
|
||||
}).RunWithStderr(ctx)
|
||||
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{}
|
||||
results := make([]*LFSResult, 0)
|
||||
// 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
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -145,6 +146,6 @@ func findLFSFileFunc(repo *git.Repository, objectID git.ObjectID, revListReader
|
||||
}
|
||||
|
||||
sort.Sort(lfsResultSlice(results))
|
||||
err = fillResultNameRev(repo.Ctx, repo.Path, results)
|
||||
err = fillResultNameRev(ctx, repo.Path, results)
|
||||
return results, err
|
||||
}
|
||||
|
||||
@@ -15,13 +15,13 @@ import (
|
||||
|
||||
func TestFindLFSFile(t *testing.T) {
|
||||
repoPath := "../../../tests/gitea-repositories-meta/user2/lfs.git"
|
||||
gitRepo, err := git.OpenRepository(t.Context(), repoPath)
|
||||
gitRepo, err := git.OpenRepository(repoPath)
|
||||
require.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
|
||||
objectID := git.MustIDFromString("2b6c6c4eaefa24b22f2092c3d54b263ff26feb58")
|
||||
|
||||
stats, err := FindLFSFile(gitRepo, objectID)
|
||||
stats, err := FindLFSFile(t.Context(), gitRepo, objectID)
|
||||
require.NoError(t, err)
|
||||
|
||||
tm, err := time.Parse(time.RFC3339, "2022-12-21T17:56:42-05:00")
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@@ -50,8 +51,8 @@ type Reference struct {
|
||||
}
|
||||
|
||||
// Commit return the commit of the reference
|
||||
func (ref *Reference) Commit() (*Commit, error) {
|
||||
return ref.repo.getCommit(ref.Object)
|
||||
func (ref *Reference) Commit(ctx context.Context) (*Commit, error) {
|
||||
return ref.repo.getCommit(ctx, ref.Object)
|
||||
}
|
||||
|
||||
// ShortName returns the short name of the reference
|
||||
|
||||
@@ -19,6 +19,23 @@ import (
|
||||
"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`
|
||||
|
||||
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 {
|
||||
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
|
||||
if len(logs) == 0 {
|
||||
return commits, nil
|
||||
@@ -41,7 +58,7 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro
|
||||
parts := bytes.SplitSeq(logs, []byte{'\n'})
|
||||
|
||||
for commitID := range parts {
|
||||
commit, err := repo.GetCommit(string(commitID))
|
||||
commit, err := repo.GetCommit(ctx, string(commitID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -81,12 +98,12 @@ func InitRepository(ctx context.Context, repoPath string, bare bool, objectForma
|
||||
}
|
||||
|
||||
// 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().
|
||||
AddOptionFormat("--git-dir=%s", repo.Path).
|
||||
AddArguments("rev-list", "-n", "1", "--all").
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
if (gitcmd.IsErrorExitCode(err, 1) && err.Stderr() == "") || gitcmd.IsErrorExitCode(err, 129) {
|
||||
// git 2.11 exits with 129 if the repo is empty
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
|
||||
gitealog "gitea.dev/modules/log"
|
||||
@@ -24,22 +23,14 @@ import (
|
||||
|
||||
const isGogit = true
|
||||
|
||||
// Repository represents a Git repository.
|
||||
type Repository struct {
|
||||
Path string
|
||||
|
||||
tagCache *ObjectCache[*Tag]
|
||||
RepositoryBase
|
||||
|
||||
gogitRepo *gogit.Repository
|
||||
gogitStorage *filesystem.Storage
|
||||
|
||||
Ctx context.Context
|
||||
LastCommitCache *LastCommitCache
|
||||
objectFormat ObjectFormat
|
||||
}
|
||||
|
||||
// OpenRepository opens the repository at the given path within the context.Context
|
||||
func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
|
||||
func OpenRepository(repoPath string) (*Repository, error) {
|
||||
repoPath, err := filepath.Abs(repoPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -74,14 +65,13 @@ func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Repository{
|
||||
Path: repoPath,
|
||||
gogitRepo: gogitRepo,
|
||||
gogitStorage: storage,
|
||||
tagCache: newObjectCache[*Tag](),
|
||||
Ctx: ctx,
|
||||
objectFormat: ParseGogitHash(plumbing.ZeroHash).Type(),
|
||||
}, nil
|
||||
repo := &Repository{
|
||||
RepositoryBase: prepareRepositoryBase(repoPath),
|
||||
gogitRepo: gogitRepo,
|
||||
gogitStorage: storage,
|
||||
}
|
||||
repo.objectFormatCache = ParseGogitHash(plumbing.ZeroHash).Type()
|
||||
return repo, nil
|
||||
}
|
||||
|
||||
// Close this repository, in particular close the underlying gogitStorage if this is not nil
|
||||
|
||||
@@ -12,29 +12,21 @@ import (
|
||||
"sync"
|
||||
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
const isGogit = false
|
||||
|
||||
// Repository represents a Git repository.
|
||||
type Repository struct {
|
||||
Path string
|
||||
|
||||
tagCache *ObjectCache[*Tag]
|
||||
RepositoryBase
|
||||
|
||||
mu sync.Mutex
|
||||
catFileBatchCloser CatFileBatchCloser
|
||||
catFileBatchInUse bool
|
||||
|
||||
Ctx context.Context
|
||||
LastCommitCache *LastCommitCache
|
||||
|
||||
objectFormat ObjectFormat
|
||||
}
|
||||
|
||||
// OpenRepository opens the repository at the given path with the provided context.
|
||||
func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
|
||||
func OpenRepository(repoPath string) (*Repository, error) {
|
||||
repoPath, err := filepath.Abs(repoPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -46,12 +38,7 @@ func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
|
||||
if !exist {
|
||||
return nil, util.NewNotExistErrorf("no such file or directory")
|
||||
}
|
||||
|
||||
return &Repository{
|
||||
Path: repoPath,
|
||||
tagCache: newObjectCache[*Tag](),
|
||||
Ctx: ctx,
|
||||
}, nil
|
||||
return &Repository{RepositoryBase: prepareRepositoryBase(repoPath)}, nil
|
||||
}
|
||||
|
||||
// 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()
|
||||
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 {
|
||||
repo.catFileBatchCloser, err = NewBatch(ctx, repo.Path)
|
||||
if err != nil {
|
||||
@@ -87,6 +82,7 @@ func (repo *Repository) CatFileBatch(ctx context.Context) (_ CatFileBatch, close
|
||||
|
||||
func (repo *Repository) Close() error {
|
||||
if repo == nil {
|
||||
setting.PanicInDevOrTesting("don't close a nil repository")
|
||||
return nil
|
||||
}
|
||||
repo.mu.Lock()
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
func TestRepoCatFileBatch(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)
|
||||
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())
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
func TestRepository_GetBlob_Found(t *testing.T) {
|
||||
repoPath := filepath.Join(testReposDir, "repo1_bare")
|
||||
r, err := OpenRepository(t.Context(), repoPath)
|
||||
r, err := OpenRepository(repoPath)
|
||||
assert.NoError(t, err)
|
||||
defer r.Close()
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestRepository_GetBlob_Found(t *testing.T) {
|
||||
blob, err := r.GetBlob(testCase.OID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
dataReader, err := blob.DataAsync()
|
||||
dataReader, err := blob.DataAsync(t.Context())
|
||||
assert.NoError(t, err)
|
||||
|
||||
data, err := io.ReadAll(dataReader)
|
||||
@@ -42,7 +42,7 @@ func TestRepository_GetBlob_Found(t *testing.T) {
|
||||
|
||||
func TestRepository_GetBlob_NotExist(t *testing.T) {
|
||||
repoPath := filepath.Join(testReposDir, "repo1_bare")
|
||||
r, err := OpenRepository(t.Context(), repoPath)
|
||||
r, err := OpenRepository(repoPath)
|
||||
assert.NoError(t, err)
|
||||
defer r.Close()
|
||||
|
||||
@@ -56,7 +56,7 @@ func TestRepository_GetBlob_NotExist(t *testing.T) {
|
||||
|
||||
func TestRepository_GetBlob_NoId(t *testing.T) {
|
||||
repoPath := filepath.Join(testReposDir, "repo1_bare")
|
||||
r, err := OpenRepository(t.Context(), repoPath)
|
||||
r, err := OpenRepository(repoPath)
|
||||
assert.NoError(t, err)
|
||||
defer r.Close()
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
)
|
||||
|
||||
@@ -12,13 +14,13 @@ import (
|
||||
const BranchPrefix = "refs/heads/"
|
||||
|
||||
// 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")
|
||||
if fetch {
|
||||
cmd.AddArguments("-f")
|
||||
}
|
||||
_, _, err := cmd.AddDynamicArguments(name, url).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
@@ -19,7 +20,7 @@ import (
|
||||
// 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.
|
||||
// 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 == "" {
|
||||
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.
|
||||
// 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.
|
||||
func (repo *Repository) IsReferenceExist(name string) bool {
|
||||
func (repo *Repository) IsReferenceExist(_ context.Context, name string) bool {
|
||||
if name == "" {
|
||||
return false
|
||||
}
|
||||
@@ -44,7 +45,7 @@ func (repo *Repository) IsReferenceExist(name string) bool {
|
||||
}
|
||||
|
||||
// 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 == "" {
|
||||
return false
|
||||
}
|
||||
@@ -60,7 +61,7 @@ func (repo *Repository) IsBranchExist(name string) bool {
|
||||
// Branches are returned with sort of `-committerdate` as the nogogit
|
||||
// implementation. This requires full fetch, sort and then the
|
||||
// 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 {
|
||||
name string
|
||||
committerDate int64
|
||||
@@ -100,7 +101,7 @@ func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
|
||||
}
|
||||
|
||||
// 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
|
||||
var iter storer.ReferenceIter
|
||||
var err error
|
||||
@@ -130,13 +131,13 @@ func (repo *Repository) WalkReferences(arg ObjectType, skip, limit int, walkfn f
|
||||
if limit != 0 && i >= skip+limit {
|
||||
return storer.ErrStop
|
||||
}
|
||||
return nil
|
||||
return ctx.Err()
|
||||
})
|
||||
return i, err
|
||||
}
|
||||
|
||||
// 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
|
||||
iter, err := repo.gogitRepo.References()
|
||||
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) {
|
||||
revList = append(revList, string(ref.Name()))
|
||||
}
|
||||
return nil
|
||||
return ctx.Err()
|
||||
})
|
||||
return revList, err
|
||||
}
|
||||
|
||||
@@ -18,12 +18,12 @@ import (
|
||||
|
||||
// IsObjectExist returns true if the given object exists in the repository.
|
||||
// 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 == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
log.Debug("Error opening CatFileBatch %v", err)
|
||||
return false
|
||||
@@ -38,12 +38,12 @@ func (repo *Repository) IsObjectExist(name string) bool {
|
||||
}
|
||||
|
||||
// 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 == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
log.Error("Error opening CatFileBatch %v", err)
|
||||
return false
|
||||
@@ -54,23 +54,23 @@ func (repo *Repository) IsReferenceExist(name string) bool {
|
||||
}
|
||||
|
||||
// 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 == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
return repo.IsReferenceExist(BranchPrefix + name)
|
||||
return repo.IsReferenceExist(ctx, BranchPrefix+name)
|
||||
}
|
||||
|
||||
// GetBranchNames returns branches from the repository, skipping "skip" initial branches and
|
||||
// returning at most "limit" branches, or all branches if "limit" is 0.
|
||||
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
|
||||
return callShowRef(repo.Ctx, repo.Path, BranchPrefix, gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}, skip, limit)
|
||||
func (repo *Repository) GetBranchNames(ctx context.Context, skip, limit int) ([]string, int, error) {
|
||||
return callShowRef(ctx, repo.Path, BranchPrefix, gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}, skip, limit)
|
||||
}
|
||||
|
||||
// WalkReferences walks all the references from the repository
|
||||
// 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
|
||||
switch refType {
|
||||
case ObjectTag:
|
||||
@@ -79,7 +79,7 @@ func (repo *Repository) WalkReferences(refType ObjectType, skip, limit int, walk
|
||||
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
|
||||
@@ -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
|
||||
func (repo *Repository) GetRefsBySha(sha, prefix string) ([]string, error) {
|
||||
func (repo *Repository) GetRefsBySha(ctx context.Context, sha, prefix string) ([]string, error) {
|
||||
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) {
|
||||
revList = append(revList, refname)
|
||||
}
|
||||
|
||||
@@ -13,25 +13,25 @@ import (
|
||||
|
||||
func TestRepository_GetBranches(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
branches, countAll, err := bareRepo1.GetBranchNames(0, 2)
|
||||
branches, countAll, err := bareRepo1.GetBranchNames(t.Context(), 0, 2)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, branches, 2)
|
||||
assert.Equal(t, 3, countAll)
|
||||
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.Len(t, branches, 3)
|
||||
assert.Equal(t, 3, countAll)
|
||||
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.Empty(t, branches)
|
||||
@@ -41,14 +41,14 @@ func TestRepository_GetBranches(t *testing.T) {
|
||||
|
||||
func BenchmarkRepository_GetBranches(b *testing.B) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(b.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer bareRepo1.Close()
|
||||
|
||||
for b.Loop() {
|
||||
_, _, err := bareRepo1.GetBranchNames(0, 0)
|
||||
_, _, err := bareRepo1.GetBranchNames(b.Context(), 0, 0)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
@@ -57,47 +57,48 @@ func BenchmarkRepository_GetBranches(b *testing.B) {
|
||||
|
||||
func TestGetRefsBySha(t *testing.T) {
|
||||
bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls")
|
||||
bareRepo5, err := OpenRepository(t.Context(), bareRepo5Path)
|
||||
bareRepo5, err := OpenRepository(bareRepo5Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer bareRepo5.Close()
|
||||
|
||||
// do not exist
|
||||
branches, err := bareRepo5.GetRefsBySha("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "")
|
||||
branches, err := bareRepo5.GetRefsBySha(t.Context(), "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "")
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, branches)
|
||||
|
||||
// refs/pull/1/head
|
||||
branches, err = bareRepo5.GetRefsBySha("c83380d7056593c51a699d12b9c00627bd5743e9", PullPrefix)
|
||||
branches, err = bareRepo5.GetRefsBySha(t.Context(), "c83380d7056593c51a699d12b9c00627bd5743e9", PullPrefix)
|
||||
assert.NoError(t, err)
|
||||
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.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.Equal(t, []string{"refs/heads/test-patch-1"}, branches)
|
||||
}
|
||||
|
||||
func BenchmarkGetRefsBySha(b *testing.B) {
|
||||
bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls")
|
||||
bareRepo5, err := OpenRepository(b.Context(), bareRepo5Path)
|
||||
bareRepo5, err := OpenRepository(bareRepo5Path)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer bareRepo5.Close()
|
||||
|
||||
_, _ = bareRepo5.GetRefsBySha("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "")
|
||||
_, _ = bareRepo5.GetRefsBySha("d8e0bbb45f200e67d9a784ce55bd90821af45ebd", "")
|
||||
_, _ = bareRepo5.GetRefsBySha("c83380d7056593c51a699d12b9c00627bd5743e9", "")
|
||||
_, _ = bareRepo5.GetRefsBySha("58a4bcc53ac13e7ff76127e0fb518b5262bf09af", "")
|
||||
_, _ = bareRepo5.GetRefsBySha(b.Context(), "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "")
|
||||
_, _ = bareRepo5.GetRefsBySha(b.Context(), "d8e0bbb45f200e67d9a784ce55bd90821af45ebd", "")
|
||||
_, _ = bareRepo5.GetRefsBySha(b.Context(), "c83380d7056593c51a699d12b9c00627bd5743e9", "")
|
||||
_, _ = bareRepo5.GetRefsBySha(b.Context(), "58a4bcc53ac13e7ff76127e0fb518b5262bf09af", "")
|
||||
}
|
||||
|
||||
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)
|
||||
defer repo.Close()
|
||||
|
||||
@@ -143,13 +144,14 @@ func TestRepository_IsObjectExist(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
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) {
|
||||
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)
|
||||
defer repo.Close()
|
||||
|
||||
@@ -195,7 +197,7 @@ func TestRepository_IsReferenceExist(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
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))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ package git
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -15,36 +16,36 @@ import (
|
||||
)
|
||||
|
||||
// GetBranchCommitID returns last commit ID string of given branch.
|
||||
func (repo *Repository) GetBranchCommitID(name string) (string, error) {
|
||||
return repo.GetRefCommitID(BranchPrefix + name)
|
||||
func (repo *Repository) GetBranchCommitID(ctx context.Context, name string) (string, error) {
|
||||
return repo.GetRefCommitID(ctx, BranchPrefix+name)
|
||||
}
|
||||
|
||||
// GetTagCommitID returns last commit ID string of given tag.
|
||||
func (repo *Repository) GetTagCommitID(name string) (string, error) {
|
||||
return repo.GetRefCommitID(TagPrefix + name)
|
||||
func (repo *Repository) GetTagCommitID(ctx context.Context, name string) (string, error) {
|
||||
return repo.GetRefCommitID(ctx, TagPrefix+name)
|
||||
}
|
||||
|
||||
// GetCommit returns a commit object of by the git ref.
|
||||
func (repo *Repository) GetCommit(ref string) (*Commit, error) {
|
||||
id, err := repo.ConvertToGitID(ref)
|
||||
func (repo *Repository) GetCommit(ctx context.Context, ref string) (*Commit, error) {
|
||||
id, err := repo.ConvertToGitID(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return repo.getCommit(id)
|
||||
return repo.getCommit(ctx, id)
|
||||
}
|
||||
|
||||
// GetBranchCommit returns the last commit of given branch.
|
||||
func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
|
||||
return repo.GetCommit(RefNameFromBranch(name).String())
|
||||
func (repo *Repository) GetBranchCommit(ctx context.Context, name string) (*Commit, error) {
|
||||
return repo.GetCommit(ctx, RefNameFromBranch(name).String())
|
||||
}
|
||||
|
||||
// GetTagCommit get the commit of the specific tag via name
|
||||
func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
|
||||
return repo.GetCommit(RefNameFromTag(name).String())
|
||||
func (repo *Repository) GetTagCommit(ctx context.Context, name string) (*Commit, error) {
|
||||
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.
|
||||
if strings.HasPrefix(relpath, ":") {
|
||||
relpath = `\` + relpath
|
||||
@@ -54,7 +55,7 @@ func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Com
|
||||
AddDynamicArguments(id.String()).
|
||||
AddDashesAndList(relpath).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
}
|
||||
@@ -64,20 +65,20 @@ func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Com
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return repo.getCommit(id)
|
||||
return repo.getCommit(ctx, id)
|
||||
}
|
||||
|
||||
// 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).
|
||||
AddDashesAndList(relpath).
|
||||
WithDir(repo.Path).
|
||||
RunStdBytes(repo.Ctx)
|
||||
RunStdBytes(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
}
|
||||
|
||||
commits, err := repo.parsePrettyFormatLogToList(stdout)
|
||||
commits, err := repo.parsePrettyFormatLogToList(ctx, stdout)
|
||||
if err != nil {
|
||||
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
|
||||
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").
|
||||
AddOptionFormat("--skip=%d", (page-1)*pageSize).
|
||||
AddOptionFormat("--max-count=%d", pageSize).
|
||||
@@ -105,15 +106,15 @@ func (repo *Repository) commitsByRangeWithTime(id ObjectID, page, pageSize int,
|
||||
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 {
|
||||
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
|
||||
addCommonSearchArgs := func(c *gitcmd.Command) {
|
||||
// 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
|
||||
addCommonSearchArgs(cmd)
|
||||
stdout, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx)
|
||||
stdout, _, err := cmd.WithDir(repo.Path).RunStdBytes(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -180,7 +181,7 @@ func (repo *Repository) searchCommits(id ObjectID, opts SearchCommitsOptions) ([
|
||||
hashCmd.AddDynamicArguments(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) {
|
||||
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
|
||||
// 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").
|
||||
AddDynamicArguments(id1, id2).
|
||||
AddDashesAndList(filename).
|
||||
WithDir(repo.Path).
|
||||
RunStdBytes(repo.Ctx)
|
||||
RunStdBytes(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -219,7 +220,7 @@ type CommitsByFileAndRangeOptions struct {
|
||||
}
|
||||
|
||||
// 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
|
||||
gitCmd := gitcmd.NewCommand("--no-pager", "log").
|
||||
AddArguments("--pretty=tformat:%H").
|
||||
@@ -244,7 +245,7 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
|
||||
defer stdoutReaderClose()
|
||||
err := gitCmd.WithDir(repo.Path).
|
||||
WithPipelineFunc(func(context gitcmd.Context) error {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -263,14 +264,14 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
commit, err := repo.getCommit(objectID)
|
||||
commit, err := repo.getCommit(ctx, objectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
commits = append(commits, commit)
|
||||
}
|
||||
}).
|
||||
RunWithStderr(repo.Ctx)
|
||||
RunWithStderr(ctx)
|
||||
|
||||
hasMore = len(commits) > limit
|
||||
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.
|
||||
// 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 {
|
||||
cmd := gitcmd.NewCommand("rev-list").WithDir(repo.Path)
|
||||
if limit >= 0 {
|
||||
@@ -295,42 +296,42 @@ func (repo *Repository) CommitsBetween(afterRef, beforeRef RefName, limit int, o
|
||||
var stdout []byte
|
||||
var err error
|
||||
if beforeRef == "" {
|
||||
stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(repo.Ctx)
|
||||
stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(ctx)
|
||||
} 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) {
|
||||
// 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
|
||||
stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(repo.Ctx)
|
||||
stdout, _, err = gitCmd().AddDynamicArguments(afterRef.String()).RunStdBytes(ctx)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
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.
|
||||
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)
|
||||
if limit > 0 {
|
||||
cmd.AddOptionFormat("-%d", limit)
|
||||
}
|
||||
cmd.AddDynamicArguments(id.String())
|
||||
|
||||
stdout, _, runErr := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx)
|
||||
stdout, _, runErr := cmd.WithDir(repo.Path).RunStdBytes(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
}
|
||||
|
||||
formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
|
||||
formattedLog, err := repo.parsePrettyFormatLogToList(ctx, bytes.TrimSpace(stdout))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commits := make([]*Commit, 0, len(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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -345,22 +346,22 @@ func (repo *Repository) commitsBefore(id ObjectID, limit int) ([]*Commit, error)
|
||||
return commits, nil
|
||||
}
|
||||
|
||||
func (repo *Repository) getCommitsBefore(id ObjectID) ([]*Commit, error) {
|
||||
return repo.commitsBefore(id, 0)
|
||||
func (repo *Repository) getCommitsBefore(ctx context.Context, id ObjectID) ([]*Commit, error) {
|
||||
return repo.commitsBefore(ctx, id, 0)
|
||||
}
|
||||
|
||||
func (repo *Repository) getCommitsBeforeLimit(id ObjectID, num int) ([]*Commit, error) {
|
||||
return repo.commitsBefore(id, num)
|
||||
func (repo *Repository) getCommitsBeforeLimit(ctx context.Context, id ObjectID, num int) ([]*Commit, error) {
|
||||
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)").
|
||||
AddOptionFormat("--count=%d", limit).
|
||||
AddOptionValues("--contains", commitID).
|
||||
AddArguments(BranchPrefix).
|
||||
WithEnv(env).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -368,11 +369,11 @@ func (repo *Repository) getBranches(env []string, commitID string, limit int) ([
|
||||
}
|
||||
|
||||
// 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))
|
||||
|
||||
for _, commitID := range commitIDs {
|
||||
commit, err := repo.GetCommit(commitID)
|
||||
commit, err := repo.GetCommit(ctx, commitID)
|
||||
if err == nil && commit != nil {
|
||||
commits = append(commits, commit)
|
||||
}
|
||||
@@ -382,11 +383,11 @@ func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit {
|
||||
}
|
||||
|
||||
// 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").
|
||||
AddDynamicArguments(commitID, branch).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
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
|
||||
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.AddDynamicArguments(endCommitID)
|
||||
|
||||
stdout, _, runErr := cmd.WithDir(repo.Path).
|
||||
WithEnv(env).
|
||||
RunStdBytes(repo.Ctx)
|
||||
RunStdBytes(ctx)
|
||||
if runErr != nil {
|
||||
return "", runErr
|
||||
}
|
||||
@@ -411,7 +412,7 @@ func (repo *Repository) GetCommitBranchStart(env []string, branch, endCommitID s
|
||||
// and we think this commit is the divergence point
|
||||
for part := range parts {
|
||||
commitID := string(part)
|
||||
branches, err := repo.getBranches(env, commitID, 2)
|
||||
branches, err := repo.getBranches(ctx, env, commitID, 2)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
@@ -17,7 +18,7 @@ import (
|
||||
)
|
||||
|
||||
// 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) {
|
||||
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
|
||||
func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) ConvertToGitID(ctx context.Context, commitID string) (ObjectID, error) {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -57,7 +58,7 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
|
||||
actualCommitID, _, err := gitcmd.NewCommand("rev-parse", "--verify").
|
||||
AddDynamicArguments(commitID).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
actualCommitID = strings.TrimSpace(actualCommitID)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "unknown revision or path") ||
|
||||
@@ -70,7 +71,7 @@ func (repo *Repository) ConvertToGitID(commitID string) (ObjectID, error) {
|
||||
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
|
||||
|
||||
commitID := plumbing.Hash(id.RawValue())
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
@@ -15,11 +16,11 @@ import (
|
||||
)
|
||||
|
||||
// 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").
|
||||
AddDynamicArguments(name).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "not a valid ref") {
|
||||
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).
|
||||
func (repo *Repository) GetRefCommitID(name string) (string, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
func (repo *Repository) GetRefCommitID(ctx context.Context, name string) (string, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -50,8 +51,8 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) {
|
||||
return info.ID, nil
|
||||
}
|
||||
|
||||
func (repo *Repository) getCommit(id ObjectID) (*Commit, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
func (repo *Repository) getCommit(ctx context.Context, id ObjectID) (*Commit, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
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
|
||||
func (repo *Repository) ConvertToGitID(ref string) (ObjectID, error) {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) ConvertToGitID(ctx context.Context, ref string) (ObjectID, error) {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
func TestRepository_GetCommitBranches(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
@@ -35,9 +35,9 @@ func TestRepository_GetCommitBranches(t *testing.T) {
|
||||
{"master", []string{"master"}},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
commit, err := bareRepo1.GetCommit(testCase.CommitID)
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), testCase.CommitID)
|
||||
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.Equal(t, testCase.ExpectedBranches, branches)
|
||||
}
|
||||
@@ -45,12 +45,12 @@ func TestRepository_GetCommitBranches(t *testing.T) {
|
||||
|
||||
func TestGetTagCommitWithSignature(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
// 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.NotNil(t, commit)
|
||||
assert.NotNil(t, commit.Signature)
|
||||
@@ -60,11 +60,11 @@ func TestGetTagCommitWithSignature(t *testing.T) {
|
||||
|
||||
func TestGetCommitWithBadCommitID(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
commit, err := bareRepo1.GetCommit("bad_branch")
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), "bad_branch")
|
||||
assert.Nil(t, commit)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, IsErrNotExist(err))
|
||||
@@ -72,22 +72,22 @@ func TestGetCommitWithBadCommitID(t *testing.T) {
|
||||
|
||||
func TestIsCommitInBranch(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
result, err := bareRepo1.IsCommitInBranch("2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1")
|
||||
result, err := bareRepo1.IsCommitInBranch(t.Context(), "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1")
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, result)
|
||||
|
||||
result, err = bareRepo1.IsCommitInBranch("2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2")
|
||||
result, err = bareRepo1.IsCommitInBranch(t.Context(), "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, result)
|
||||
}
|
||||
|
||||
func TestRepository_CommitsBetween(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo4_commitsbetween")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
@@ -101,7 +101,7 @@ func TestRepository_CommitsBetween(t *testing.T) {
|
||||
{"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, // com2 -> com2_new
|
||||
}
|
||||
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.Len(t, commits, c.ExpectedCommits, "case %d", i)
|
||||
}
|
||||
@@ -109,7 +109,7 @@ func TestRepository_CommitsBetween(t *testing.T) {
|
||||
|
||||
func TestGetRefCommitID(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
@@ -125,7 +125,7 @@ func TestGetRefCommitID(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
commitID, err := bareRepo1.GetRefCommitID(testCase.Ref)
|
||||
commitID, err := bareRepo1.GetRefCommitID(t.Context(), testCase.Ref)
|
||||
if assert.NoError(t, err) {
|
||||
assert.Equal(t, testCase.ExpectedCommitID, commitID)
|
||||
}
|
||||
@@ -136,17 +136,17 @@ func TestCommitsByFileAndRange(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Git.CommitsRangeSize, 2)()
|
||||
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
require.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
// "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)
|
||||
assert.True(t, hasMore)
|
||||
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)
|
||||
assert.Len(t, commits, 1)
|
||||
assert.False(t, hasMore)
|
||||
@@ -179,14 +179,14 @@ M 100644 :1 b.txt
|
||||
`))).RunStdString(t.Context())
|
||||
require.NoError(t, runErr)
|
||||
|
||||
repoFollowRename, err := OpenRepository(t.Context(), repoFollowRenameDir)
|
||||
repoFollowRename, err := OpenRepository(repoFollowRenameDir)
|
||||
require.NoError(t, err)
|
||||
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)
|
||||
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)
|
||||
assert.Len(t, commits, 2)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ package git
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -31,7 +32,7 @@ func (l *lineCountWriter) Write(p []byte) (n int, err error) {
|
||||
|
||||
// GetDiffNumChangedFiles counts the number of changed files
|
||||
// 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
|
||||
w := &lineCountWriter{}
|
||||
|
||||
@@ -45,7 +46,7 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
|
||||
AddArguments("--").
|
||||
WithDir(repo.Path).
|
||||
WithStdoutCopy(w).
|
||||
RunWithStderr(repo.Ctx); err != nil {
|
||||
RunWithStderr(ctx); err != nil {
|
||||
if gitcmd.IsStderr(err, gitcmd.StderrNoMergeBase) {
|
||||
// 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
|
||||
@@ -59,35 +60,35 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
|
||||
var patchCommits = regexp.MustCompile(`^From\s(\w+)\s`)
|
||||
|
||||
// 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).
|
||||
WithDir(repo.Path).
|
||||
WithStdoutCopy(w).
|
||||
Run(repo.Ctx)
|
||||
Run(ctx)
|
||||
}
|
||||
|
||||
// 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").
|
||||
AddDynamicArguments(compareArg).
|
||||
WithDir(repo.Path).
|
||||
WithStdoutCopy(w).
|
||||
Run(repo.Ctx)
|
||||
Run(ctx)
|
||||
}
|
||||
|
||||
// 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).
|
||||
WithDir(repo.Path).
|
||||
WithStdoutCopy(w).
|
||||
Run(repo.Ctx)
|
||||
Run(ctx)
|
||||
}
|
||||
|
||||
// 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 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) {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) GetFilesChangedBetween(ctx context.Context, base, head string) ([]string, error) {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -97,7 +98,7 @@ func (repo *Repository) GetFilesChangedBetween(base, head string) ([]string, err
|
||||
} else {
|
||||
cmd.AddDynamicArguments(base, head)
|
||||
}
|
||||
stdout, _, err := cmd.WithDir(repo.Path).RunStdString(repo.Ctx)
|
||||
stdout, _, err := cmd.WithDir(repo.Path).RunStdString(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestGetFormatPatch(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
repo, err := OpenRepository(t.Context(), clonedPath)
|
||||
repo, err := OpenRepository(clonedPath)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -30,7 +30,7 @@ func TestGetFormatPatch(t *testing.T) {
|
||||
defer repo.Close()
|
||||
|
||||
rd := &bytes.Buffer{}
|
||||
err = repo.GetPatch("8d92fc95^...8d92fc95", rd)
|
||||
err = repo.GetPatch(t.Context(), "8d92fc95^...8d92fc95", rd)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -50,7 +50,7 @@ func TestGetFormatPatch(t *testing.T) {
|
||||
func TestReadPatch(t *testing.T) {
|
||||
// Ensure we can read the patch files
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
repo, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -88,7 +88,7 @@ func TestReadWritePullHead(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
repo, err := OpenRepository(t.Context(), clonedPath)
|
||||
repo, err := OpenRepository(clonedPath)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -96,7 +96,7 @@ func TestReadWritePullHead(t *testing.T) {
|
||||
defer repo.Close()
|
||||
|
||||
// Try to open non-existing Pull
|
||||
_, err = repo.GetRefCommitID(PullPrefix + "0/head")
|
||||
_, err = repo.GetRefCommitID(t.Context(), PullPrefix+"0/head")
|
||||
assert.Error(t, err)
|
||||
|
||||
// Write a fake sha1 with only 40 zeros
|
||||
@@ -111,7 +111,7 @@ func TestReadWritePullHead(t *testing.T) {
|
||||
}
|
||||
|
||||
// Read the file created
|
||||
headContents, err := repo.GetRefCommitID(PullPrefix + "1/head")
|
||||
headContents, err := repo.GetRefCommitID(t.Context(), PullPrefix+"1/head")
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -130,11 +130,11 @@ func TestReadWritePullHead(t *testing.T) {
|
||||
|
||||
func TestGetCommitFilesChanged(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
repo, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
repo, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
objectFormat, err := repo.GetObjectFormat(t.Context())
|
||||
assert.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
@@ -164,7 +164,7 @@ func TestGetCommitFilesChanged(t *testing.T) {
|
||||
}
|
||||
|
||||
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.ElementsMatch(t, tc.files, changedFiles)
|
||||
}
|
||||
|
||||
@@ -15,14 +15,14 @@ import (
|
||||
)
|
||||
|
||||
// ReadTreeToIndex reads a treeish to the index
|
||||
func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) ReadTreeToIndex(ctx context.Context, treeish string, indexFilename ...string) error {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
@@ -34,15 +34,15 @@ func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string)
|
||||
if err != nil {
|
||||
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
|
||||
if len(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 {
|
||||
return err
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func (repo *Repository) readTreeToIndex(id ObjectID, indexFilename ...string) er
|
||||
}
|
||||
|
||||
// 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() {
|
||||
// if error happens and there is a cancel function, do clean up
|
||||
if err != nil && cancel != nil {
|
||||
@@ -66,7 +66,7 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilena
|
||||
|
||||
tmpIndexFilename = filepath.Join(tmpDir, ".tmp-index")
|
||||
|
||||
err = repo.ReadTreeToIndex(treeish, tmpIndexFilename)
|
||||
err = repo.ReadTreeToIndex(ctx, treeish, tmpIndexFilename)
|
||||
if err != nil {
|
||||
return "", "", cancel, err
|
||||
}
|
||||
@@ -74,15 +74,15 @@ func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilena
|
||||
}
|
||||
|
||||
// EmptyIndex empties the index
|
||||
func (repo *Repository) EmptyIndex() error {
|
||||
_, _, err := gitcmd.NewCommand("read-tree", "--empty").WithDir(repo.Path).RunStdString(repo.Ctx)
|
||||
func (repo *Repository) EmptyIndex(ctx context.Context) error {
|
||||
_, _, err := gitcmd.NewCommand("read-tree", "--empty").WithDir(repo.Path).RunStdString(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// 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...)
|
||||
res, _, err := cmd.WithDir(repo.Path).RunStdBytes(repo.Ctx)
|
||||
res, _, err := cmd.WithDir(repo.Path).RunStdBytes(ctx)
|
||||
if err != nil {
|
||||
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.
|
||||
func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) RemoveFilesFromIndex(ctx context.Context, filenames ...string) error {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -111,7 +111,7 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error {
|
||||
return cmd.
|
||||
WithDir(repo.Path).
|
||||
WithStdinBytes(input.Bytes()).
|
||||
RunWithStderr(repo.Ctx)
|
||||
RunWithStderr(ctx)
|
||||
}
|
||||
|
||||
type IndexObjectInfo struct {
|
||||
@@ -121,7 +121,7 @@ type IndexObjectInfo struct {
|
||||
}
|
||||
|
||||
// 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")
|
||||
input := new(bytes.Buffer)
|
||||
for _, object := range objects {
|
||||
@@ -131,17 +131,17 @@ func (repo *Repository) AddObjectsToIndex(objects ...IndexObjectInfo) error {
|
||||
return cmd.
|
||||
WithDir(repo.Path).
|
||||
WithStdinBytes(input.Bytes()).
|
||||
RunWithStderr(repo.Ctx)
|
||||
RunWithStderr(ctx)
|
||||
}
|
||||
|
||||
// AddObjectToIndex adds the provided object hash to the index at the provided filename
|
||||
func (repo *Repository) AddObjectToIndex(mode string, object ObjectID, filename string) error {
|
||||
return repo.AddObjectsToIndex(IndexObjectInfo{Mode: mode, Object: object, Filename: filename})
|
||||
func (repo *Repository) AddObjectToIndex(ctx context.Context, mode string, object ObjectID, filename string) error {
|
||||
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
|
||||
func (repo *Repository) WriteTree() (*Tree, error) {
|
||||
stdout, _, runErr := gitcmd.NewCommand("write-tree").WithDir(repo.Path).RunStdString(repo.Ctx)
|
||||
func (repo *Repository) WriteTree(ctx context.Context) (*Tree, error) {
|
||||
stdout, _, runErr := gitcmd.NewCommand("write-tree").WithDir(repo.Path).RunStdString(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
@@ -31,12 +32,12 @@ func (o ObjectType) Bytes() []byte {
|
||||
return []byte(o)
|
||||
}
|
||||
|
||||
func (repo *Repository) GetObjectFormat() (ObjectFormat, error) {
|
||||
if repo != nil && repo.objectFormat != nil {
|
||||
return repo.objectFormat, nil
|
||||
func (repo *Repository) GetObjectFormat(ctx context.Context) (ObjectFormat, error) {
|
||||
if repo.objectFormatCache != nil {
|
||||
return repo.objectFormatCache, nil
|
||||
}
|
||||
|
||||
str, err := repo.hashObjectBytes(nil, false)
|
||||
str, err := repo.hashObjectBytes(ctx, nil, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -45,21 +46,21 @@ func (repo *Repository) GetObjectFormat() (ObjectFormat, error) {
|
||||
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
|
||||
func (repo *Repository) HashObjectBytes(buf []byte) (ObjectID, error) {
|
||||
idStr, err := repo.hashObjectBytes(buf, true)
|
||||
func (repo *Repository) HashObjectBytes(ctx context.Context, buf []byte) (ObjectID, error) {
|
||||
idStr, err := repo.hashObjectBytes(ctx, buf, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
if save {
|
||||
cmd = gitcmd.NewCommand("hash-object", "-w", "--stdin")
|
||||
@@ -69,7 +70,7 @@ func (repo *Repository) hashObjectBytes(buf []byte, save bool) (string, error) {
|
||||
stdout, _, err := cmd.
|
||||
WithDir(repo.Path).
|
||||
WithStdinBytes(buf).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
)
|
||||
|
||||
// GetRefs returns all references of the repository.
|
||||
func (repo *Repository) GetRefs() ([]*Reference, error) {
|
||||
return repo.GetRefsFiltered("")
|
||||
func (repo *Repository) GetRefs(ctx context.Context) ([]*Reference, error) {
|
||||
return repo.GetRefsFiltered(ctx, "")
|
||||
}
|
||||
|
||||
// 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"
|
||||
// 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.
|
||||
func (repo *Repository) UnstableGuessRefByShortName(shortName string) RefName {
|
||||
if repo.IsBranchExist(shortName) {
|
||||
func (repo *Repository) UnstableGuessRefByShortName(ctx context.Context, shortName string) RefName {
|
||||
if repo.IsBranchExist(ctx, shortName) {
|
||||
return RefNameFromBranch(shortName)
|
||||
}
|
||||
if repo.IsTagExist(shortName) {
|
||||
if repo.IsTagExist(ctx, shortName) {
|
||||
return RefNameFromTag(shortName)
|
||||
}
|
||||
if strings.HasPrefix(shortName, "refs/") {
|
||||
if repo.IsReferenceExist(shortName) {
|
||||
if repo.IsReferenceExist(ctx, shortName) {
|
||||
return RefName(shortName)
|
||||
}
|
||||
}
|
||||
commit, err := repo.GetCommit(shortName)
|
||||
commit, err := repo.GetCommit(ctx, shortName)
|
||||
if err == nil {
|
||||
commitIDString := commit.ID.String()
|
||||
// make sure the "shortName" is either partial commit ID, or it is HEAD
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"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.
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -30,7 +31,7 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
|
||||
refType := string(ObjectCommit)
|
||||
if ref.Name().IsTag() {
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ package git
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
@@ -14,7 +15,7 @@ import (
|
||||
)
|
||||
|
||||
// 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)
|
||||
cmd := gitcmd.NewCommand("for-each-ref")
|
||||
stdoutReader, stdoutReaderClose := cmd.MakeStdoutPipe()
|
||||
@@ -70,6 +71,6 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}).RunWithStderr(repo.Ctx)
|
||||
}).RunWithStderr(ctx)
|
||||
return refs, err
|
||||
}
|
||||
|
||||
@@ -12,11 +12,11 @@ import (
|
||||
|
||||
func TestRepository_GetRefs(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
refs, err := bareRepo1.GetRefs()
|
||||
refs, err := bareRepo1.GetRefs(t.Context())
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, refs, 6)
|
||||
@@ -37,11 +37,11 @@ func TestRepository_GetRefs(t *testing.T) {
|
||||
|
||||
func TestRepository_GetRefsFiltered(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
refs, err := bareRepo1.GetRefsFiltered(TagPrefix)
|
||||
refs, err := bareRepo1.GetRefsFiltered(t.Context(), TagPrefix)
|
||||
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, refs, 2) {
|
||||
|
||||
@@ -5,6 +5,7 @@ package git
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -34,7 +35,7 @@ type CodeActivityAuthor struct {
|
||||
}
|
||||
|
||||
// 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{}
|
||||
|
||||
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").
|
||||
AddOptionFormat("--since=%s", since).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
}
|
||||
@@ -131,7 +132,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
|
||||
stats.Authors = a
|
||||
return nil
|
||||
}).
|
||||
RunWithStderr(repo.Ctx)
|
||||
RunWithStderr(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetCodeActivityStats: %w", err)
|
||||
}
|
||||
|
||||
@@ -13,14 +13,14 @@ import (
|
||||
|
||||
func TestRepository_GetCodeActivityStats(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
timeFrom, err := time.Parse(time.RFC3339, "2016-01-01T00:00:00+00:00")
|
||||
assert.NoError(t, err)
|
||||
|
||||
code, err := bareRepo1.GetCodeActivityStats(timeFrom, "")
|
||||
code, err := bareRepo1.GetCodeActivityStats(t.Context(), timeFrom, "")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, code)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -17,28 +18,28 @@ import (
|
||||
const TagPrefix = "refs/tags/"
|
||||
|
||||
// CreateTag create one tag in the repository
|
||||
func (repo *Repository) CreateTag(name, revision string) error {
|
||||
_, _, err := gitcmd.NewCommand("tag").AddDashesAndList(name, revision).WithDir(repo.Path).RunStdString(repo.Ctx)
|
||||
func (repo *Repository) CreateTag(ctx context.Context, name, revision string) error {
|
||||
_, _, err := gitcmd.NewCommand("tag").AddDashesAndList(name, revision).WithDir(repo.Path).RunStdString(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// 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").
|
||||
AddDynamicArguments(message).
|
||||
AddDashesAndList(name, revision).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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 {
|
||||
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)
|
||||
func (repo *Repository) GetTagID(name string) (string, error) {
|
||||
stdout, _, err := gitcmd.NewCommand("show-ref", "--tags").AddDashesAndList(name).WithDir(repo.Path).RunStdString(repo.Ctx)
|
||||
func (repo *Repository) GetTagID(ctx context.Context, name string) (string, error) {
|
||||
stdout, _, err := gitcmd.NewCommand("show-ref", "--tags").AddDashesAndList(name).WithDir(repo.Path).RunStdString(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -76,8 +77,8 @@ func (repo *Repository) GetTagID(name string) (string, error) {
|
||||
}
|
||||
|
||||
// GetTag returns a Git tag by given name.
|
||||
func (repo *Repository) GetTag(name string) (*Tag, error) {
|
||||
idStr, err := repo.GetTagID(name)
|
||||
func (repo *Repository) GetTag(ctx context.Context, name string) (*Tag, error) {
|
||||
idStr, err := repo.GetTagID(ctx, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -87,7 +88,7 @@ func (repo *Repository) GetTag(name string) (*Tag, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tag, err := repo.getTag(id, name)
|
||||
tag, err := repo.getTag(ctx, id, name)
|
||||
if err != nil {
|
||||
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
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tag, err := repo.getTag(id, name)
|
||||
tag, err := repo.getTag(ctx, id, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -109,7 +110,7 @@ func (repo *Repository) GetTagWithID(idStr, name string) (*Tag, error) {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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")
|
||||
@@ -147,7 +148,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) {
|
||||
}
|
||||
return nil
|
||||
}).
|
||||
RunWithStderr(repo.Ctx)
|
||||
RunWithStderr(ctx)
|
||||
|
||||
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
|
||||
func (repo *Repository) GetAnnotatedTag(sha string) (*Tag, error) {
|
||||
func (repo *Repository) GetAnnotatedTag(ctx context.Context, sha string) (*Tag, error) {
|
||||
id, err := NewIDFromString(sha)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 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
|
||||
} else if ObjectType(tagType) != ObjectTag {
|
||||
// not an annotated tag
|
||||
@@ -209,12 +210,12 @@ func (repo *Repository) GetAnnotatedTag(sha string) (*Tag, error) {
|
||||
}
|
||||
|
||||
// Get tag name
|
||||
name, err := repo.GetTagNameBySHA(id.String())
|
||||
name, err := repo.GetTagNameBySHA(ctx, id.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tag, err := repo.getTag(id, name)
|
||||
tag, err := repo.getTag(ctx, id, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -7,19 +7,21 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.dev/modules/log"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing"
|
||||
)
|
||||
|
||||
// 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)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// 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
|
||||
obj, err := repo.gogitRepo.Object(plumbing.AnyObject, plumbing.Hash(id.RawValue()))
|
||||
if err != nil {
|
||||
@@ -32,7 +34,7 @@ func (repo *Repository) GetTagType(id ObjectID) (string, error) {
|
||||
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())
|
||||
if ok {
|
||||
log.Debug("Hit cache: %s", tagID)
|
||||
@@ -41,13 +43,13 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
|
||||
return &tagClone, nil
|
||||
}
|
||||
|
||||
tp, err := repo.GetTagType(tagID)
|
||||
tp, err := repo.GetTagType(ctx, tagID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// every tag should have a commit ID so return all errors
|
||||
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 ObjectType(tp) == ObjectCommit {
|
||||
commit, err := repo.GetCommit(commitIDStr)
|
||||
commit, err := repo.GetCommit(ctx, commitIDStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
@@ -14,17 +15,17 @@ import (
|
||||
)
|
||||
|
||||
// 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 == "" {
|
||||
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)
|
||||
func (repo *Repository) GetTagType(id ObjectID) (string, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
func (repo *Repository) GetTagType(ctx context.Context, id ObjectID) (string, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -39,7 +40,7 @@ func (repo *Repository) GetTagType(id ObjectID) (string, error) {
|
||||
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())
|
||||
if ok {
|
||||
log.Debug("Hit cache: %s", tagID)
|
||||
@@ -48,13 +49,13 @@ func (repo *Repository) getTag(tagID ObjectID, name string) (*Tag, error) {
|
||||
return &tagClone, nil
|
||||
}
|
||||
|
||||
tp, err := repo.GetTagType(tagID)
|
||||
tp, err := repo.GetTagType(ctx, tagID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// every tag should have a commit ID so return all errors
|
||||
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 ObjectType(tp) == ObjectCommit {
|
||||
commit, err := repo.GetCommit(commitIDStr)
|
||||
commit, err := repo.GetCommit(ctx, commitIDStr)
|
||||
if err != nil {
|
||||
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.
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -13,14 +13,14 @@ import (
|
||||
|
||||
func TestRepository_GetTagInfos(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
|
||||
bareRepo1, err := OpenRepository(bareRepo1Path)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
}
|
||||
defer bareRepo1.Close()
|
||||
|
||||
tags, total, err := bareRepo1.GetTagInfos(0, 0)
|
||||
tags, total, err := bareRepo1.GetTagInfos(t.Context(), 0, 0)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -44,7 +44,7 @@ func TestRepository_GetTag(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
bareRepo1, err := OpenRepository(t.Context(), clonedPath)
|
||||
bareRepo1, err := OpenRepository(clonedPath)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -56,14 +56,14 @@ func TestRepository_GetTag(t *testing.T) {
|
||||
lTagName := "lightweightTag"
|
||||
|
||||
// Create the lightweight tag
|
||||
err = bareRepo1.CreateTag(lTagName, lTagCommitID)
|
||||
err = bareRepo1.CreateTag(t.Context(), lTagName, lTagCommitID)
|
||||
if err != nil {
|
||||
assert.NoError(t, err, "Unable to create the lightweight tag: %s for ID: %s. Error: %v", lTagName, lTagCommitID, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 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.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"
|
||||
|
||||
// Create the annotated tag
|
||||
err = bareRepo1.CreateAnnotatedTag(aTagName, aTagMessage, aTagCommitID)
|
||||
err = bareRepo1.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, aTagCommitID)
|
||||
if err != nil {
|
||||
assert.NoError(t, err, "Unable to create the annotated tag: %s for ID: %s. Error: %v", aTagName, aTagCommitID, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 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 {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
aTag, err := bareRepo1.GetTag(aTagName)
|
||||
aTag, err := bareRepo1.GetTag(t.Context(), aTagName)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, aTag, "nil aTag: %s", aTagName)
|
||||
|
||||
@@ -106,20 +106,20 @@ func TestRepository_GetTag(t *testing.T) {
|
||||
rTagCommitID := "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"
|
||||
rTagName := "release/" + lTagName
|
||||
|
||||
err = bareRepo1.CreateTag(rTagName, rTagCommitID)
|
||||
err = bareRepo1.CreateTag(t.Context(), rTagName, rTagCommitID)
|
||||
if err != nil {
|
||||
assert.NoError(t, err, "Unable to create the tag: %s for ID: %s. Error: %v", rTagName, rTagCommitID, err)
|
||||
return
|
||||
}
|
||||
|
||||
rTagID, err := bareRepo1.GetTagID(rTagName)
|
||||
rTagID, err := bareRepo1.GetTagID(t.Context(), rTagName)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
}
|
||||
assert.Equal(t, rTagCommitID, rTagID)
|
||||
|
||||
oTagID, err := bareRepo1.GetTagID(lTagName)
|
||||
oTagID, err := bareRepo1.GetTagID(t.Context(), lTagName)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -136,7 +136,7 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
bareRepo1, err := OpenRepository(t.Context(), clonedPath)
|
||||
bareRepo1, err := OpenRepository(clonedPath)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -145,16 +145,16 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
|
||||
|
||||
lTagCommitID := "6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1"
|
||||
lTagName := "lightweightTag"
|
||||
bareRepo1.CreateTag(lTagName, lTagCommitID)
|
||||
bareRepo1.CreateTag(t.Context(), lTagName, lTagCommitID)
|
||||
|
||||
aTagCommitID := "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"
|
||||
aTagName := "annotatedTag"
|
||||
aTagMessage := "my annotated message"
|
||||
bareRepo1.CreateAnnotatedTag(aTagName, aTagMessage, aTagCommitID)
|
||||
aTagID, _ := bareRepo1.GetTagID(aTagName)
|
||||
bareRepo1.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, aTagCommitID)
|
||||
aTagID, _ := bareRepo1.GetTagID(t.Context(), aTagName)
|
||||
|
||||
// Try an annotated tag
|
||||
tag, err := bareRepo1.GetAnnotatedTag(aTagID)
|
||||
tag, err := bareRepo1.GetAnnotatedTag(t.Context(), aTagID)
|
||||
if err != nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
@@ -165,18 +165,18 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
|
||||
assert.Equal(t, "tag", tag.Type)
|
||||
|
||||
// Annotated tag's Commit ID should fail
|
||||
tag2, err := bareRepo1.GetAnnotatedTag(aTagCommitID)
|
||||
tag2, err := bareRepo1.GetAnnotatedTag(t.Context(), aTagCommitID)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, IsErrNotExist(err))
|
||||
assert.Nil(t, tag2)
|
||||
|
||||
// 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.Nil(t, tag3)
|
||||
|
||||
// Lightweight Tag should fail
|
||||
tag4, err := bareRepo1.GetAnnotatedTag(lTagCommitID)
|
||||
tag4, err := bareRepo1.GetAnnotatedTag(t.Context(), lTagCommitID)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, IsErrNotExist(err))
|
||||
assert.Nil(t, tag4)
|
||||
|
||||
@@ -15,10 +15,10 @@ import (
|
||||
|
||||
func TestRepoIsEmpty(t *testing.T) {
|
||||
emptyRepo2Path := filepath.Join(testReposDir, "repo2_empty")
|
||||
repo, err := OpenRepository(t.Context(), emptyRepo2Path)
|
||||
repo, err := OpenRepository(emptyRepo2Path)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
isEmpty, err := repo.IsEmpty()
|
||||
isEmpty, err := repo.IsEmpty(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, isEmpty)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ package git
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -23,7 +24,7 @@ type CommitTreeOpts struct {
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// 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).
|
||||
WithDir(repo.Path).
|
||||
WithStdinBytes(messageBytes.Bytes()).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
@@ -14,7 +15,7 @@ import (
|
||||
"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()))
|
||||
if err != nil {
|
||||
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.
|
||||
func (repo *Repository) GetTree(idStr string) (*Tree, error) {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) GetTree(ctx context.Context, idStr string) (*Tree, error) {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -41,7 +42,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
|
||||
res, _, err := gitcmd.NewCommand("rev-parse", "--verify").
|
||||
AddDynamicArguments(idStr).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -57,7 +58,7 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
|
||||
if err == nil {
|
||||
id = ParseGogitHash(commitObject.TreeHash)
|
||||
}
|
||||
treeObject, err := repo.getTree(id)
|
||||
treeObject, err := repo.getTree(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
)
|
||||
|
||||
func (repo *Repository) getTree(id ObjectID) (*Tree, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(repo.Ctx)
|
||||
func (repo *Repository) getTree(ctx context.Context, id ObjectID) (*Tree, error) {
|
||||
batch, cancel, err := repo.CatFileBatch(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -50,7 +51,7 @@ func (repo *Repository) getTree(id ObjectID) (*Tree, error) {
|
||||
return tree, nil
|
||||
case "tree":
|
||||
tree := newTree(id)
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,13 +72,13 @@ func (repo *Repository) getTree(id ObjectID) (*Tree, error) {
|
||||
}
|
||||
|
||||
// GetTree find the tree object in the repository.
|
||||
func (repo *Repository) GetTree(idStr string) (*Tree, error) {
|
||||
objectFormat, err := repo.GetObjectFormat()
|
||||
func (repo *Repository) GetTree(ctx context.Context, idStr string) (*Tree, error) {
|
||||
objectFormat, err := repo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(idStr) != objectFormat.FullLength() {
|
||||
res, err := repo.GetRefCommitID(idStr)
|
||||
res, err := repo.GetRefCommitID(ctx, idStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -90,5 +91,5 @@ func (repo *Repository) GetTree(idStr string) (*Tree, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return repo.getTree(id)
|
||||
return repo.getTree(ctx, id)
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func (t *Tree) SubTree(ctx context.Context, gitRepo *Repository, rpath string) (
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g, err = gitRepo.getTree(te.ID)
|
||||
g, err = gitRepo.getTree(ctx, te.ID)
|
||||
if err != nil {
|
||||
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
|
||||
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").
|
||||
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 {
|
||||
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
|
||||
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").
|
||||
AddDynamicArguments(refName).AddDashesAndList(treePath).
|
||||
WithDir(repo.Path).
|
||||
RunStdString(repo.Ctx)
|
||||
RunStdString(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repo.GetCommit(strings.TrimSpace(stdout))
|
||||
return repo.GetCommit(ctx, strings.TrimSpace(stdout))
|
||||
}
|
||||
|
||||
@@ -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
|
||||
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)
|
||||
}
|
||||
|
||||
link, err := te.Blob(gitRepo).GetBlobContent(maxSymlinkSize)
|
||||
link, err := te.Blob(gitRepo).GetBlobContent(ctx, maxSymlinkSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -126,8 +126,8 @@ func EntryFollowLinks(ctx context.Context, gitRepo *Repository, commit *Commit,
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (te *TreeEntry) Tree(gitRepo *Repository) *Tree {
|
||||
t, err := gitRepo.getTree(te.ID)
|
||||
func (te *TreeEntry) Tree(ctx context.Context, gitRepo *Repository) *Tree {
|
||||
t, err := gitRepo.getTree(ctx, te.ID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -13,11 +13,11 @@ import (
|
||||
)
|
||||
|
||||
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)
|
||||
defer r.Close()
|
||||
|
||||
commit, err := r.GetCommit("37991dec2c8e592043f47155ce4808d4580f9123")
|
||||
commit, err := r.GetCommit(t.Context(), "37991dec2c8e592043f47155ce4808d4580f9123")
|
||||
require.NoError(t, err)
|
||||
|
||||
// get the symlink
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
)
|
||||
|
||||
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)
|
||||
defer repo.Close()
|
||||
|
||||
commit, err := repo.GetCommit("ce064814f4a0d337b333e646ece456cd39fab612")
|
||||
commit, err := repo.GetCommit(t.Context(), "ce064814f4a0d337b333e646ece456cd39fab612")
|
||||
assert.NoError(t, err)
|
||||
|
||||
// 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) {
|
||||
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo6_blame"))
|
||||
repo, err := OpenRepository(filepath.Join(testReposDir, "repo6_blame"))
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
commitID, err := repo.GetBranchCommitID("master")
|
||||
commitID, err := repo.GetBranchCommitID(t.Context(), "master")
|
||||
assert.NoError(t, err)
|
||||
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.NotNil(t, commit)
|
||||
assert.Equal(t, "45fb6cbc12f970b04eacd5cd4165edd11c8d7376", commit.ID.String())
|
||||
|
||||
@@ -186,7 +186,7 @@ func tryCreateBlameIgnoreRevsFile(ctx context.Context, gitRepo *git.Repository,
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
r, err := entry.Blob(gitRepo).DataAsync()
|
||||
r, err := entry.Blob(gitRepo).DataAsync(ctx)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
@@ -25,11 +25,11 @@ func TestReadingBlameOutputSha256(t *testing.T) {
|
||||
|
||||
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := &mockRepository{path: "repo5_pulls_sha256"}
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
repo, err := OpenRepository(storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
commit, err := repo.GetCommit("0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345")
|
||||
commit, err := repo.GetCommit(t.Context(), "0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345")
|
||||
assert.NoError(t, err)
|
||||
|
||||
parts := []*BlamePart{
|
||||
@@ -71,7 +71,7 @@ func TestReadingBlameOutputSha256(t *testing.T) {
|
||||
|
||||
t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := &mockRepository{path: "repo6_blame_sha256"}
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
repo, err := OpenRepository(storage)
|
||||
assert.NoError(t, err)
|
||||
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)
|
||||
for _, c := range cases {
|
||||
commit, err := repo.GetCommit(c.CommitID)
|
||||
commit, err := repo.GetCommit(t.Context(), c.CommitID)
|
||||
assert.NoError(t, err)
|
||||
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
|
||||
assert.NoError(t, err)
|
||||
|
||||
@@ -20,10 +20,10 @@ func TestReadingBlameOutput(t *testing.T) {
|
||||
|
||||
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := &mockRepository{path: "repo5_pulls"}
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
repo, err := OpenRepository(storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
commit, err := repo.GetCommit("f32b0a9dfd09a60f616f29158f772cedd89942d2")
|
||||
commit, err := repo.GetCommit(t.Context(), "f32b0a9dfd09a60f616f29158f772cedd89942d2")
|
||||
assert.NoError(t, err)
|
||||
|
||||
parts := []*BlamePart{
|
||||
@@ -65,7 +65,7 @@ func TestReadingBlameOutput(t *testing.T) {
|
||||
|
||||
t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := &mockRepository{path: "repo6_blame"}
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
repo, err := OpenRepository(storage)
|
||||
assert.NoError(t, err)
|
||||
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)
|
||||
for _, c := range cases {
|
||||
commit, err := repo.GetCommit(c.CommitID)
|
||||
commit, err := repo.GetCommit(t.Context(), c.CommitID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
|
||||
|
||||
@@ -15,23 +15,23 @@ import (
|
||||
// GetBranchesByPath returns a branch by its path
|
||||
// if limit = 0 it will not limit
|
||||
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 {
|
||||
return nil, 0, err
|
||||
}
|
||||
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) {
|
||||
gitRepo, err := OpenRepository(ctx, repo)
|
||||
gitRepo, err := OpenRepository(repo)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer gitRepo.Close()
|
||||
|
||||
return gitRepo.GetBranchCommitID(branch)
|
||||
return gitRepo.GetBranchCommitID(ctx, branch)
|
||||
}
|
||||
|
||||
// SetDefaultBranch sets default branch of repository.
|
||||
|
||||
@@ -18,10 +18,7 @@ import (
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// Repository represents a git repository which stored in a disk
|
||||
type Repository interface {
|
||||
RelativePath() string // We don't assume how the directory structure of the repository is, so we only need the relative path
|
||||
}
|
||||
type Repository = git.RepositoryFacade
|
||||
|
||||
// repoPath resolves the Repository.RelativePath (which is a unix-style path like "username/reponame.git")
|
||||
// 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.
|
||||
func OpenRepository(ctx context.Context, repo Repository) (*git.Repository, error) {
|
||||
return git.OpenRepository(ctx, repoPath(repo))
|
||||
func OpenRepository(repo Repository) (*git.Repository, error) {
|
||||
return git.OpenRepository(repoPath(repo))
|
||||
}
|
||||
|
||||
// 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)
|
||||
return gitRepo, util.NopCloser{}, err
|
||||
}
|
||||
gitRepo, err := OpenRepository(ctx, repo)
|
||||
gitRepo, err := OpenRepository(repo)
|
||||
return gitRepo, gitRepo, err
|
||||
}
|
||||
|
||||
@@ -58,7 +55,7 @@ func RepositoryFromRequestContextOrOpen(ctx reqctx.RequestContext, repo Reposito
|
||||
if gitRepo, ok := ctx.Value(ck).(*git.Repository); ok {
|
||||
return gitRepo, nil
|
||||
}
|
||||
gitRepo, err := git.OpenRepository(ctx, ck.repoPath)
|
||||
gitRepo, err := git.OpenRepository(ck.repoPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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.
|
||||
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 {
|
||||
return nil, 0, fmt.Errorf("gitRepo.GetRefCommitID: %w", err)
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ func (db *DBIndexer) Index(id int64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
gitRepo, err := gitrepo.OpenRepository(ctx, repo)
|
||||
gitRepo, err := gitrepo.OpenRepository(repo)
|
||||
if err != nil {
|
||||
if err.Error() == "no such file or directory" {
|
||||
return nil
|
||||
@@ -47,7 +47,7 @@ func (db *DBIndexer) Index(id int64) error {
|
||||
defer gitRepo.Close()
|
||||
|
||||
// Get latest commit for default branch
|
||||
commitID, err := gitRepo.GetBranchCommitID(repo.DefaultBranch)
|
||||
commitID, err := gitRepo.GetBranchCommitID(ctx, repo.DefaultBranch)
|
||||
if err != nil {
|
||||
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())
|
||||
|
||||
@@ -42,8 +42,8 @@ func Unmarshal(filename string, content []byte) (*api.IssueTemplate, error) {
|
||||
}
|
||||
|
||||
// UnmarshalFromEntry parses out a valid template from the blob in entry
|
||||
func UnmarshalFromEntry(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
|
||||
func UnmarshalFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry, dir string) (*api.IssueTemplate, error) {
|
||||
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
|
||||
@@ -52,12 +52,12 @@ func UnmarshalFromCommit(ctx context.Context, gitRepo *git.Repository, commit *g
|
||||
if err != nil {
|
||||
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
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
func unmarshalFromEntry(gitRepo *git.Repository, entry *git.TreeEntry, filename string) (*api.IssueTemplate, error) {
|
||||
if size := entry.Blob(gitRepo).Size(); size > setting.UI.MaxDisplayFileSize {
|
||||
func unmarshalFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry, filename string) (*api.IssueTemplate, error) {
|
||||
if size := entry.Blob(gitRepo).Size(ctx); size > setting.UI.MaxDisplayFileSize {
|
||||
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 {
|
||||
return nil, fmt.Errorf("data async: %w", err)
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
|
||||
gitRepo, err := gitrepo.OpenRepository(ctx, repo)
|
||||
gitRepo, err := gitrepo.OpenRepository(repo)
|
||||
if err != nil {
|
||||
log.Error("OpenRepository[%s]: %w", repo.FullName(), 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) {
|
||||
objFmt, err := gitRepo.GetObjectFormat()
|
||||
objFmt, err := gitRepo.GetObjectFormat(ctx)
|
||||
if err != nil {
|
||||
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]{}
|
||||
{
|
||||
branches, _, err := gitRepo.GetBranchNames(0, 0)
|
||||
branches, _, err := gitRepo.GetBranchNames(ctx, 0, 0)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func SyncRepoBranchesWithRepo(ctx context.Context, repo *repo_model.Repository,
|
||||
var syncResults []*SyncResult
|
||||
for branch := range allBranches {
|
||||
dbb := dbBranches[branch]
|
||||
commit, err := gitRepo.GetBranchCommit(branch)
|
||||
commit, err := gitRepo.GetBranchCommit(ctx, branch)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ func SyncRepoTags(ctx context.Context, repoID int64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
gitRepo, err := gitrepo.OpenRepository(ctx, repo)
|
||||
gitRepo, err := gitrepo.OpenRepository(repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -181,7 +181,7 @@ func (shortRelease) TableName() string {
|
||||
// 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) {
|
||||
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 {
|
||||
return nil, fmt.Errorf("unable to GetTagInfos in pull-mirror Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err)
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ func GetBlob(ctx *context.APIContext) {
|
||||
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())
|
||||
} else {
|
||||
ctx.JSON(http.StatusOK, blob)
|
||||
|
||||
@@ -68,7 +68,7 @@ func GetBranch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
c, err := ctx.Repo.GitRepo.GetBranchCommit(branchName)
|
||||
c, err := ctx.Repo.GitRepo.GetBranchCommit(ctx, branchName)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
@@ -219,14 +219,14 @@ func CreateBranch(ctx *context.APIContext) {
|
||||
var err error
|
||||
|
||||
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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
} 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
|
||||
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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
@@ -236,14 +236,14 @@ func CreateBranch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
} 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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
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 git_model.IsErrBranchNotExist(err) {
|
||||
ctx.APIError(http.StatusNotFound, "The old branch does not exist")
|
||||
@@ -259,7 +259,7 @@ func CreateBranch(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
commit, err := ctx.Repo.GitRepo.GetBranchCommit(opt.BranchName)
|
||||
commit, err := ctx.Repo.GitRepo.GetBranchCommit(ctx, opt.BranchName)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
@@ -360,7 +360,7 @@ func ListBranches(ctx *context.APIContext) {
|
||||
|
||||
apiBranches = make([]*api.Branch, 0, len(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 {
|
||||
// Skip if this branch doesn't exist anymore.
|
||||
if git.IsErrNotExist(err) {
|
||||
|
||||
@@ -74,7 +74,7 @@ func GetSingleCommit(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
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 git.IsErrNotExist(err) {
|
||||
ctx.APIErrorNotFound("commit doesn't exist: " + identifier)
|
||||
@@ -208,14 +208,14 @@ func GetAllCommits(ctx *context.APIContext) {
|
||||
var baseCommit *git.Commit
|
||||
if len(sha) == 0 {
|
||||
// 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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// get commit specified by sha
|
||||
baseCommit, err = ctx.Repo.GitRepo.GetCommit(sha)
|
||||
baseCommit, err = ctx.Repo.GitRepo.GetCommit(ctx, sha)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
@@ -235,7 +235,7 @@ func GetAllCommits(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
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{
|
||||
Revision: sha,
|
||||
File: path,
|
||||
@@ -360,7 +360,7 @@ func DownloadCommitDiffOrPatch(ctx *context.APIContext) {
|
||||
sha := ctx.PathParam("sha")
|
||||
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) {
|
||||
ctx.APIErrorNotFound("commit doesn't exist: " + sha)
|
||||
return
|
||||
|
||||
@@ -120,9 +120,9 @@ func downloadCompareDiffOrPatch(ctx *context.APIContext, compareInfo *git_servic
|
||||
|
||||
var err error
|
||||
if patch {
|
||||
err = compareInfo.HeadGitRepo.GetPatch(compareArg, ctx.Resp)
|
||||
err = compareInfo.HeadGitRepo.GetPatch(ctx, compareArg, ctx.Resp)
|
||||
} else {
|
||||
err = compareInfo.HeadGitRepo.GetDiff(compareArg, ctx.Resp)
|
||||
err = compareInfo.HeadGitRepo.GetDiff(ctx, compareArg, ctx.Resp)
|
||||
}
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
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 errors.Is(err, util.ErrInvalidArgument) {
|
||||
ctx.APIError(http.StatusBadRequest, err.Error())
|
||||
|
||||
@@ -136,7 +136,7 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
|
||||
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
|
||||
if blob.Size() > lfs.MetaFileMaxSize {
|
||||
if blob.Size(ctx) > lfs.MetaFileMaxSize {
|
||||
// First handle caching for the blob
|
||||
if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
|
||||
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,
|
||||
// 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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
@@ -217,7 +217,7 @@ func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, entry *git.TreeEn
|
||||
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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
return nil, nil, nil
|
||||
|
||||
@@ -66,7 +66,7 @@ func getNote(ctx *context.APIContext, identifier string) {
|
||||
return
|
||||
}
|
||||
|
||||
commitID, err := ctx.Repo.GitRepo.ConvertToGitID(identifier)
|
||||
commitID, err := ctx.Repo.GitRepo.ConvertToGitID(ctx, identifier)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
|
||||
@@ -1107,7 +1107,7 @@ func parseCompareInfo(ctx *context.APIContext, compareParam string) (result *git
|
||||
headGitRepo = ctx.Repo.GitRepo
|
||||
closer = func() {} // no need to close the head repo because it shares the base repo
|
||||
} else {
|
||||
headGitRepo, err = gitrepo.OpenRepository(ctx, headRepo)
|
||||
headGitRepo, err = gitrepo.OpenRepository(headRepo)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return nil, nil
|
||||
@@ -1146,12 +1146,12 @@ func parseCompareInfo(ctx *context.APIContext, compareParam string) (result *git
|
||||
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 {
|
||||
ctx.APIErrorAuto(err)
|
||||
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 {
|
||||
ctx.APIErrorAuto(err)
|
||||
return nil, nil
|
||||
@@ -1570,7 +1570,7 @@ func GetPullRequestFiles(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
headCommitID, err := baseGitRepo.GetRefCommitID(pr.GetGitHeadRefName())
|
||||
headCommitID, err := baseGitRepo.GetRefCommitID(ctx, pr.GetGitHeadRefName())
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
|
||||
@@ -526,7 +526,7 @@ func CreatePullReview(ctx *context.APIContext) {
|
||||
}
|
||||
defer closer.Close()
|
||||
|
||||
headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitHeadRefName())
|
||||
headCommitID, err := gitRepo.GetRefCommitID(ctx, pr.GetGitHeadRefName())
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
@@ -645,7 +645,7 @@ func SubmitPullReview(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
headCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(pr.GetGitHeadRefName())
|
||||
headCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(ctx, pr.GetGitHeadRefName())
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
|
||||
@@ -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
|
||||
// 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) {
|
||||
ctx.APIError(http.StatusConflict, err.Error())
|
||||
} else if release_service.IsErrProtectedTagName(err) {
|
||||
|
||||
@@ -55,7 +55,7 @@ func ListTags(ctx *context.APIContext) {
|
||||
|
||||
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 {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
@@ -107,13 +107,13 @@ func GetAnnotatedTag(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
tag, err := ctx.Repo.GitRepo.GetAnnotatedTag(sha)
|
||||
tag, err := ctx.Repo.GitRepo.GetAnnotatedTag(ctx, sha)
|
||||
if err != nil {
|
||||
ctx.APIError(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
commit, err := ctx.Repo.GitRepo.GetTagCommit(tag.Name)
|
||||
commit, err := ctx.Repo.GitRepo.GetTagCommit(ctx, tag.Name)
|
||||
if err != nil {
|
||||
ctx.APIError(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
@@ -151,7 +151,7 @@ func GetTag(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/notFound"
|
||||
tagName := ctx.PathParam("*")
|
||||
|
||||
tag, err := ctx.Repo.GitRepo.GetTag(tagName)
|
||||
tag, err := ctx.Repo.GitRepo.GetTag(ctx, tagName)
|
||||
if err != nil {
|
||||
ctx.APIErrorNotFound("tag doesn't exist: " + tagName)
|
||||
return
|
||||
@@ -201,7 +201,7 @@ func CreateTag(ctx *context.APIContext) {
|
||||
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 {
|
||||
ctx.APIError(http.StatusNotFound, fmt.Sprintf("target not found: %v", err))
|
||||
return
|
||||
@@ -221,7 +221,7 @@ func CreateTag(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
tag, err := ctx.Repo.GitRepo.GetTag(form.TagName)
|
||||
tag, err := ctx.Repo.GitRepo.GetTag(ctx, form.TagName)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user