mirror of
https://github.com/go-gitea/gitea.git
synced 2026-07-26 02:31:52 +00:00
refactor: remove Ctx field from git.Repository (#38500)
This commit is contained in:
@@ -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())
|
||||
|
||||
Reference in New Issue
Block a user