Remove wrong "git.DefaultContext" (#35364)
Some checks failed
cron-translations / crowdin-pull (push) Has been skipped
release-nightly / nightly-binary (push) Has been cancelled
release-nightly / nightly-docker-rootful (push) Has been cancelled
release-nightly / nightly-docker-rootless (push) Has been cancelled

This commit is contained in:
wxiaoguang
2025-08-28 00:31:21 +08:00
committed by GitHub
parent e837c998b7
commit 60246730b5
71 changed files with 384 additions and 476 deletions

View File

@ -15,7 +15,6 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/commitstatus"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"github.com/stretchr/testify/assert"
@ -187,7 +186,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo2)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo2)
assert.NoError(t, err)
defer gitRepo.Close()

View File

@ -42,17 +42,24 @@ const minDBVersion = 70 // Gitea 1.5.3
type migration struct {
idNumber int64 // DB version is "the last migration's idNumber" + 1
description string
migrate func(*xorm.Engine) error
migrate func(context.Context, *xorm.Engine) error
}
// newMigration creates a new migration
func newMigration(idNumber int64, desc string, fn func(*xorm.Engine) error) *migration {
return &migration{idNumber, desc, fn}
func newMigration[T func(*xorm.Engine) error | func(context.Context, *xorm.Engine) error](idNumber int64, desc string, fn T) *migration {
m := &migration{idNumber: idNumber, description: desc}
var ok bool
if m.migrate, ok = any(fn).(func(context.Context, *xorm.Engine) error); !ok {
m.migrate = func(ctx context.Context, x *xorm.Engine) error {
return any(fn).(func(*xorm.Engine) error)(x)
}
}
return m
}
// Migrate executes the migration
func (m *migration) Migrate(x *xorm.Engine) error {
return m.migrate(x)
func (m *migration) Migrate(ctx context.Context, x *xorm.Engine) error {
return m.migrate(ctx, x)
}
// Version describes the version table. Should have only one row with id==1
@ -456,7 +463,7 @@ func migrationIDNumberToDBVersion(idNumber int64) int64 {
}
// Migrate database to current version
func Migrate(x *xorm.Engine) error {
func Migrate(ctx context.Context, x *xorm.Engine) error {
migrations := prepareMigrationTasks()
maxDBVer := calcDBVersion(migrations)
@ -500,18 +507,16 @@ Please try upgrading to a lower version first (suggested v1.6.4), then upgrade t
}
// Some migration tasks depend on the git command
if git.DefaultContext == nil {
if err = git.InitSimple(); err != nil {
return err
}
}
// Migrate
for _, m := range getPendingMigrations(curDBVer, migrations) {
log.Info("Migration[%d]: %s", m.idNumber, m.description)
// Reset the mapper between each migration - migrations are not supposed to depend on each other
x.SetMapper(names.GonicMapper{})
if err = m.Migrate(x); err != nil {
if err = m.Migrate(ctx, x); err != nil {
return fmt.Errorf("migration[%d]: %s failed: %w", m.idNumber, m.description, err)
}
currentVersion.Version = migrationIDNumberToDBVersion(m.idNumber)

View File

@ -4,6 +4,7 @@
package v1_12
import (
"context"
"fmt"
"math"
"path/filepath"
@ -17,7 +18,7 @@ import (
"xorm.io/xorm"
)
func FixMergeBase(x *xorm.Engine) error {
func FixMergeBase(ctx context.Context, x *xorm.Engine) error {
type Repository struct {
ID int64 `xorm:"pk autoincr"`
OwnerID int64 `xorm:"UNIQUE(s) index"`
@ -82,17 +83,17 @@ func FixMergeBase(x *xorm.Engine) error {
if !pr.HasMerged {
var err error
pr.MergeBase, _, err = git.NewCommand("merge-base").AddDashesAndList(pr.BaseBranch, gitRefName).RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
pr.MergeBase, _, err = git.NewCommand("merge-base").AddDashesAndList(pr.BaseBranch, gitRefName).RunStdString(ctx, &git.RunOpts{Dir: repoPath})
if err != nil {
var err2 error
pr.MergeBase, _, err2 = git.NewCommand("rev-parse").AddDynamicArguments(git.BranchPrefix+pr.BaseBranch).RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
pr.MergeBase, _, err2 = git.NewCommand("rev-parse").AddDynamicArguments(git.BranchPrefix+pr.BaseBranch).RunStdString(ctx, &git.RunOpts{Dir: repoPath})
if err2 != nil {
log.Error("Unable to get merge base for PR ID %d, Index %d in %s/%s. Error: %v & %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err, err2)
continue
}
}
} else {
parentsString, _, err := git.NewCommand("rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
parentsString, _, err := git.NewCommand("rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(ctx, &git.RunOpts{Dir: repoPath})
if err != nil {
log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err)
continue
@ -106,7 +107,7 @@ func FixMergeBase(x *xorm.Engine) error {
refs = append(refs, gitRefName)
cmd := git.NewCommand("merge-base").AddDashesAndList(refs...)
pr.MergeBase, _, err = cmd.RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
pr.MergeBase, _, err = cmd.RunStdString(ctx, &git.RunOpts{Dir: repoPath})
if err != nil {
log.Error("Unable to get merge base for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err)
continue

View File

@ -4,6 +4,7 @@
package v1_12
import (
"context"
"fmt"
"math"
"path/filepath"
@ -17,7 +18,7 @@ import (
"xorm.io/xorm"
)
func RefixMergeBase(x *xorm.Engine) error {
func RefixMergeBase(ctx context.Context, x *xorm.Engine) error {
type Repository struct {
ID int64 `xorm:"pk autoincr"`
OwnerID int64 `xorm:"UNIQUE(s) index"`
@ -79,7 +80,7 @@ func RefixMergeBase(x *xorm.Engine) error {
gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index)
parentsString, _, err := git.NewCommand("rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
parentsString, _, err := git.NewCommand("rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(ctx, &git.RunOpts{Dir: repoPath})
if err != nil {
log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err)
continue
@ -94,7 +95,7 @@ func RefixMergeBase(x *xorm.Engine) error {
refs = append(refs, gitRefName)
cmd := git.NewCommand("merge-base").AddDashesAndList(refs...)
pr.MergeBase, _, err = cmd.RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
pr.MergeBase, _, err = cmd.RunStdString(ctx, &git.RunOpts{Dir: repoPath})
if err != nil {
log.Error("Unable to get merge base for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err)
continue

View File

@ -4,6 +4,7 @@
package v1_14
import (
"context"
"fmt"
"path/filepath"
"strings"
@ -24,7 +25,7 @@ func userPath(userName string) string {
return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
}
func FixPublisherIDforTagReleases(x *xorm.Engine) error {
func FixPublisherIDforTagReleases(ctx context.Context, x *xorm.Engine) error {
type Release struct {
ID int64
RepoID int64
@ -108,7 +109,7 @@ func FixPublisherIDforTagReleases(x *xorm.Engine) error {
return err
}
}
gitRepo, err = git.OpenRepository(git.DefaultContext, repoPath(repo.OwnerName, repo.Name))
gitRepo, err = git.OpenRepository(ctx, repoPath(repo.OwnerName, repo.Name))
if err != nil {
log.Error("Error whilst opening git repo for [%d]%s/%s. Error: %v", repo.ID, repo.OwnerName, repo.Name, err)
return err

View File

@ -4,6 +4,7 @@
package v1_9
import (
"context"
"fmt"
"path/filepath"
"strings"
@ -14,7 +15,7 @@ import (
"xorm.io/xorm"
)
func FixReleaseSha1OnReleaseTable(x *xorm.Engine) error {
func FixReleaseSha1OnReleaseTable(ctx context.Context, x *xorm.Engine) error {
type Release struct {
ID int64
RepoID int64
@ -98,7 +99,7 @@ func FixReleaseSha1OnReleaseTable(x *xorm.Engine) error {
userCache[repo.OwnerID] = user
}
gitRepo, err = git.OpenRepository(git.DefaultContext, RepoPath(user.Name, repo.Name))
gitRepo, err = git.OpenRepository(ctx, RepoPath(user.Name, repo.Name))
if err != nil {
return err
}

View File

@ -141,7 +141,7 @@ func CreateBlameReader(ctx context.Context, objectFormat ObjectFormat, repoPath
}
}()
cmd := NewCommandNoGlobals("blame", "--porcelain")
cmd := NewCommand("blame", "--porcelain")
if DefaultFeatures().CheckVersionAtLeast("2.23") && !bypassBlameIgnore {
ignoreRevsFileName, ignoreRevsFileCleanup, err = tryCreateBlameIgnoreRevsFile(commit)

View File

@ -16,7 +16,7 @@ import (
func TestBlob_Data(t *testing.T) {
output := "file2\n"
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := openRepositoryWithDefaultContext(bareRepo1Path)
repo, err := OpenRepository(t.Context(), bareRepo1Path)
require.NoError(t, err)
defer repo.Close()
@ -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 := openRepositoryWithDefaultContext(bareRepo1Path)
repo, err := OpenRepository(b.Context(), bareRepo1Path)
if err != nil {
b.Fatal(err)
}

View File

@ -29,13 +29,8 @@ import (
// In most cases, it shouldn't be used. Use AddXxx function instead
type TrustedCmdArgs []internal.CmdArg
var (
// globalCommandArgs global command args for external package setting
globalCommandArgs TrustedCmdArgs
// defaultCommandExecutionTimeout default command execution timeout duration
defaultCommandExecutionTimeout = 360 * time.Second
)
var defaultCommandExecutionTimeout = 360 * time.Second
// DefaultLocale is the default LC_ALL to run git commands in.
const DefaultLocale = "C"
@ -44,7 +39,6 @@ const DefaultLocale = "C"
type Command struct {
prog string
args []string
globalArgsLength int
brokenArgs []string
cmd *exec.Cmd // for debug purpose only
configArgs []string
@ -72,10 +66,7 @@ func (c *Command) LogString() string {
}
a := make([]string, 0, len(c.args)+1)
a = append(a, debugQuote(c.prog))
if c.globalArgsLength > 0 {
a = append(a, "...global...")
}
for i := c.globalArgsLength; i < len(c.args); i++ {
for i := 0; i < len(c.args); i++ {
a = append(a, debugQuote(logArgSanitize(c.args[i])))
}
return strings.Join(a, " ")
@ -91,24 +82,6 @@ func (c *Command) ProcessState() string {
// NewCommand creates and returns a new Git Command based on given command and arguments.
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
func NewCommand(args ...internal.CmdArg) *Command {
// Make an explicit copy of globalCommandArgs, otherwise append might overwrite it
cargs := make([]string, 0, len(globalCommandArgs)+len(args))
for _, arg := range globalCommandArgs {
cargs = append(cargs, string(arg))
}
for _, arg := range args {
cargs = append(cargs, string(arg))
}
return &Command{
prog: GitExecutable,
args: cargs,
globalArgsLength: len(globalCommandArgs),
}
}
// NewCommandNoGlobals creates and returns a new Git Command based on given command and arguments only with the specified args and don't use global command args
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
func NewCommandNoGlobals(args ...internal.CmdArg) *Command {
cargs := make([]string, 0, len(args))
for _, arg := range args {
cargs = append(cargs, string(arg))
@ -468,19 +441,3 @@ func (c *Command) runStdBytes(ctx context.Context, opts *RunOpts) (stdout, stder
// even if there is no err, there could still be some stderr output
return stdoutBuf.Bytes(), stderr, nil
}
// AllowLFSFiltersArgs return globalCommandArgs with lfs filter, it should only be used for tests
func AllowLFSFiltersArgs() TrustedCmdArgs {
// Now here we should explicitly allow lfs filters to run
filteredLFSGlobalArgs := make(TrustedCmdArgs, len(globalCommandArgs))
j := 0
for _, arg := range globalCommandArgs {
if strings.Contains(string(arg), "lfs") {
j--
} else {
filteredLFSGlobalArgs[j] = arg
j++
}
}
return filteredLFSGlobalArgs[:j]
}

View File

@ -53,9 +53,9 @@ func TestGitArgument(t *testing.T) {
}
func TestCommandString(t *testing.T) {
cmd := NewCommandNoGlobals("a", "-m msg", "it's a test", `say "hello"`)
cmd := NewCommand("a", "-m msg", "it's a test", `say "hello"`)
assert.Equal(t, cmd.prog+` a "-m msg" "it's a test" "say \"hello\""`, cmd.LogString())
cmd = NewCommandNoGlobals("url: https://a:b@c/", "/root/dir-a/dir-b")
cmd = NewCommand("url: https://a:b@c/", "/root/dir-a/dir-b")
assert.Equal(t, cmd.prog+` "url: https://sanitized-credential@c/" .../dir-a/dir-b`, cmd.LogString())
}

View File

@ -86,18 +86,13 @@ func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) {
}
// AddChanges marks local changes to be ready for commit.
func AddChanges(repoPath string, all bool, files ...string) error {
return AddChangesWithArgs(repoPath, globalCommandArgs, all, files...)
}
// AddChangesWithArgs marks local changes to be ready for commit.
func AddChangesWithArgs(repoPath string, globalArgs TrustedCmdArgs, all bool, files ...string) error {
cmd := NewCommandNoGlobals(globalArgs...).AddArguments("add")
func AddChanges(ctx context.Context, repoPath string, all bool, files ...string) error {
cmd := NewCommand().AddArguments("add")
if all {
cmd.AddArguments("--all")
}
cmd.AddDashesAndList(files...)
_, _, err := cmd.RunStdString(DefaultContext, &RunOpts{Dir: repoPath})
_, _, err := cmd.RunStdString(ctx, &RunOpts{Dir: repoPath})
return err
}
@ -110,16 +105,8 @@ type CommitChangesOptions struct {
// CommitChanges commits local changes with given committer, author and message.
// If author is nil, it will be the same as committer.
func CommitChanges(repoPath string, opts CommitChangesOptions) error {
cargs := make(TrustedCmdArgs, len(globalCommandArgs))
copy(cargs, globalCommandArgs)
return CommitChangesWithArgs(repoPath, cargs, opts)
}
// CommitChangesWithArgs commits local changes with given committer, author and message.
// If author is nil, it will be the same as committer.
func CommitChangesWithArgs(repoPath string, args TrustedCmdArgs, opts CommitChangesOptions) error {
cmd := NewCommandNoGlobals(args...)
func CommitChanges(ctx context.Context, repoPath string, opts CommitChangesOptions) error {
cmd := NewCommand()
if opts.Committer != nil {
cmd.AddOptionValues("-c", "user.name="+opts.Committer.Name)
cmd.AddOptionValues("-c", "user.email="+opts.Committer.Email)
@ -134,7 +121,7 @@ func CommitChangesWithArgs(repoPath string, args TrustedCmdArgs, opts CommitChan
}
cmd.AddOptionFormat("--message=%s", opts.Message)
_, _, err := cmd.RunStdString(DefaultContext, &RunOpts{Dir: repoPath})
_, _, err := cmd.RunStdString(ctx, &RunOpts{Dir: repoPath})
// No stderr but exit status 1 means nothing to commit.
if err != nil && err.Error() == "exit status 1" {
return nil

View File

@ -18,7 +18,7 @@ const (
func cloneRepo(tb testing.TB, url string) (string, error) {
repoDir := tb.TempDir()
if err := Clone(DefaultContext, url, repoDir, CloneRepoOptions{
if err := Clone(tb.Context(), url, repoDir, CloneRepoOptions{
Mirror: false,
Bare: false,
Quiet: true,
@ -104,7 +104,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) {
func TestEntries_GetCommitsInfo(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -114,7 +114,7 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
if err != nil {
assert.NoError(t, err)
}
clonedRepo1, err := openRepositoryWithDefaultContext(clonedPath)
clonedRepo1, err := OpenRepository(t.Context(), clonedPath)
if err != nil {
assert.NoError(t, err)
}
@ -163,7 +163,7 @@ func BenchmarkEntries_GetCommitsInfo(b *testing.B) {
b.Fatal(err)
}
if repo, err = openRepositoryWithDefaultContext(repoPath); err != nil {
if repo, err = OpenRepository(b.Context(), repoPath); err != nil {
b.Fatal(err)
}
defer repo.Close()

View File

@ -17,7 +17,7 @@ import (
func TestCommitsCountSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
commitsCount, err := CommitsCount(DefaultContext,
commitsCount, err := CommitsCount(t.Context(),
CommitsCountOptions{
RepoPath: bareRepo1Path,
Revision: []string{"f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc"},
@ -30,7 +30,7 @@ func TestCommitsCountSha256(t *testing.T) {
func TestCommitsCountWithoutBaseSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
commitsCount, err := CommitsCount(DefaultContext,
commitsCount, err := CommitsCount(t.Context(),
CommitsCountOptions{
RepoPath: bareRepo1Path,
Not: "main",
@ -44,7 +44,7 @@ func TestCommitsCountWithoutBaseSha256(t *testing.T) {
func TestGetFullCommitIDSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
id, err := GetFullCommitID(DefaultContext, bareRepo1Path, "f004f4")
id, err := GetFullCommitID(t.Context(), bareRepo1Path, "f004f4")
assert.NoError(t, err)
assert.Equal(t, "f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc", id)
}
@ -52,7 +52,7 @@ func TestGetFullCommitIDSha256(t *testing.T) {
func TestGetFullCommitIDErrorSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
id, err := GetFullCommitID(DefaultContext, bareRepo1Path, "unknown")
id, err := GetFullCommitID(t.Context(), bareRepo1Path, "unknown")
assert.Empty(t, id)
if assert.Error(t, err) {
assert.EqualError(t, err, "object does not exist [id: unknown, rel_path: ]")
@ -87,7 +87,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 := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare_sha256"))
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare_sha256"))
assert.NoError(t, err)
assert.NotNil(t, gitRepo)
defer gitRepo.Close()
@ -130,7 +130,7 @@ signed commit`, commitFromReader.Signature.Payload)
func TestHasPreviousCommitSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
repo, err := openRepositoryWithDefaultContext(bareRepo1Path)
repo, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer repo.Close()
@ -161,7 +161,7 @@ func TestHasPreviousCommitSha256(t *testing.T) {
func TestGetCommitFileStatusMergesSha256(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo6_merge_sha256")
commitFileStatus, err := GetCommitFileStatus(DefaultContext, bareRepo1Path, "d2e5609f630dd8db500f5298d05d16def282412e3e66ed68cc7d0833b29129a1")
commitFileStatus, err := GetCommitFileStatus(t.Context(), bareRepo1Path, "d2e5609f630dd8db500f5298d05d16def282412e3e66ed68cc7d0833b29129a1")
assert.NoError(t, err)
expected := CommitFileStatus{
@ -186,7 +186,7 @@ func TestGetCommitFileStatusMergesSha256(t *testing.T) {
[]string{},
}
commitFileStatus, err = GetCommitFileStatus(DefaultContext, bareRepo1Path, "da1ded40dc8e5b7c564171f4bf2fc8370487decfb1cb6a99ef28f3ed73d09172")
commitFileStatus, err = GetCommitFileStatus(t.Context(), bareRepo1Path, "da1ded40dc8e5b7c564171f4bf2fc8370487decfb1cb6a99ef28f3ed73d09172")
assert.NoError(t, err)
assert.Equal(t, expected.Added, commitFileStatus.Added)

View File

@ -16,7 +16,7 @@ import (
func TestCommitsCount(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
commitsCount, err := CommitsCount(DefaultContext,
commitsCount, err := CommitsCount(t.Context(),
CommitsCountOptions{
RepoPath: bareRepo1Path,
Revision: []string{"8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"},
@ -29,7 +29,7 @@ func TestCommitsCount(t *testing.T) {
func TestCommitsCountWithoutBase(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
commitsCount, err := CommitsCount(DefaultContext,
commitsCount, err := CommitsCount(t.Context(),
CommitsCountOptions{
RepoPath: bareRepo1Path,
Not: "master",
@ -43,7 +43,7 @@ func TestCommitsCountWithoutBase(t *testing.T) {
func TestGetFullCommitID(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
id, err := GetFullCommitID(DefaultContext, bareRepo1Path, "8006ff9a")
id, err := GetFullCommitID(t.Context(), bareRepo1Path, "8006ff9a")
assert.NoError(t, err)
assert.Equal(t, "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", id)
}
@ -51,7 +51,7 @@ func TestGetFullCommitID(t *testing.T) {
func TestGetFullCommitIDError(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
id, err := GetFullCommitID(DefaultContext, bareRepo1Path, "unknown")
id, err := GetFullCommitID(t.Context(), bareRepo1Path, "unknown")
assert.Empty(t, id)
if assert.Error(t, err) {
assert.EqualError(t, err, "object does not exist [id: unknown, rel_path: ]")
@ -83,7 +83,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 := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare"))
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
assert.NoError(t, err)
assert.NotNil(t, gitRepo)
defer gitRepo.Close()
@ -147,7 +147,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 := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare"))
gitRepo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
assert.NoError(t, err)
assert.NotNil(t, gitRepo)
defer gitRepo.Close()
@ -189,7 +189,7 @@ ISO-8859-1`, commitFromReader.Signature.Payload)
func TestHasPreviousCommit(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := openRepositoryWithDefaultContext(bareRepo1Path)
repo, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer repo.Close()
@ -320,7 +320,7 @@ func TestParseCommitFileStatus(t *testing.T) {
func TestGetCommitFileStatusMerges(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo6_merge")
commitFileStatus, err := GetCommitFileStatus(DefaultContext, bareRepo1Path, "022f4ce6214973e018f02bf363bf8a2e3691f699")
commitFileStatus, err := GetCommitFileStatus(t.Context(), bareRepo1Path, "022f4ce6214973e018f02bf363bf8a2e3691f699")
assert.NoError(t, err)
expected := CommitFileStatus{

View File

@ -4,6 +4,7 @@
package git
import (
"context"
"fmt"
"os"
"regexp"
@ -14,7 +15,7 @@ import (
)
// syncGitConfig only modifies gitconfig, won't change global variables (otherwise there will be data-race problem)
func syncGitConfig() (err error) {
func syncGitConfig(ctx context.Context) (err error) {
if err = os.MkdirAll(HomeDir(), os.ModePerm); err != nil {
return fmt.Errorf("unable to prepare git home directory %s, err: %w", HomeDir(), err)
}
@ -22,7 +23,7 @@ func syncGitConfig() (err error) {
// first, write user's git config options to git config file
// user config options could be overwritten by builtin values later, because if a value is builtin, it must have some special purposes
for k, v := range setting.GitConfig.Options {
if err = configSet(strings.ToLower(k), v); err != nil {
if err = configSet(ctx, strings.ToLower(k), v); err != nil {
return err
}
}
@ -34,41 +35,41 @@ func syncGitConfig() (err error) {
"user.name": "Gitea",
"user.email": "gitea@fake.local",
} {
if err := configSetNonExist(configKey, defaultValue); err != nil {
if err := configSetNonExist(ctx, configKey, defaultValue); err != nil {
return err
}
}
// Set git some configurations - these must be set to these values for gitea to work correctly
if err := configSet("core.quotePath", "false"); err != nil {
if err := configSet(ctx, "core.quotePath", "false"); err != nil {
return err
}
if DefaultFeatures().CheckVersionAtLeast("2.10") {
if err := configSet("receive.advertisePushOptions", "true"); err != nil {
if err := configSet(ctx, "receive.advertisePushOptions", "true"); err != nil {
return err
}
}
if DefaultFeatures().CheckVersionAtLeast("2.18") {
if err := configSet("core.commitGraph", "true"); err != nil {
if err := configSet(ctx, "core.commitGraph", "true"); err != nil {
return err
}
if err := configSet("gc.writeCommitGraph", "true"); err != nil {
if err := configSet(ctx, "gc.writeCommitGraph", "true"); err != nil {
return err
}
if err := configSet("fetch.writeCommitGraph", "true"); err != nil {
if err := configSet(ctx, "fetch.writeCommitGraph", "true"); err != nil {
return err
}
}
if DefaultFeatures().SupportProcReceive {
// set support for AGit flow
if err := configAddNonExist("receive.procReceiveRefs", "refs/for"); err != nil {
if err := configAddNonExist(ctx, "receive.procReceiveRefs", "refs/for"); err != nil {
return err
}
} else {
if err := configUnsetAll("receive.procReceiveRefs", "refs/for"); err != nil {
if err := configUnsetAll(ctx, "receive.procReceiveRefs", "refs/for"); err != nil {
return err
}
}
@ -81,18 +82,18 @@ func syncGitConfig() (err error) {
// As Gitea now always use its internal git config file, and access to the git repositories is managed through Gitea,
// it is now safe to set "safe.directory=*" for internal usage only.
// Although this setting is only supported by some new git versions, it is also tolerated by earlier versions
if err := configAddNonExist("safe.directory", "*"); err != nil {
if err := configAddNonExist(ctx, "safe.directory", "*"); err != nil {
return err
}
if runtime.GOOS == "windows" {
if err := configSet("core.longpaths", "true"); err != nil {
if err := configSet(ctx, "core.longpaths", "true"); err != nil {
return err
}
if setting.Git.DisableCoreProtectNTFS {
err = configSet("core.protectNTFS", "false")
err = configSet(ctx, "core.protectNTFS", "false")
} else {
err = configUnsetAll("core.protectNTFS", "false")
err = configUnsetAll(ctx, "core.protectNTFS", "false")
}
if err != nil {
return err
@ -101,22 +102,22 @@ func syncGitConfig() (err error) {
// By default partial clones are disabled, enable them from git v2.22
if !setting.Git.DisablePartialClone && DefaultFeatures().CheckVersionAtLeast("2.22") {
if err = configSet("uploadpack.allowfilter", "true"); err != nil {
if err = configSet(ctx, "uploadpack.allowfilter", "true"); err != nil {
return err
}
err = configSet("uploadpack.allowAnySHA1InWant", "true")
err = configSet(ctx, "uploadpack.allowAnySHA1InWant", "true")
} else {
if err = configUnsetAll("uploadpack.allowfilter", "true"); err != nil {
if err = configUnsetAll(ctx, "uploadpack.allowfilter", "true"); err != nil {
return err
}
err = configUnsetAll("uploadpack.allowAnySHA1InWant", "true")
err = configUnsetAll(ctx, "uploadpack.allowAnySHA1InWant", "true")
}
return err
}
func configSet(key, value string) error {
stdout, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key).RunStdString(DefaultContext, nil)
func configSet(ctx context.Context, key, value string) error {
stdout, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key).RunStdString(ctx, nil)
if err != nil && !IsErrorExitCode(err, 1) {
return fmt.Errorf("failed to get git config %s, err: %w", key, err)
}
@ -126,7 +127,7 @@ func configSet(key, value string) error {
return nil
}
_, _, err = NewCommand("config", "--global").AddDynamicArguments(key, value).RunStdString(DefaultContext, nil)
_, _, err = NewCommand("config", "--global").AddDynamicArguments(key, value).RunStdString(ctx, nil)
if err != nil {
return fmt.Errorf("failed to set git global config %s, err: %w", key, err)
}
@ -134,15 +135,15 @@ func configSet(key, value string) error {
return nil
}
func configSetNonExist(key, value string) error {
_, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key).RunStdString(DefaultContext, nil)
func configSetNonExist(ctx context.Context, key, value string) error {
_, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key).RunStdString(ctx, nil)
if err == nil {
// already exist
return nil
}
if IsErrorExitCode(err, 1) {
// not exist, set new config
_, _, err = NewCommand("config", "--global").AddDynamicArguments(key, value).RunStdString(DefaultContext, nil)
_, _, err = NewCommand("config", "--global").AddDynamicArguments(key, value).RunStdString(ctx, nil)
if err != nil {
return fmt.Errorf("failed to set git global config %s, err: %w", key, err)
}
@ -152,15 +153,15 @@ func configSetNonExist(key, value string) error {
return fmt.Errorf("failed to get git config %s, err: %w", key, err)
}
func configAddNonExist(key, value string) error {
_, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(DefaultContext, nil)
func configAddNonExist(ctx context.Context, key, value string) error {
_, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(ctx, nil)
if err == nil {
// already exist
return nil
}
if IsErrorExitCode(err, 1) {
// not exist, add new config
_, _, err = NewCommand("config", "--global", "--add").AddDynamicArguments(key, value).RunStdString(DefaultContext, nil)
_, _, err = NewCommand("config", "--global", "--add").AddDynamicArguments(key, value).RunStdString(ctx, nil)
if err != nil {
return fmt.Errorf("failed to add git global config %s, err: %w", key, err)
}
@ -169,11 +170,11 @@ func configAddNonExist(key, value string) error {
return fmt.Errorf("failed to get git config %s, err: %w", key, err)
}
func configUnsetAll(key, value string) error {
_, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key).RunStdString(DefaultContext, nil)
func configUnsetAll(ctx context.Context, key, value string) error {
_, _, err := NewCommand("config", "--global", "--get").AddDynamicArguments(key).RunStdString(ctx, nil)
if err == nil {
// exist, need to remove
_, _, err = NewCommand("config", "--global", "--unset-all").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(DefaultContext, nil)
_, _, err = NewCommand("config", "--global", "--unset-all").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(ctx, nil)
if err != nil {
return fmt.Errorf("failed to unset git global config %s, err: %w", key, err)
}

View File

@ -21,35 +21,36 @@ func gitConfigContains(sub string) bool {
}
func TestGitConfig(t *testing.T) {
ctx := t.Context()
assert.False(t, gitConfigContains("key-a"))
assert.NoError(t, configSetNonExist("test.key-a", "val-a"))
assert.NoError(t, configSetNonExist(ctx, "test.key-a", "val-a"))
assert.True(t, gitConfigContains("key-a = val-a"))
assert.NoError(t, configSetNonExist("test.key-a", "val-a-changed"))
assert.NoError(t, configSetNonExist(ctx, "test.key-a", "val-a-changed"))
assert.False(t, gitConfigContains("key-a = val-a-changed"))
assert.NoError(t, configSet("test.key-a", "val-a-changed"))
assert.NoError(t, configSet(ctx, "test.key-a", "val-a-changed"))
assert.True(t, gitConfigContains("key-a = val-a-changed"))
assert.NoError(t, configAddNonExist("test.key-b", "val-b"))
assert.NoError(t, configAddNonExist(ctx, "test.key-b", "val-b"))
assert.True(t, gitConfigContains("key-b = val-b"))
assert.NoError(t, configAddNonExist("test.key-b", "val-2b"))
assert.NoError(t, configAddNonExist(ctx, "test.key-b", "val-2b"))
assert.True(t, gitConfigContains("key-b = val-b"))
assert.True(t, gitConfigContains("key-b = val-2b"))
assert.NoError(t, configUnsetAll("test.key-b", "val-b"))
assert.NoError(t, configUnsetAll(ctx, "test.key-b", "val-b"))
assert.False(t, gitConfigContains("key-b = val-b"))
assert.True(t, gitConfigContains("key-b = val-2b"))
assert.NoError(t, configUnsetAll("test.key-b", "val-2b"))
assert.NoError(t, configUnsetAll(ctx, "test.key-b", "val-2b"))
assert.False(t, gitConfigContains("key-b = val-2b"))
assert.NoError(t, configSet("test.key-x", "*"))
assert.NoError(t, configSet(ctx, "test.key-x", "*"))
assert.True(t, gitConfigContains("key-x = *"))
assert.NoError(t, configSetNonExist("test.key-x", "*"))
assert.NoError(t, configUnsetAll("test.key-x", "*"))
assert.NoError(t, configSetNonExist(ctx, "test.key-x", "*"))
assert.NoError(t, configUnsetAll(ctx, "test.key-x", "*"))
assert.False(t, gitConfigContains("key-x = *"))
}
@ -60,7 +61,7 @@ func TestSyncConfig(t *testing.T) {
}()
setting.GitConfig.Options["sync-test.cfg-key-a"] = "CfgValA"
assert.NoError(t, syncGitConfig())
assert.NoError(t, syncGitConfig(t.Context()))
assert.True(t, gitConfigContains("[sync-test]"))
assert.True(t, gitConfigContains("cfg-key-a = CfgValA"))
}

View File

@ -35,7 +35,6 @@ type Features struct {
var (
GitExecutable = "git" // the command name of git, will be updated to an absolute path during initialization
DefaultContext context.Context // the default context to run git commands in, must be initialized by git.InitXxx
defaultFeatures *Features
)
@ -61,7 +60,7 @@ func DefaultFeatures() *Features {
}
func loadGitVersionFeatures() (*Features, error) {
stdout, _, runErr := NewCommand("version").RunStdString(DefaultContext, nil)
stdout, _, runErr := NewCommand("version").RunStdString(context.Background(), nil)
if runErr != nil {
return nil, runErr
}
@ -163,14 +162,10 @@ func InitSimple() error {
return errors.New("unable to init Git's HomeDir, incorrect initialization of the setting and git modules")
}
if DefaultContext != nil && (!setting.IsProd || setting.IsInTesting) {
if defaultFeatures != nil && (!setting.IsProd || setting.IsInTesting) {
log.Warn("git module has been initialized already, duplicate init may work but it's better to fix it")
}
// FIXME: git context is used across the application, so it should use the global default context, this design is not right but it's hard to change now.
DefaultContext = context.Background()
globalCommandArgs = nil
if setting.Git.Timeout.Default > 0 {
defaultCommandExecutionTimeout = time.Duration(setting.Git.Timeout.Default) * time.Second
}
@ -202,22 +197,11 @@ func InitFull() (err error) {
return err
}
// Since git wire protocol has been released from git v2.18
if setting.Git.EnableAutoGitWireProtocol && DefaultFeatures().CheckVersionAtLeast("2.18") {
globalCommandArgs = append(globalCommandArgs, "-c", "protocol.version=2")
}
// Explicitly disable credential helper, otherwise Git credentials might leak
if DefaultFeatures().CheckVersionAtLeast("2.9") {
globalCommandArgs = append(globalCommandArgs, "-c", "credential.helper=")
}
if setting.LFS.StartServer {
if !DefaultFeatures().CheckVersionAtLeast("2.1.2") {
return errors.New("LFS server support requires Git >= 2.1.2")
}
globalCommandArgs = append(globalCommandArgs, "-c", "filter.lfs.required=", "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
}
return syncGitConfig()
return syncGitConfig(context.Background())
}

View File

@ -11,7 +11,7 @@ import (
)
func TestGrepSearch(t *testing.T) {
repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "language_stats_repo"))
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "language_stats_repo"))
assert.NoError(t, err)
defer repo.Close()

View File

@ -12,7 +12,7 @@ import (
func TestGetNotes(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), 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 := openRepositoryWithDefaultContext(repoPath)
repo, err := OpenRepository(t.Context(), 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 := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()

View File

@ -121,17 +121,12 @@ type CloneRepoOptions struct {
// Clone clones original repository to target path.
func Clone(ctx context.Context, from, to string, opts CloneRepoOptions) error {
return CloneWithArgs(ctx, globalCommandArgs, from, to, opts)
}
// CloneWithArgs original repository to target path.
func CloneWithArgs(ctx context.Context, args TrustedCmdArgs, from, to string, opts CloneRepoOptions) (err error) {
toDir := path.Dir(to)
if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
if err := os.MkdirAll(toDir, os.ModePerm); err != nil {
return err
}
cmd := NewCommandNoGlobals(args...).AddArguments("clone")
cmd := NewCommand().AddArguments("clone")
if opts.SkipTLSVerify {
cmd.AddArguments("-c", "http.sslVerify=false")
}

View File

@ -39,11 +39,6 @@ type Repository struct {
objectFormat ObjectFormat
}
// openRepositoryWithDefaultContext opens the repository at the given path with DefaultContext.
func openRepositoryWithDefaultContext(repoPath string) (*Repository, error) {
return OpenRepository(DefaultContext, repoPath)
}
// OpenRepository opens the repository at the given path within the context.Context
func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
repoPath, err := filepath.Abs(repoPath)

View File

@ -37,11 +37,6 @@ type Repository struct {
objectFormat ObjectFormat
}
// openRepositoryWithDefaultContext opens the repository at the given path with DefaultContext.
func openRepositoryWithDefaultContext(repoPath string) (*Repository, error) {
return OpenRepository(DefaultContext, repoPath)
}
// OpenRepository opens the repository at the given path with the provided context.
func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) {
repoPath, err := filepath.Abs(repoPath)

View File

@ -14,7 +14,7 @@ import (
func TestRepository_GetBlob_Found(t *testing.T) {
repoPath := filepath.Join(testReposDir, "repo1_bare")
r, err := openRepositoryWithDefaultContext(repoPath)
r, err := OpenRepository(t.Context(), repoPath)
assert.NoError(t, err)
defer r.Close()
@ -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 := openRepositoryWithDefaultContext(repoPath)
r, err := OpenRepository(t.Context(), 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 := openRepositoryWithDefaultContext(repoPath)
r, err := OpenRepository(t.Context(), repoPath)
assert.NoError(t, err)
defer r.Close()

View File

@ -13,7 +13,7 @@ import (
func TestRepository_GetBranches(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -41,7 +41,7 @@ func TestRepository_GetBranches(t *testing.T) {
func BenchmarkRepository_GetBranches(b *testing.B) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(b.Context(), bareRepo1Path)
if err != nil {
b.Fatal(err)
}
@ -57,7 +57,7 @@ func BenchmarkRepository_GetBranches(b *testing.B) {
func TestGetRefsBySha(t *testing.T) {
bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls")
bareRepo5, err := OpenRepository(DefaultContext, bareRepo5Path)
bareRepo5, err := OpenRepository(t.Context(), bareRepo5Path)
if err != nil {
t.Fatal(err)
}
@ -84,7 +84,7 @@ func TestGetRefsBySha(t *testing.T) {
func BenchmarkGetRefsBySha(b *testing.B) {
bareRepo5Path := filepath.Join(testReposDir, "repo5_pulls")
bareRepo5, err := OpenRepository(DefaultContext, bareRepo5Path)
bareRepo5, err := OpenRepository(b.Context(), bareRepo5Path)
if err != nil {
b.Fatal(err)
}
@ -97,7 +97,7 @@ func BenchmarkGetRefsBySha(b *testing.B) {
}
func TestRepository_IsObjectExist(t *testing.T) {
repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare"))
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
require.NoError(t, err)
defer repo.Close()
@ -149,7 +149,7 @@ func TestRepository_IsObjectExist(t *testing.T) {
}
func TestRepository_IsReferenceExist(t *testing.T) {
repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare"))
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
require.NoError(t, err)
defer repo.Close()

View File

@ -17,7 +17,7 @@ import (
func TestRepository_GetCommitBranches(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -44,7 +44,7 @@ func TestRepository_GetCommitBranches(t *testing.T) {
func TestGetTagCommitWithSignature(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -59,7 +59,7 @@ func TestGetTagCommitWithSignature(t *testing.T) {
func TestGetCommitWithBadCommitID(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -71,7 +71,7 @@ func TestGetCommitWithBadCommitID(t *testing.T) {
func TestIsCommitInBranch(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -86,7 +86,7 @@ func TestIsCommitInBranch(t *testing.T) {
func TestRepository_CommitsBetweenIDs(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo4_commitsbetween")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -108,7 +108,7 @@ func TestRepository_CommitsBetweenIDs(t *testing.T) {
func TestGetRefCommitID(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -135,7 +135,7 @@ func TestCommitsByFileAndRange(t *testing.T) {
defer test.MockVariableValue(&setting.Git.CommitsRangeSize, 2)()
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
require.NoError(t, err)
defer bareRepo1.Close()

View File

@ -20,7 +20,7 @@ func TestGetFormatPatch(t *testing.T) {
return
}
repo, err := openRepositoryWithDefaultContext(clonedPath)
repo, err := OpenRepository(t.Context(), clonedPath)
if err != nil {
assert.NoError(t, err)
return
@ -48,7 +48,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 := openRepositoryWithDefaultContext(bareRepo1Path)
repo, err := OpenRepository(t.Context(), bareRepo1Path)
if err != nil {
assert.NoError(t, err)
return
@ -86,7 +86,7 @@ func TestReadWritePullHead(t *testing.T) {
return
}
repo, err := openRepositoryWithDefaultContext(clonedPath)
repo, err := OpenRepository(t.Context(), clonedPath)
if err != nil {
assert.NoError(t, err)
return
@ -122,7 +122,7 @@ func TestReadWritePullHead(t *testing.T) {
func TestGetCommitFilesChanged(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := openRepositoryWithDefaultContext(bareRepo1Path)
repo, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer repo.Close()

View File

@ -12,7 +12,7 @@ import (
func TestRepository_GetRefs(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()
@ -37,7 +37,7 @@ func TestRepository_GetRefs(t *testing.T) {
func TestRepository_GetRefsFiltered(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()

View File

@ -13,7 +13,7 @@ import (
func TestRepository_GetCodeActivityStats(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer bareRepo1.Close()

View File

@ -13,7 +13,7 @@ import (
func TestRepository_GetTags(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path)
bareRepo1, err := OpenRepository(t.Context(), bareRepo1Path)
if err != nil {
assert.NoError(t, err)
return
@ -44,7 +44,7 @@ func TestRepository_GetTag(t *testing.T) {
return
}
bareRepo1, err := openRepositoryWithDefaultContext(clonedPath)
bareRepo1, err := OpenRepository(t.Context(), clonedPath)
if err != nil {
assert.NoError(t, err)
return
@ -136,7 +136,7 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
return
}
bareRepo1, err := openRepositoryWithDefaultContext(clonedPath)
bareRepo1, err := OpenRepository(t.Context(), clonedPath)
if err != nil {
assert.NoError(t, err)
return

View File

@ -12,7 +12,7 @@ import (
func TestGetLatestCommitTime(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
lct, err := GetLatestCommitTime(DefaultContext, bareRepo1Path)
lct, err := GetLatestCommitTime(t.Context(), bareRepo1Path)
assert.NoError(t, err)
// Time is Sun Nov 13 16:40:14 2022 +0100
// which is the time of commit
@ -22,7 +22,7 @@ func TestGetLatestCommitTime(t *testing.T) {
func TestRepoIsEmpty(t *testing.T) {
emptyRepo2Path := filepath.Join(testReposDir, "repo2_empty")
repo, err := openRepositoryWithDefaultContext(emptyRepo2Path)
repo, err := OpenRepository(t.Context(), emptyRepo2Path)
assert.NoError(t, err)
defer repo.Close()
isEmpty, err := repo.IsEmpty()

View File

@ -14,7 +14,7 @@ import (
func TestGetTemplateSubmoduleCommits(t *testing.T) {
testRepoPath := filepath.Join(testReposDir, "repo4_submodules")
submodules, err := GetTemplateSubmoduleCommits(DefaultContext, testRepoPath)
submodules, err := GetTemplateSubmoduleCommits(t.Context(), testRepoPath)
require.NoError(t, err)
assert.Len(t, submodules, 2)
@ -39,7 +39,7 @@ func TestAddTemplateSubmoduleIndexes(t *testing.T) {
require.NoError(t, err)
_, _, err = NewCommand("-c", "user.name=a", "-c", "user.email=b", "commit", "-m=test").RunStdString(ctx, &RunOpts{Dir: tmpDir})
require.NoError(t, err)
submodules, err := GetTemplateSubmoduleCommits(DefaultContext, tmpDir)
submodules, err := GetTemplateSubmoduleCommits(t.Context(), tmpDir)
require.NoError(t, err)
assert.Len(t, submodules, 1)
assert.Equal(t, "new-dir", submodules[0].Path)

View File

@ -13,7 +13,7 @@ import (
)
func TestFollowLink(t *testing.T) {
r, err := openRepositoryWithDefaultContext("tests/repos/repo1_bare")
r, err := OpenRepository(t.Context(), "tests/repos/repo1_bare")
require.NoError(t, err)
defer r.Close()

View File

@ -11,7 +11,7 @@ import (
)
func TestSubTree_Issue29101(t *testing.T) {
repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare"))
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
assert.NoError(t, err)
defer repo.Close()
@ -27,7 +27,7 @@ func TestSubTree_Issue29101(t *testing.T) {
}
func Test_GetTreePathLatestCommit(t *testing.T) {
repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo6_blame"))
repo, err := OpenRepository(t.Context(), filepath.Join(testReposDir, "repo6_blame"))
assert.NoError(t, err)
defer repo.Close()

View File

@ -50,7 +50,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) {
pushCommits.HeadCommit = &PushCommit{Sha1: "69554a6"}
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16})
payloadCommits, headCommit, err := pushCommits.ToAPIPayloadCommits(git.DefaultContext, repo)
payloadCommits, headCommit, err := pushCommits.ToAPIPayloadCommits(t.Context(), repo)
assert.NoError(t, err)
assert.Len(t, payloadCommits, 3)
assert.NotNil(t, headCommit)

View File

@ -8,7 +8,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"github.com/stretchr/testify/assert"
@ -22,7 +21,7 @@ func TestEditorUtils(t *testing.T) {
assert.Equal(t, "user2-patch-1", branchName)
})
t.Run("getClosestParentWithFiles", func(t *testing.T) {
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
treePath := getClosestParentWithFiles(gitRepo, "sub-home-md-img-check", "docs/foo/bar")
assert.Equal(t, "docs", treePath)

View File

@ -29,7 +29,7 @@ const (
)
func wikiEntry(t *testing.T, repo *repo_model.Repository, wikiName wiki_service.WebPath) *git.TreeEntry {
wikiRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo.WikiStorageRepo())
wikiRepo, err := gitrepo.OpenRepository(t.Context(), repo.WikiStorageRepo())
assert.NoError(t, err)
defer wikiRepo.Close()
commit, err := wikiRepo.GetBranchCommit("master")

View File

@ -12,7 +12,6 @@ import (
access_model "code.gitea.io/gitea/models/perm/access"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -25,7 +24,7 @@ func TestPullRequest_APIFormat(t *testing.T) {
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadAttributes(db.DefaultContext))
assert.NoError(t, pr.LoadIssue(db.DefaultContext))
apiPullRequest := ToAPIPullRequest(git.DefaultContext, pr, nil)
apiPullRequest := ToAPIPullRequest(t.Context(), pr, nil)
assert.NotNil(t, apiPullRequest)
assert.Equal(t, &structs.PRBranchInfo{
Name: "branch1",
@ -42,12 +41,12 @@ func TestPullRequest_APIFormat(t *testing.T) {
// simulate fork deletion
pr.HeadRepo = nil
pr.HeadRepoID = 100000
apiPullRequest = ToAPIPullRequest(git.DefaultContext, pr, nil)
apiPullRequest = ToAPIPullRequest(t.Context(), pr, nil)
assert.NotNil(t, apiPullRequest)
assert.Nil(t, apiPullRequest.Head.Repository)
assert.EqualValues(t, -1, apiPullRequest.Head.RepoID)
apiPullRequests, err := ToAPIPullRequests(git.DefaultContext, pr.BaseRepo, []*issues_model.PullRequest{pr}, nil)
apiPullRequests, err := ToAPIPullRequests(t.Context(), pr.BaseRepo, []*issues_model.PullRequest{pr}, nil)
assert.NoError(t, err)
assert.Len(t, apiPullRequests, 1)
assert.NotNil(t, apiPullRequests[0])

View File

@ -206,7 +206,7 @@ func TestGitDiffTree(t *testing.T) {
for _, tt := range test {
t.Run(tt.Name, func(t *testing.T) {
gitRepo, err := git.OpenRepository(git.DefaultContext, tt.RepoPath)
gitRepo, err := git.OpenRepository(t.Context(), tt.RepoPath)
assert.NoError(t, err)
defer gitRepo.Close()
@ -415,7 +415,7 @@ func TestGitDiffTreeErrors(t *testing.T) {
for _, tt := range test {
t.Run(tt.Name, func(t *testing.T) {
gitRepo, err := git.OpenRepository(git.DefaultContext, tt.RepoPath)
gitRepo, err := git.OpenRepository(t.Context(), tt.RepoPath)
assert.NoError(t, err)
defer gitRepo.Close()

View File

@ -236,22 +236,22 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) {
//
fromRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
baseRef := "master"
assert.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false, fromRepo.ObjectFormatName))
err := git.NewCommand("symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseRef).Run(git.DefaultContext, &git.RunOpts{Dir: fromRepo.RepoPath()})
assert.NoError(t, git.InitRepository(t.Context(), fromRepo.RepoPath(), false, fromRepo.ObjectFormatName))
err := git.NewCommand("symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseRef).Run(t.Context(), &git.RunOpts{Dir: fromRepo.RepoPath()})
assert.NoError(t, err)
assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("# Testing Repository\n\nOriginally created in: "+fromRepo.RepoPath()), 0o644))
assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true))
assert.NoError(t, git.AddChanges(t.Context(), fromRepo.RepoPath(), true))
signature := git.Signature{
Email: "test@example.com",
Name: "test",
When: time.Now(),
}
assert.NoError(t, git.CommitChanges(fromRepo.RepoPath(), git.CommitChangesOptions{
assert.NoError(t, git.CommitChanges(t.Context(), fromRepo.RepoPath(), git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
Message: "Initial Commit",
}))
fromGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, fromRepo)
fromGitRepo, err := gitrepo.OpenRepository(t.Context(), fromRepo)
assert.NoError(t, err)
defer fromGitRepo.Close()
baseSHA, err := fromGitRepo.GetBranchCommitID(baseRef)
@ -261,12 +261,12 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) {
// fromRepo branch1
//
headRef := "branch1"
_, _, err = git.NewCommand("checkout", "-b").AddDynamicArguments(headRef).RunStdString(git.DefaultContext, &git.RunOpts{Dir: fromRepo.RepoPath()})
_, _, err = git.NewCommand("checkout", "-b").AddDynamicArguments(headRef).RunStdString(t.Context(), &git.RunOpts{Dir: fromRepo.RepoPath()})
assert.NoError(t, err)
assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("SOMETHING"), 0o644))
assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true))
assert.NoError(t, git.AddChanges(t.Context(), fromRepo.RepoPath(), true))
signature.When = time.Now()
assert.NoError(t, git.CommitChanges(fromRepo.RepoPath(), git.CommitChangesOptions{
assert.NoError(t, git.CommitChanges(t.Context(), fromRepo.RepoPath(), git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
Message: "Pull request",
@ -282,19 +282,19 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) {
//
forkHeadRef := "branch2"
forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8})
assert.NoError(t, git.CloneWithArgs(git.DefaultContext, nil, fromRepo.RepoPath(), forkRepo.RepoPath(), git.CloneRepoOptions{
assert.NoError(t, git.Clone(t.Context(), fromRepo.RepoPath(), forkRepo.RepoPath(), git.CloneRepoOptions{
Branch: headRef,
}))
_, _, err = git.NewCommand("checkout", "-b").AddDynamicArguments(forkHeadRef).RunStdString(git.DefaultContext, &git.RunOpts{Dir: forkRepo.RepoPath()})
_, _, err = git.NewCommand("checkout", "-b").AddDynamicArguments(forkHeadRef).RunStdString(t.Context(), &git.RunOpts{Dir: forkRepo.RepoPath()})
assert.NoError(t, err)
assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte("# branch2 "+forkRepo.RepoPath()), 0o644))
assert.NoError(t, git.AddChanges(forkRepo.RepoPath(), true))
assert.NoError(t, git.CommitChanges(forkRepo.RepoPath(), git.CommitChangesOptions{
assert.NoError(t, git.AddChanges(t.Context(), forkRepo.RepoPath(), true))
assert.NoError(t, git.CommitChanges(t.Context(), forkRepo.RepoPath(), git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
Message: "branch2 commit",
}))
forkGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, forkRepo)
forkGitRepo, err := gitrepo.OpenRepository(t.Context(), forkRepo)
assert.NoError(t, err)
defer forkGitRepo.Close()
forkHeadSHA, err := forkGitRepo.GetBranchCommitID(forkHeadRef)

View File

@ -12,7 +12,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"github.com/stretchr/testify/assert"
@ -42,7 +41,7 @@ func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) {
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext))
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, pr.BaseRepo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), pr.BaseRepo)
assert.NoError(t, err)
defer gitRepo.Close()
@ -72,7 +71,7 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) {
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2, BaseRepo: baseRepo})
assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext))
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, pr.BaseRepo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), pr.BaseRepo)
assert.NoError(t, err)
defer gitRepo.Close()

View File

@ -12,7 +12,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/services/attachment"
@ -31,7 +30,7 @@ func TestRelease_Create(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
@ -136,7 +135,7 @@ func TestRelease_Update(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
@ -278,7 +277,7 @@ func TestRelease_createTag(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
@ -359,6 +358,6 @@ func TestCreateNewTag(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.NoError(t, CreateNewTag(git.DefaultContext, user, repo, "master", "v2.0",
assert.NoError(t, CreateNewTag(t.Context(), user, repo, "master", "v2.0",
"v2.0 is released \n\n BUGFIX: .... \n\n 123"))
}

View File

@ -11,7 +11,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert"
@ -23,7 +22,7 @@ func TestCreateRepositoryDirectly(t *testing.T) {
// a successful creating repository
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
createdRepo, err := CreateRepositoryDirectly(git.DefaultContext, user2, user2, CreateRepoOptions{
createdRepo, err := CreateRepositoryDirectly(t.Context(), user2, user2, CreateRepoOptions{
Name: "created-repo",
}, true)
assert.NoError(t, err)

View File

@ -11,7 +11,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/util"
@ -26,7 +25,7 @@ func TestForkRepository(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 13})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10})
fork, err := ForkRepository(git.DefaultContext, user, user, ForkRepoOptions{
fork, err := ForkRepository(t.Context(), user, user, ForkRepoOptions{
BaseRepo: repo,
Name: "test",
Description: "test",
@ -42,7 +41,7 @@ func TestForkRepository(t *testing.T) {
defer test.MockVariableValue(&setting.Repository.AllowForkWithoutMaximumLimit, false)()
// user has reached maximum limit of repositories
user.MaxRepoCreation = 0
fork2, err := ForkRepository(git.DefaultContext, user, user, ForkRepoOptions{
fork2, err := ForkRepository(t.Context(), user, user, ForkRepoOptions{
BaseRepo: repo,
Name: "test",
Description: "test",
@ -58,7 +57,7 @@ func TestForkRepositoryCleanup(t *testing.T) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo10 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10})
fork, err := ForkRepository(git.DefaultContext, user2, user2, ForkRepoOptions{
fork, err := ForkRepository(t.Context(), user2, user2, ForkRepoOptions{
BaseRepo: repo10,
Name: "test",
})

View File

@ -16,7 +16,7 @@ import (
)
func BenchmarkGetCommitGraph(b *testing.B) {
currentRepo, err := git.OpenRepository(git.DefaultContext, ".")
currentRepo, err := git.OpenRepository(b.Context(), ".")
if err != nil || currentRepo == nil {
b.Error("Could not open repository")
}

View File

@ -20,5 +20,5 @@ func Migrate(ctx context.Context, x *xorm.Engine) error {
}
defer release()
return migrations.Migrate(x)
return migrations.Migrate(ctx, x)
}

View File

@ -144,11 +144,11 @@ func TestRepository_InitWiki(t *testing.T) {
unittest.PrepareTestEnv(t)
// repo1 already has a wiki
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.NoError(t, InitWiki(git.DefaultContext, repo1))
assert.NoError(t, InitWiki(t.Context(), repo1))
// repo2 does not already have a wiki
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
assert.NoError(t, InitWiki(git.DefaultContext, repo2))
assert.NoError(t, InitWiki(t.Context(), repo2))
assert.True(t, repo2.HasWiki())
}
@ -164,9 +164,9 @@ func TestRepository_AddWikiPage(t *testing.T) {
} {
t.Run("test wiki exist: "+userTitle, func(t *testing.T) {
webPath := UserTitleToWebPath("", userTitle)
assert.NoError(t, AddWikiPage(git.DefaultContext, doer, repo, webPath, wikiContent, commitMsg))
assert.NoError(t, AddWikiPage(t.Context(), doer, repo, webPath, wikiContent, commitMsg))
// Now need to show that the page has been added:
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo.WikiStorageRepo())
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo.WikiStorageRepo())
require.NoError(t, err)
defer gitRepo.Close()
@ -182,7 +182,7 @@ func TestRepository_AddWikiPage(t *testing.T) {
t.Run("check wiki already exist", func(t *testing.T) {
t.Parallel()
// test for already-existing wiki name
err := AddWikiPage(git.DefaultContext, doer, repo, "Home", wikiContent, commitMsg)
err := AddWikiPage(t.Context(), doer, repo, "Home", wikiContent, commitMsg)
assert.Error(t, err)
assert.True(t, repo_model.IsErrWikiAlreadyExist(err))
})
@ -190,7 +190,7 @@ func TestRepository_AddWikiPage(t *testing.T) {
t.Run("check wiki reserved name", func(t *testing.T) {
t.Parallel()
// test for reserved wiki name
err := AddWikiPage(git.DefaultContext, doer, repo, "_edit", wikiContent, commitMsg)
err := AddWikiPage(t.Context(), doer, repo, "_edit", wikiContent, commitMsg)
assert.Error(t, err)
assert.True(t, repo_model.IsErrWikiReservedName(err))
})
@ -210,10 +210,10 @@ func TestRepository_EditWikiPage(t *testing.T) {
} {
webPath := UserTitleToWebPath("", newWikiName)
unittest.PrepareTestEnv(t)
assert.NoError(t, EditWikiPage(git.DefaultContext, doer, repo, "Home", webPath, newWikiContent, commitMsg))
assert.NoError(t, EditWikiPage(t.Context(), doer, repo, "Home", webPath, newWikiContent, commitMsg))
// Now need to show that the page has been added:
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo.WikiStorageRepo())
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo.WikiStorageRepo())
assert.NoError(t, err)
masterTree, err := gitRepo.GetTree(repo.DefaultWikiBranch)
assert.NoError(t, err)
@ -234,10 +234,10 @@ func TestRepository_DeleteWikiPage(t *testing.T) {
unittest.PrepareTestEnv(t)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, DeleteWikiPage(git.DefaultContext, doer, repo, "Home"))
assert.NoError(t, DeleteWikiPage(t.Context(), doer, repo, "Home"))
// Now need to show that the page has been added:
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo.WikiStorageRepo())
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo.WikiStorageRepo())
require.NoError(t, err)
defer gitRepo.Close()
@ -251,7 +251,7 @@ func TestRepository_DeleteWikiPage(t *testing.T) {
func TestPrepareWikiFileName(t *testing.T) {
unittest.PrepareTestEnv(t)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo.WikiStorageRepo())
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo.WikiStorageRepo())
require.NoError(t, err)
defer gitRepo.Close()
@ -301,10 +301,10 @@ func TestPrepareWikiFileName_FirstPage(t *testing.T) {
// Now create a temporaryDirectory
tmpDir := t.TempDir()
err := git.InitRepository(git.DefaultContext, tmpDir, true, git.Sha1ObjectFormat.Name())
err := git.InitRepository(t.Context(), tmpDir, true, git.Sha1ObjectFormat.Name())
assert.NoError(t, err)
gitRepo, err := git.OpenRepository(git.DefaultContext, tmpDir)
gitRepo, err := git.OpenRepository(t.Context(), tmpDir)
require.NoError(t, err)
defer gitRepo.Close()

View File

@ -65,7 +65,7 @@ func TestPullRequestTargetEvent(t *testing.T) {
t.Run("AddUser4AsCollaboratorWithReadAccess", doAPIAddCollaborator(ctx, "user4", perm.AccessModeRead))
// create the forked repo
forkedRepo, err := repo_service.ForkRepository(git.DefaultContext, user2, user4, repo_service.ForkRepoOptions{
forkedRepo, err := repo_service.ForkRepository(t.Context(), user2, user4, repo_service.ForkRepoOptions{
BaseRepo: baseRepo,
Name: "forked-repo-pull-request-target",
Description: "test pull-request-target event",
@ -74,7 +74,7 @@ func TestPullRequestTargetEvent(t *testing.T) {
assert.NotEmpty(t, forkedRepo)
// add workflow file to the base repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), baseRepo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -112,7 +112,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// add a new file to the forked repo
addFileToForkedResp, err := files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, user4, &files_service.ChangeRepoFilesOptions{
addFileToForkedResp, err := files_service.ChangeRepoFiles(t.Context(), forkedRepo, user4, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -157,7 +157,7 @@ jobs:
Type: issues_model.PullRequestGitea,
}
prOpts := &pull_service.NewPullRequestOptions{Repo: baseRepo, Issue: pullIssue, PullRequest: pullRequest}
err = pull_service.NewPullRequest(git.DefaultContext, prOpts)
err = pull_service.NewPullRequest(t.Context(), prOpts)
assert.NoError(t, err)
// load and compare ActionRun
@ -167,7 +167,7 @@ jobs:
assert.Equal(t, actions_module.GithubEventPullRequestTarget, actionRun.TriggerEvent)
// add another file whose name cannot match the specified path
addFileToForkedResp, err = files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, user4, &files_service.ChangeRepoFilesOptions{
addFileToForkedResp, err = files_service.ChangeRepoFiles(t.Context(), forkedRepo, user4, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -212,7 +212,7 @@ jobs:
Type: issues_model.PullRequestGitea,
}
prOpts = &pull_service.NewPullRequestOptions{Repo: baseRepo, Issue: pullIssue, PullRequest: pullRequest}
err = pull_service.NewPullRequest(git.DefaultContext, prOpts)
err = pull_service.NewPullRequest(t.Context(), prOpts)
assert.NoError(t, err)
// the new pull request cannot trigger actions, so there is still only 1 record
@ -240,7 +240,7 @@ func TestSkipCI(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -281,7 +281,7 @@ jobs:
assert.Equal(t, 1, unittest.GetCount(t, &actions_model.ActionRun{RepoID: repo.ID}))
// add a file with a configured skip-ci string in commit message
addFileResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addFileResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -312,7 +312,7 @@ jobs:
assert.Equal(t, 1, unittest.GetCount(t, &actions_model.ActionRun{RepoID: repo.ID}))
// add file to new branch
addFileToBranchResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addFileToBranchResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -369,7 +369,7 @@ func TestCreateDeleteRefEvent(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -405,7 +405,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -491,7 +491,7 @@ func TestPullRequestCommitStatusEvent(t *testing.T) {
t.Run("AddUser4AsCollaboratorWithReadAccess", doAPIAddCollaborator(ctx, "user4", perm.AccessModeRead))
// add the workflow file to the repo
addWorkflow, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflow, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -530,9 +530,9 @@ jobs:
// create a new branch
testBranch := "test-branch"
gitRepo, err := git.OpenRepository(git.DefaultContext, ".")
gitRepo, err := git.OpenRepository(t.Context(), ".")
assert.NoError(t, err)
err = repo_service.CreateNewBranch(git.DefaultContext, user2, repo, gitRepo, "main", testBranch)
err = repo_service.CreateNewBranch(t.Context(), user2, repo, gitRepo, "main", testBranch)
assert.NoError(t, err)
// create Pull
@ -606,7 +606,7 @@ jobs:
checkCommitStatusAndInsertFakeStatus(t, repo, sha)
// synchronize
addFileResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addFileResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -715,7 +715,7 @@ func TestWorkflowDispatchPublicApi(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -751,7 +751,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -795,7 +795,7 @@ func TestWorkflowDispatchPublicApiWithInputs(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -831,7 +831,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -886,7 +886,7 @@ func TestWorkflowDispatchPublicApiJSON(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -922,7 +922,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -972,7 +972,7 @@ func TestWorkflowDispatchPublicApiWithInputsJSON(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -1008,7 +1008,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -1066,7 +1066,7 @@ func TestWorkflowDispatchPublicApiWithInputsNonDefaultBranchJSON(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -1102,7 +1102,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// add workflow file to the repo
addWorkflowToBaseResp, err = files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err = files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "update",
@ -1138,7 +1138,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the dispatch branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
commit, err := gitRepo.GetBranchCommit("dispatch")
@ -1204,7 +1204,7 @@ func TestWorkflowApi(t *testing.T) {
assert.Empty(t, workflows.Workflows)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -1336,7 +1336,7 @@ jobs:
assert.Equal(t, workflows.Workflows[0].State, workflow.State)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -1470,7 +1470,7 @@ func TestActionRunNameWithContextVariables(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -1507,7 +1507,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)
@ -1547,7 +1547,7 @@ func TestActionRunName(t *testing.T) {
assert.NotEmpty(t, repo)
// add workflow file to the repo
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -1584,7 +1584,7 @@ jobs:
assert.NotEmpty(t, addWorkflowToBaseResp)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch)

View File

@ -20,7 +20,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/services/convert"
@ -444,7 +443,7 @@ func TestAPIViewPullFilesWithHeadRepoDeleted(t *testing.T) {
forkedRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ForkID: baseRepo.ID, OwnerName: "user1"})
// add a new file to the forked repo
addFileToForkedResp, err := files_service.ChangeRepoFiles(git.DefaultContext, forkedRepo, user1, &files_service.ChangeRepoFilesOptions{
addFileToForkedResp, err := files_service.ChangeRepoFiles(t.Context(), forkedRepo, user1, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -490,7 +489,7 @@ func TestAPIViewPullFilesWithHeadRepoDeleted(t *testing.T) {
}
prOpts := &pull_service.NewPullRequestOptions{Repo: baseRepo, Issue: pullIssue, PullRequest: pullRequest}
err = pull_service.NewPullRequest(git.DefaultContext, prOpts)
err = pull_service.NewPullRequest(t.Context(), prOpts)
assert.NoError(t, err)
pr := convert.ToAPIPullRequest(t.Context(), pullRequest, user1)

View File

@ -17,7 +17,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/tests"
@ -110,7 +109,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
@ -162,7 +161,7 @@ func TestAPICreateProtectedTagRelease(t *testing.T) {
session := loginUser(t, writer.LowerName)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()
@ -198,7 +197,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()

View File

@ -4,16 +4,17 @@
package integration
import (
"context"
"strings"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
files_service "code.gitea.io/gitea/services/repository/files"
)
func createFileInBranch(user *user_model.User, repo *repo_model.Repository, treePath, branchName, content string) (*api.FilesResponse, error) {
ctx := context.TODO()
opts := &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
@ -26,10 +27,11 @@ func createFileInBranch(user *user_model.User, repo *repo_model.Repository, tree
Author: nil,
Committer: nil,
}
return files_service.ChangeRepoFiles(git.DefaultContext, repo, user, opts)
return files_service.ChangeRepoFiles(ctx, repo, user, opts)
}
func deleteFileInBranch(user *user_model.User, repo *repo_model.Repository, treePath, branchName string) (*api.FilesResponse, error) {
ctx := context.TODO()
opts := &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
@ -41,7 +43,7 @@ func deleteFileInBranch(user *user_model.User, repo *repo_model.Repository, tree
Author: nil,
Committer: nil,
}
return files_service.ChangeRepoFiles(git.DefaultContext, repo, user, opts)
return files_service.ChangeRepoFiles(ctx, repo, user, opts)
}
func createOrReplaceFileInBranch(user *user_model.User, repo *repo_model.Repository, treePath, branchName, content string) error {

View File

@ -13,7 +13,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
@ -43,7 +42,7 @@ func TestAPIGetRequestedFiles(t *testing.T) {
session = loginUser(t, user4.Name)
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo1)
assert.NoError(t, err)
defer gitRepo.Close()
lastCommit, _ := gitRepo.GetCommitByPath("README.md")

View File

@ -14,7 +14,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -75,13 +74,13 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo1)
assert.NoError(t, err)
defer gitRepo.Close()
// Make a new branch in repo1
newBranch := "test_branch"
err = repo_service.CreateNewBranch(git.DefaultContext, user2, repo1, gitRepo, repo1.DefaultBranch, newBranch)
err = repo_service.CreateNewBranch(t.Context(), user2, repo1, gitRepo, repo1.DefaultBranch, newBranch)
assert.NoError(t, err)
commitID, _ := gitRepo.GetBranchCommitID(repo1.DefaultBranch)

View File

@ -15,7 +15,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -80,13 +79,13 @@ func testAPIGetContents(t *testing.T, u *url.URL) {
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository)
// Get the commit ID of the default branch
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo1)
require.NoError(t, err)
defer gitRepo.Close()
// Make a new branch in repo1
newBranch := "test_branch"
err = repo_service.CreateNewBranch(git.DefaultContext, user2, repo1, gitRepo, repo1.DefaultBranch, newBranch)
err = repo_service.CreateNewBranch(t.Context(), user2, repo1, gitRepo, repo1.DefaultBranch, newBranch)
require.NoError(t, err)
commitID, err := gitRepo.GetBranchCommitID(repo1.DefaultBranch)

View File

@ -30,10 +30,10 @@ func TestAPIGitTags(t *testing.T) {
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository)
// Set up git config for the tagger
_ = git.NewCommand("config", "user.name").AddDynamicArguments(user.Name).Run(git.DefaultContext, &git.RunOpts{Dir: repo.RepoPath()})
_ = git.NewCommand("config", "user.email").AddDynamicArguments(user.Email).Run(git.DefaultContext, &git.RunOpts{Dir: repo.RepoPath()})
_ = git.NewCommand("config", "user.name").AddDynamicArguments(user.Name).Run(t.Context(), &git.RunOpts{Dir: repo.RepoPath()})
_ = git.NewCommand("config", "user.email").AddDynamicArguments(user.Email).Run(t.Context(), &git.RunOpts{Dir: repo.RepoPath()})
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit("master")

View File

@ -187,7 +187,7 @@ func testEditorWebGitCommitEmail(t *testing.T) {
require.True(t, user.KeepEmailPrivate)
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gitRepo, _ := git.OpenRepository(git.DefaultContext, repo1.RepoPath())
gitRepo, _ := git.OpenRepository(t.Context(), repo1.RepoPath())
defer gitRepo.Close()
getLastCommit := func(t *testing.T) *git.Commit {
c, err := gitRepo.GetBranchCommit("master")

View File

@ -4,6 +4,7 @@
package integration
import (
"context"
"encoding/hex"
"fmt"
"io"
@ -193,14 +194,14 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string, sizes ...int) (pushedFil
t.Run("CommitAndPushLFS", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
prefix := "lfs-data-file-"
err := git.NewCommand("lfs").AddArguments("install").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err := git.NewCommand("lfs").AddArguments("install").Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
_, _, err = git.NewCommand("lfs").AddArguments("track").AddDynamicArguments(prefix+"*").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("lfs").AddArguments("track").AddDynamicArguments(prefix+"*").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
err = git.AddChanges(dstPath, false, ".gitattributes")
err = git.AddChanges(t.Context(), dstPath, false, ".gitattributes")
assert.NoError(t, err)
err = git.CommitChangesWithArgs(dstPath, git.AllowLFSFiltersArgs(), git.CommitChangesOptions{
err = git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: "user2@example.com",
Name: "User Two",
@ -311,25 +312,25 @@ func lockTest(t *testing.T, repoPath string) {
}
func lockFileTest(t *testing.T, filename, repoPath string) {
_, _, err := git.NewCommand("lfs").AddArguments("locks").RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
_, _, err := git.NewCommand("lfs").AddArguments("locks").RunStdString(t.Context(), &git.RunOpts{Dir: repoPath})
assert.NoError(t, err)
_, _, err = git.NewCommand("lfs").AddArguments("lock").AddDynamicArguments(filename).RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
_, _, err = git.NewCommand("lfs").AddArguments("lock").AddDynamicArguments(filename).RunStdString(t.Context(), &git.RunOpts{Dir: repoPath})
assert.NoError(t, err)
_, _, err = git.NewCommand("lfs").AddArguments("locks").RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
_, _, err = git.NewCommand("lfs").AddArguments("locks").RunStdString(t.Context(), &git.RunOpts{Dir: repoPath})
assert.NoError(t, err)
_, _, err = git.NewCommand("lfs").AddArguments("unlock").AddDynamicArguments(filename).RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath})
_, _, err = git.NewCommand("lfs").AddArguments("unlock").AddDynamicArguments(filename).RunStdString(t.Context(), &git.RunOpts{Dir: repoPath})
assert.NoError(t, err)
}
func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
name, err := generateCommitWithNewData(t.Context(), size, repoPath, "user2@example.com", "User Two", prefix)
assert.NoError(t, err)
_, _, err = git.NewCommand("push", "origin", "master").RunStdString(git.DefaultContext, &git.RunOpts{Dir: repoPath}) // Push
_, _, err = git.NewCommand("push", "origin", "master").RunStdString(t.Context(), &git.RunOpts{Dir: repoPath}) // Push
assert.NoError(t, err)
return name
}
func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
func generateCommitWithNewData(ctx context.Context, size int, repoPath, email, fullName, prefix string) (string, error) {
tmpFile, err := os.CreateTemp(repoPath, prefix)
if err != nil {
return "", err
@ -345,13 +346,11 @@ func generateCommitWithNewData(size int, repoPath, email, fullName, prefix strin
_ = tmpFile.Close()
// Commit
// Now here we should explicitly allow lfs filters to run
globalArgs := git.AllowLFSFiltersArgs()
err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
err = git.AddChanges(ctx, repoPath, false, filepath.Base(tmpFile.Name()))
if err != nil {
return "", err
}
err = git.CommitChangesWithArgs(repoPath, globalArgs, git.CommitChangesOptions{
err = git.CommitChanges(ctx, repoPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: email,
Name: fullName,
@ -381,14 +380,14 @@ func doCreateProtectedBranch(baseCtx *APITestContext, dstPath string) func(t *te
// push a new branch with a new unprotected file
t.Run("CreateProtectedBranch-UnprotectedFile", doGitCreateBranch(dstPath, "release-v2.0"))
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "abc.txt")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "abc.txt")
assert.NoError(t, err)
t.Run("PushProtectedBranch-UnprotectedFile", doGitPushTestRepository(dstPath, "origin", "release-v2.0"))
t.Run("CheckoutMaster-UnprotectedFile", doGitCheckoutBranch(dstPath, "master"))
// push a new branch with a new protected file
t.Run("CreateProtectedBranch-ProtectedFile", doGitCreateBranch(dstPath, "release-v3.0"))
_, err = generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "config")
_, err = generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "config")
assert.NoError(t, err)
t.Run("PushProtectedBranch-ProtectedFile", doGitPushTestRepositoryFail(dstPath, "origin", "release-v3.0"))
t.Run("CheckoutMaster-ProtectedFile", doGitCheckoutBranch(dstPath, "master"))
@ -408,7 +407,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
// Try to push without permissions, which should fail
t.Run("TryPushWithoutPermissions", func(t *testing.T) {
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
assert.NoError(t, err)
doGitPushTestRepositoryFail(dstPath, "origin", "protected")(t)
})
@ -418,7 +417,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
// Normal push should work
t.Run("NormalPushWithPermissions", func(t *testing.T) {
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
assert.NoError(t, err)
doGitPushTestRepository(dstPath, "origin", "protected")(t)
})
@ -426,8 +425,8 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
// Try to force push without force push permissions, which should fail
t.Run("ForcePushWithoutForcePermissions", func(t *testing.T) {
t.Run("CreateDivergentHistory", func(t *testing.T) {
git.NewCommand("reset", "--hard", "HEAD~1").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-new")
git.NewCommand("reset", "--hard", "HEAD~1").Run(t.Context(), &git.RunOpts{Dir: dstPath})
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-new")
assert.NoError(t, err)
})
doGitPushTestRepositoryFail(dstPath, "-f", "origin", "protected")(t)
@ -454,7 +453,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
assert.NoError(t, err)
})
t.Run("GenerateCommit", func(t *testing.T) {
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
assert.NoError(t, err)
})
t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected-2"))
@ -469,7 +468,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
t.Run("ProtectProtectedBranchUnprotectedFilePaths", doProtectBranch(ctx, "protected", "", "", "unprotected-file-*", ""))
t.Run("GenerateCommit", func(t *testing.T) {
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "unprotected-file-")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "unprotected-file-")
assert.NoError(t, err)
})
t.Run("PushUnprotectedFilesToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
@ -479,7 +478,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
t.Run("CheckoutMaster", doGitCheckoutBranch(dstPath, "master"))
t.Run("CreateBranchForced", doGitCreateBranch(dstPath, "toforce"))
t.Run("GenerateCommit", func(t *testing.T) {
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
assert.NoError(t, err)
})
t.Run("FailToForcePushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected"))
@ -716,7 +715,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
t.Run("CheckoutProtected", doGitCheckoutBranch(dstPath, "protected"))
t.Run("PullProtected", doGitPull(dstPath, "origin", "protected"))
t.Run("GenerateCommit", func(t *testing.T) {
_, err := generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
_, err := generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
assert.NoError(t, err)
})
t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected3"))
@ -807,7 +806,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
return
}
gitRepo, err := git.OpenRepository(git.DefaultContext, dstPath)
gitRepo, err := git.OpenRepository(t.Context(), dstPath)
require.NoError(t, err)
defer gitRepo.Close()
@ -827,10 +826,10 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666)
require.NoError(t, err)
err = git.AddChanges(dstPath, true)
err = git.AddChanges(t.Context(), dstPath, true)
assert.NoError(t, err)
err = git.CommitChanges(dstPath, git.CommitChangesOptions{
err = git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: "user2@example.com",
Name: "user2",
@ -849,7 +848,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
})
t.Run("Push", func(t *testing.T) {
err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic="+headBranch).Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic="+headBranch).Run(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+1)
@ -867,7 +866,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
assert.Contains(t, "Testing commit 1", prMsg.Body)
assert.Equal(t, commit, prMsg.Head.Sha)
_, _, err = git.NewCommand("push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/"+headBranch).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/"+headBranch).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2)
@ -893,10 +892,10 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666)
require.NoError(t, err)
err = git.AddChanges(dstPath, true)
err = git.AddChanges(t.Context(), dstPath, true)
assert.NoError(t, err)
err = git.CommitChanges(dstPath, git.CommitChangesOptions{
err = git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: "user2@example.com",
Name: "user2",
@ -915,7 +914,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
})
t.Run("Push2", func(t *testing.T) {
err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic="+headBranch).Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic="+headBranch).Run(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2)
@ -925,7 +924,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string
assert.False(t, prMsg.HasMerged)
assert.Equal(t, commit, prMsg.Head.Sha)
_, _, err = git.NewCommand("push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/"+headBranch).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/"+headBranch).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2)

View File

@ -88,7 +88,7 @@ func onGiteaRun[T testing.TB](t T, callback func(T, *url.URL)) {
func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
return func(t *testing.T) {
assert.NoError(t, git.CloneWithArgs(t.Context(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{}))
assert.NoError(t, git.Clone(t.Context(), u.String(), dstLocalPath, git.CloneRepoOptions{}))
exist, err := util.IsExist(filepath.Join(dstLocalPath, "README.md"))
assert.NoError(t, err)
assert.True(t, exist)
@ -97,7 +97,7 @@ func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
func doPartialGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
return func(t *testing.T) {
assert.NoError(t, git.CloneWithArgs(t.Context(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{
assert.NoError(t, git.Clone(t.Context(), u.String(), dstLocalPath, git.CloneRepoOptions{
Filter: "blob:none",
}))
exist, err := util.IsExist(filepath.Join(dstLocalPath, "README.md"))
@ -109,7 +109,7 @@ func doPartialGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
func doGitCloneFail(u *url.URL) func(*testing.T) {
return func(t *testing.T) {
tmpDir := t.TempDir()
assert.Error(t, git.Clone(git.DefaultContext, u.String(), tmpDir, git.CloneRepoOptions{}))
assert.Error(t, git.Clone(t.Context(), u.String(), tmpDir, git.CloneRepoOptions{}))
exist, err := util.IsExist(filepath.Join(tmpDir, "README.md"))
assert.NoError(t, err)
assert.False(t, exist)
@ -119,18 +119,18 @@ func doGitCloneFail(u *url.URL) func(*testing.T) {
func doGitInitTestRepository(dstPath string) func(*testing.T) {
return func(t *testing.T) {
// Init repository in dstPath
assert.NoError(t, git.InitRepository(git.DefaultContext, dstPath, false, git.Sha1ObjectFormat.Name()))
assert.NoError(t, git.InitRepository(t.Context(), dstPath, false, git.Sha1ObjectFormat.Name()))
// forcibly set default branch to master
_, _, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte("# Testing Repository\n\nOriginally created in: "+dstPath), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
assert.NoError(t, git.AddChanges(t.Context(), dstPath, true))
signature := git.Signature{
Email: "test@example.com",
Name: "test",
When: time.Now(),
}
assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{
assert.NoError(t, git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
Message: "Initial Commit",
@ -140,21 +140,21 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommand("remote", "add").AddDynamicArguments(remoteName, u.String()).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("remote", "add").AddDynamicArguments(remoteName, u.String()).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
}
}
func doGitPushTestRepository(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommand("push", "-u").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("push", "-u").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
}
}
func doGitPushTestRepositoryFail(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommand("push").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("push").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.Error(t, err)
}
}
@ -164,12 +164,12 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) {
doGitCheckoutBranch(dstPath, branch)(t)
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte("file "+branch), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
assert.NoError(t, git.AddChanges(t.Context(), dstPath, true))
signature := git.Signature{
Email: "test@test.test",
Name: "test",
}
assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{
assert.NoError(t, git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
Message: "update " + branch,
@ -179,28 +179,28 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) {
func doGitCreateBranch(dstPath, branch string) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommand("checkout", "-b").AddDynamicArguments(branch).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("checkout", "-b").AddDynamicArguments(branch).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
}
}
func doGitCheckoutBranch(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommandNoGlobals(git.AllowLFSFiltersArgs()...).AddArguments("checkout").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand().AddArguments("checkout").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
}
}
func doGitMerge(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommand("merge").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("merge").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
}
}
func doGitPull(dstPath string, args ...string) func(*testing.T) {
return func(t *testing.T) {
_, _, err := git.NewCommandNoGlobals(git.AllowLFSFiltersArgs()...).AddArguments("pull").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand().AddArguments("pull").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
}
}

View File

@ -97,14 +97,14 @@ func TestAgitPullPush(t *testing.T) {
doGitCreateBranch(dstPath, "test-agit-push")
// commit 1
_, err = generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
_, err = generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-")
assert.NoError(t, err)
// push to create an agit pull request
err = git.NewCommand("push", "origin",
"-o", "title=test-title", "-o", "description=test-description",
"HEAD:refs/for/master/test-agit-push",
).Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
).Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// check pull request exist
@ -114,24 +114,24 @@ func TestAgitPullPush(t *testing.T) {
assert.Equal(t, "test-description", pr.Issue.Content)
// commit 2
_, err = generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-2-")
_, err = generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "branch-data-file-2-")
assert.NoError(t, err)
// push 2
err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-push").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-push").Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// reset to first commit
err = git.NewCommand("reset", "--hard", "HEAD~1").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err = git.NewCommand("reset", "--hard", "HEAD~1").Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// test force push without confirm
_, stderr, err := git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-push").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, stderr, err := git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-push").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.Error(t, err)
assert.Contains(t, stderr, "[remote rejected] HEAD -> refs/for/master/test-agit-push (request `force-push` push option)")
// test force push with confirm
err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-push", "-o", "force-push").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-push", "-o", "force-push").Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
})
}
@ -153,14 +153,14 @@ func TestAgitReviewStaleness(t *testing.T) {
doGitCreateBranch(dstPath, "test-agit-review")
// Create initial commit
_, err = generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "initial-")
_, err = generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "initial-")
assert.NoError(t, err)
// create PR via agit
err = git.NewCommand("push", "origin",
"-o", "title=Test agit Review Staleness", "-o", "description=Testing review staleness",
"HEAD:refs/for/master/test-agit-review",
).Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
).Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{
@ -197,10 +197,10 @@ func TestAgitReviewStaleness(t *testing.T) {
assert.False(t, reviews[0].Stale, "Review should not be stale initially")
// Create a new commit and update the agit PR
_, err = generateCommitWithNewData(testFileSizeSmall, dstPath, "user2@example.com", "User Two", "updated-")
_, err = generateCommitWithNewData(t.Context(), testFileSizeSmall, dstPath, "user2@example.com", "User Two", "updated-")
assert.NoError(t, err)
err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-review").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test-agit-review").Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// Reload PR to get updated commit ID

View File

@ -162,7 +162,7 @@ func runTestGitPush(t *testing.T, u *url.URL, gitOperation func(t *testing.T, gi
doGitAddRemote(gitPath, "origin", u)(t)
gitRepo, err := git.OpenRepository(git.DefaultContext, gitPath)
gitRepo, err := git.OpenRepository(t.Context(), gitPath)
require.NoError(t, err)
defer gitRepo.Close()
@ -205,7 +205,7 @@ func TestPushPullRefs(t *testing.T) {
doGitClone(dstPath, u)(t)
cmd := git.NewCommand("push", "--delete", "origin", "refs/pull/2/head")
stdout, stderr, err := cmd.RunStdString(git.DefaultContext, &git.RunOpts{
stdout, stderr, err := cmd.RunStdString(t.Context(), &git.RunOpts{
Dir: dstPath,
})
assert.Error(t, err)

View File

@ -14,7 +14,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/indexer/stats"
"code.gitea.io/gitea/modules/queue"
repo_service "code.gitea.io/gitea/services/repository"
@ -237,7 +236,7 @@ func TestLinguist(t *testing.T) {
f.Operation = "create"
}
_, err = files_service.ChangeRepoFiles(git.DefaultContext, repo, user, &files_service.ChangeRepoFilesOptions{
_, err = files_service.ChangeRepoFiles(t.Context(), repo, user, &files_service.ChangeRepoFilesOptions{
Files: files,
OldBranch: repo.DefaultBranch,
NewBranch: repo.DefaultBranch,

View File

@ -250,7 +250,7 @@ func restoreOldDB(t *testing.T, version string) {
func wrappedMigrate(ctx context.Context, x *xorm.Engine) error {
currentEngine = x
return migrations.Migrate(x)
return migrations.Migrate(ctx, x)
}
func doMigrationTest(t *testing.T, version string) {

View File

@ -12,7 +12,6 @@ import (
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/migration"
mirror_service "code.gitea.io/gitea/services/mirror"
@ -61,7 +60,7 @@ func TestMirrorPull(t *testing.T) {
assert.True(t, slices.ContainsFunc(mirrorRepo.Units, func(u *repo_model.RepoUnit) bool { return u.Type == unit.TypeReleases }))
assert.True(t, slices.ContainsFunc(mirrorRepo.Units, func(u *repo_model.RepoUnit) bool { return u.Type == unit.TypeWiki }))
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo)
assert.NoError(t, err)
defer gitRepo.Close()

View File

@ -15,7 +15,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/services/migrations"
@ -55,14 +54,14 @@ func testMirrorPush(t *testing.T, u *url.URL) {
ok := mirror_service.SyncPushMirror(t.Context(), mirrors[0].ID)
assert.True(t, ok)
srcGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, srcRepo)
srcGitRepo, err := gitrepo.OpenRepository(t.Context(), srcRepo)
assert.NoError(t, err)
defer srcGitRepo.Close()
srcCommit, err := srcGitRepo.GetBranchCommit("master")
assert.NoError(t, err)
mirrorGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, mirrorRepo)
mirrorGitRepo, err := gitrepo.OpenRepository(t.Context(), mirrorRepo)
assert.NoError(t, err)
defer mirrorGitRepo.Close()

View File

@ -265,7 +265,7 @@ func TestCreateAgitPullWithReadPermission(t *testing.T) {
t.Run("add commit", doGitAddSomeCommits(dstPath, "master"))
t.Run("do agit pull create", func(t *testing.T) {
err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic="+"test-topic").Run(git.DefaultContext, &git.RunOpts{Dir: dstPath})
err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic="+"test-topic").Run(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
})
})

View File

@ -264,7 +264,7 @@ func TestCantMergeConflict(t *testing.T) {
BaseBranch: "base",
})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo1)
assert.NoError(t, err)
err = pull_service.Merge(t.Context(), pr, user1, gitRepo, repo_model.MergeStyleMerge, "", "CONFLICT", false)
@ -295,12 +295,12 @@ func TestCantMergeUnrelated(t *testing.T) {
})
path := repo_model.RepoPath(user1.Name, repo1.Name)
err := git.NewCommand("read-tree", "--empty").Run(git.DefaultContext, &git.RunOpts{Dir: path})
err := git.NewCommand("read-tree", "--empty").Run(t.Context(), &git.RunOpts{Dir: path})
assert.NoError(t, err)
stdin := strings.NewReader("Unrelated File")
var stdout strings.Builder
err = git.NewCommand("hash-object", "-w", "--stdin").Run(git.DefaultContext, &git.RunOpts{
err = git.NewCommand("hash-object", "-w", "--stdin").Run(t.Context(), &git.RunOpts{
Dir: path,
Stdin: stdin,
Stdout: &stdout,
@ -309,10 +309,10 @@ func TestCantMergeUnrelated(t *testing.T) {
assert.NoError(t, err)
sha := strings.TrimSpace(stdout.String())
_, _, err = git.NewCommand("update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments("100644", sha, "somewher-over-the-rainbow").RunStdString(git.DefaultContext, &git.RunOpts{Dir: path})
_, _, err = git.NewCommand("update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments("100644", sha, "somewher-over-the-rainbow").RunStdString(t.Context(), &git.RunOpts{Dir: path})
assert.NoError(t, err)
treeSha, _, err := git.NewCommand("write-tree").RunStdString(git.DefaultContext, &git.RunOpts{Dir: path})
treeSha, _, err := git.NewCommand("write-tree").RunStdString(t.Context(), &git.RunOpts{Dir: path})
assert.NoError(t, err)
treeSha = strings.TrimSpace(treeSha)
@ -333,7 +333,7 @@ func TestCantMergeUnrelated(t *testing.T) {
stdout.Reset()
err = git.NewCommand("commit-tree").AddDynamicArguments(treeSha).
Run(git.DefaultContext, &git.RunOpts{
Run(t.Context(), &git.RunOpts{
Env: env,
Dir: path,
Stdin: messageBytes,
@ -342,7 +342,7 @@ func TestCantMergeUnrelated(t *testing.T) {
assert.NoError(t, err)
commitSha := strings.TrimSpace(stdout.String())
_, _, err = git.NewCommand("branch", "unrelated").AddDynamicArguments(commitSha).RunStdString(git.DefaultContext, &git.RunOpts{Dir: path})
_, _, err = git.NewCommand("branch", "unrelated").AddDynamicArguments(commitSha).RunStdString(t.Context(), &git.RunOpts{Dir: path})
assert.NoError(t, err)
testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n")
@ -357,7 +357,7 @@ func TestCantMergeUnrelated(t *testing.T) {
session.MakeRequest(t, req, http.StatusCreated)
// Now this PR could be marked conflict - or at least a race may occur - so drop down to pure code at this point...
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1)
gitRepo, err := gitrepo.OpenRepository(t.Context(), repo1)
assert.NoError(t, err)
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{
HeadRepoID: repo1.ID,
@ -403,7 +403,7 @@ func TestFastForwardOnlyMerge(t *testing.T) {
BaseBranch: "master",
})
gitRepo, err := git.OpenRepository(git.DefaultContext, repo_model.RepoPath(user1.Name, repo1.Name))
gitRepo, err := git.OpenRepository(t.Context(), repo_model.RepoPath(user1.Name, repo1.Name))
assert.NoError(t, err)
err = pull_service.Merge(t.Context(), pr, user1, gitRepo, repo_model.MergeStyleFastForwardOnly, "", "FAST-FORWARD-ONLY", false)
@ -445,7 +445,7 @@ func TestCantFastForwardOnlyMergeDiverging(t *testing.T) {
BaseBranch: "master",
})
gitRepo, err := git.OpenRepository(git.DefaultContext, repo_model.RepoPath(user1.Name, repo1.Name))
gitRepo, err := git.OpenRepository(t.Context(), repo_model.RepoPath(user1.Name, repo1.Name))
assert.NoError(t, err)
err = pull_service.Merge(t.Context(), pr, user1, gitRepo, repo_model.MergeStyleFastForwardOnly, "", "DIVERGING", false)
@ -473,7 +473,7 @@ func TestConflictChecking(t *testing.T) {
assert.NotEmpty(t, baseRepo)
// create a commit on new branch.
_, err = files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, user, &files_service.ChangeRepoFilesOptions{
_, err = files_service.ChangeRepoFiles(t.Context(), baseRepo, user, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -488,7 +488,7 @@ func TestConflictChecking(t *testing.T) {
assert.NoError(t, err)
// create a commit on main branch.
_, err = files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, user, &files_service.ChangeRepoFilesOptions{
_, err = files_service.ChangeRepoFiles(t.Context(), baseRepo, user, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -521,7 +521,7 @@ func TestConflictChecking(t *testing.T) {
Type: issues_model.PullRequestGitea,
}
prOpts := &pull_service.NewPullRequestOptions{Repo: baseRepo, Issue: pullIssue, PullRequest: pullRequest}
err = pull_service.NewPullRequest(git.DefaultContext, prOpts)
err = pull_service.NewPullRequest(t.Context(), prOpts)
assert.NoError(t, err)
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "PR with conflict!"})
@ -906,10 +906,10 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666)
assert.NoError(t, err)
err = git.AddChanges(dstPath, true)
err = git.AddChanges(t.Context(), dstPath, true)
assert.NoError(t, err)
err = git.CommitChanges(dstPath, git.CommitChangesOptions{
err = git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: "user2@example.com",
Name: "user2",
@ -932,7 +932,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
AddDynamicArguments(`title="create a test pull request with agit"`).
AddArguments("-o").
AddDynamicArguments(`description="This PR is a test pull request which created with agit"`).
Run(git.DefaultContext, &git.RunOpts{Dir: dstPath, Stderr: stderrBuf})
Run(t.Context(), &git.RunOpts{Dir: dstPath, Stderr: stderrBuf})
assert.NoError(t, err)
assert.Contains(t, stderrBuf.String(), setting.AppURL+"user2/repo1/pulls/6")

View File

@ -15,7 +15,6 @@ import (
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
pull_service "code.gitea.io/gitea/services/pull"
repo_service "code.gitea.io/gitea/services/repository"
files_service "code.gitea.io/gitea/services/repository/files"
@ -31,7 +30,7 @@ func TestAPIPullUpdate(t *testing.T) {
pr := createOutdatedPR(t, user, org26)
// Test GetDiverging
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
diffCount, err := pull_service.GetDiverging(t.Context(), pr)
assert.NoError(t, err)
assert.Equal(t, 1, diffCount.Behind)
assert.Equal(t, 1, diffCount.Ahead)
@ -45,7 +44,7 @@ func TestAPIPullUpdate(t *testing.T) {
session.MakeRequest(t, req, http.StatusOK)
// Test GetDiverging after update
diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr)
diffCount, err = pull_service.GetDiverging(t.Context(), pr)
assert.NoError(t, err)
assert.Equal(t, 0, diffCount.Behind)
assert.Equal(t, 2, diffCount.Ahead)
@ -60,7 +59,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
pr := createOutdatedPR(t, user, org26)
// Test GetDiverging
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
diffCount, err := pull_service.GetDiverging(t.Context(), pr)
assert.NoError(t, err)
assert.Equal(t, 1, diffCount.Behind)
assert.Equal(t, 1, diffCount.Ahead)
@ -74,7 +73,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
session.MakeRequest(t, req, http.StatusOK)
// Test GetDiverging after update
diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr)
diffCount, err = pull_service.GetDiverging(t.Context(), pr)
assert.NoError(t, err)
assert.Equal(t, 0, diffCount.Behind)
assert.Equal(t, 1, diffCount.Ahead)
@ -94,7 +93,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod
assert.NoError(t, err)
assert.NotEmpty(t, baseRepo)
headRepo, err := repo_service.ForkRepository(git.DefaultContext, actor, forkOrg, repo_service.ForkRepoOptions{
headRepo, err := repo_service.ForkRepository(t.Context(), actor, forkOrg, repo_service.ForkRepoOptions{
BaseRepo: baseRepo,
Name: "repo-pr-update",
Description: "desc",
@ -103,7 +102,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod
assert.NotEmpty(t, headRepo)
// create a commit on base Repo
_, err = files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, actor, &files_service.ChangeRepoFilesOptions{
_, err = files_service.ChangeRepoFiles(t.Context(), baseRepo, actor, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -130,7 +129,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod
assert.NoError(t, err)
// create a commit on head Repo
_, err = files_service.ChangeRepoFiles(git.DefaultContext, headRepo, actor, &files_service.ChangeRepoFilesOptions{
_, err = files_service.ChangeRepoFiles(t.Context(), headRepo, actor, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",
@ -174,7 +173,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod
Type: issues_model.PullRequestGitea,
}
prOpts := &pull_service.NewPullRequestOptions{Repo: baseRepo, Issue: pullIssue, PullRequest: pullRequest}
err = pull_service.NewPullRequest(git.DefaultContext, prOpts)
err = pull_service.NewPullRequest(t.Context(), prOpts)
assert.NoError(t, err)
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "Test Pull -to-update-"})

View File

@ -33,14 +33,14 @@ func TestCreateNewTagProtected(t *testing.T) {
t.Run("Code", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
err := release.CreateNewTag(git.DefaultContext, owner, repo, "master", "t-first", "first tag")
err := release.CreateNewTag(t.Context(), owner, repo, "master", "t-first", "first tag")
assert.NoError(t, err)
err = release.CreateNewTag(git.DefaultContext, owner, repo, "master", "v-2", "second tag")
err = release.CreateNewTag(t.Context(), owner, repo, "master", "v-2", "second tag")
assert.Error(t, err)
assert.True(t, release.IsErrProtectedTagName(err))
err = release.CreateNewTag(git.DefaultContext, owner, repo, "master", "v-1.1", "third tag")
err = release.CreateNewTag(t.Context(), owner, repo, "master", "v-1.1", "third tag")
assert.NoError(t, err)
})
@ -55,10 +55,10 @@ func TestCreateNewTagProtected(t *testing.T) {
doGitClone(dstPath, u)(t)
_, _, err := git.NewCommand("tag", "v-2").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("tag", "v-2").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
_, _, err = git.NewCommand("push", "--tags").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "--tags").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.Error(t, err)
assert.Contains(t, err.Error(), "Tag v-2 is protected")
})
@ -75,20 +75,20 @@ func TestCreateNewTagProtected(t *testing.T) {
doGitClone(dstPath, u)(t)
_, _, err := git.NewCommand("tag", "v-1.1", "-m", "force update", "--force").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("tag", "v-1.1", "-m", "force update", "--force").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
_, _, err = git.NewCommand("push", "--tags").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "--tags").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
_, _, err = git.NewCommand("tag", "v-1.1", "-m", "force update v2", "--force").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("tag", "v-1.1", "-m", "force update v2", "--force").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
_, _, err = git.NewCommand("push", "--tags").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "--tags").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.Error(t, err)
assert.Contains(t, err.Error(), "the tag already exists in the remote")
_, _, err = git.NewCommand("push", "--tags", "--force").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "--tags", "--force").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
require.NoError(t, err)
req := NewRequestf(t, "GET", "/%s/releases/tag/v-1.1", repo.FullName())
resp := MakeRequest(t, req, http.StatusOK)
@ -137,15 +137,15 @@ func TestRepushTag(t *testing.T) {
doGitClone(dstPath, u)(t)
// create and push a tag
_, _, err := git.NewCommand("tag", "v2.0").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand("tag", "v2.0").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
_, _, err = git.NewCommand("push", "origin", "--tags", "v2.0").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "origin", "--tags", "v2.0").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// create a release for the tag
createdRelease := createNewReleaseUsingAPI(t, token, owner, repo, "v2.0", "", "Release of v2.0", "desc")
assert.False(t, createdRelease.IsDraft)
// delete the tag
_, _, err = git.NewCommand("push", "origin", "--delete", "v2.0").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "origin", "--delete", "v2.0").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// query the release by API and it should be a draft
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0"))
@ -154,7 +154,7 @@ func TestRepushTag(t *testing.T) {
DecodeJSON(t, resp, &respRelease)
assert.True(t, respRelease.IsDraft)
// re-push the tag
_, _, err = git.NewCommand("push", "origin", "--tags", "v2.0").RunStdString(git.DefaultContext, &git.RunOpts{Dir: dstPath})
_, _, err = git.NewCommand("push", "origin", "--tags", "v2.0").RunStdString(t.Context(), &git.RunOpts{Dir: dstPath})
assert.NoError(t, err)
// query the release by API and it should not be a draft
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0"))

View File

@ -18,7 +18,6 @@ import (
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/util"
@ -527,7 +526,7 @@ func TestGenerateRepository(t *testing.T) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo44 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 44})
generatedRepo, err := repo_service.GenerateRepository(git.DefaultContext, user2, user2, repo44, repo_service.GenerateRepoOptions{
generatedRepo, err := repo_service.GenerateRepository(t.Context(), user2, user2, repo44, repo_service.GenerateRepoOptions{
Name: "generated-from-template-44",
GitContent: true,
})

View File

@ -407,11 +407,11 @@ func TestChangeRepoFilesForCreate(t *testing.T) {
opts := getCreateRepoFilesOptions(repo)
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
// asserts
assert.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
commitID, _ := gitRepo.GetBranchCommitID(opts.NewBranch)
@ -444,11 +444,11 @@ func TestChangeRepoFilesForUpdate(t *testing.T) {
opts := getUpdateRepoFilesOptions(repo)
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
// asserts
assert.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(opts.NewBranch)
@ -480,11 +480,11 @@ func TestChangeRepoFilesForUpdateWithFileMove(t *testing.T) {
opts.Files[0].TreePath = "README_new.md" // new file name, README_new.md
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
// asserts
assert.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(opts.NewBranch)
@ -526,11 +526,11 @@ func TestChangeRepoFilesForUpdateWithFileRename(t *testing.T) {
opts := getUpdateRepoFilesRenameOptions(repo)
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, ctx.Doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, ctx.Doer, opts)
// asserts
assert.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(repo.DefaultBranch)
@ -563,11 +563,11 @@ func TestChangeRepoFilesWithoutBranchNames(t *testing.T) {
opts.NewBranch = ""
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
// asserts
assert.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
gitRepo, _ := gitrepo.OpenRepository(t.Context(), repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(repo.DefaultBranch)
@ -596,7 +596,7 @@ func testDeleteRepoFiles(t *testing.T, u *url.URL) {
opts := getDeleteRepoFilesOptions(repo)
t.Run("Delete README.md file", func(t *testing.T) {
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepoFilesDelete()
assert.NotNil(t, filesResponse)
@ -608,7 +608,7 @@ func testDeleteRepoFiles(t *testing.T, u *url.URL) {
})
t.Run("Verify README.md has been deleted", func(t *testing.T) {
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Nil(t, filesResponse)
expectedError := "repository file does not exist [path: " + opts.Files[0].TreePath + "]"
assert.EqualError(t, err, expectedError)
@ -638,7 +638,7 @@ func testDeleteRepoFilesWithoutBranchNames(t *testing.T, u *url.URL) {
opts.NewBranch = ""
t.Run("Delete README.md without Branch Name", func(t *testing.T) {
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepoFilesDelete()
assert.NotNil(t, filesResponse)
@ -667,7 +667,7 @@ func TestChangeRepoFilesErrors(t *testing.T) {
t.Run("bad branch", func(t *testing.T) {
opts := getUpdateRepoFilesOptions(repo)
opts.OldBranch = "bad_branch"
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Error(t, err)
assert.Nil(t, filesResponse)
expectedError := fmt.Sprintf("branch does not exist [repo_id: %d name: %s]", repo.ID, opts.OldBranch)
@ -678,7 +678,7 @@ func TestChangeRepoFilesErrors(t *testing.T) {
opts := getUpdateRepoFilesOptions(repo)
origSHA := opts.Files[0].SHA
opts.Files[0].SHA = "bad_sha"
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Nil(t, filesResponse)
assert.Error(t, err)
expectedError := "sha does not match [given: " + opts.Files[0].SHA + ", expected: " + origSHA + "]"
@ -688,7 +688,7 @@ func TestChangeRepoFilesErrors(t *testing.T) {
t.Run("new branch already exists", func(t *testing.T) {
opts := getUpdateRepoFilesOptions(repo)
opts.NewBranch = "develop"
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Nil(t, filesResponse)
assert.Error(t, err)
expectedError := "branch already exists [name: " + opts.NewBranch + "]"
@ -698,7 +698,7 @@ func TestChangeRepoFilesErrors(t *testing.T) {
t.Run("treePath is empty:", func(t *testing.T) {
opts := getUpdateRepoFilesOptions(repo)
opts.Files[0].TreePath = ""
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Nil(t, filesResponse)
assert.Error(t, err)
expectedError := "path contains a malformed path component [path: ]"
@ -708,7 +708,7 @@ func TestChangeRepoFilesErrors(t *testing.T) {
t.Run("treePath is a git directory:", func(t *testing.T) {
opts := getUpdateRepoFilesOptions(repo)
opts.Files[0].TreePath = ".git"
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Nil(t, filesResponse)
assert.Error(t, err)
expectedError := "path contains a malformed path component [path: " + opts.Files[0].TreePath + "]"
@ -718,7 +718,7 @@ func TestChangeRepoFilesErrors(t *testing.T) {
t.Run("create file that already exists", func(t *testing.T) {
opts := getCreateRepoFilesOptions(repo)
opts.Files[0].TreePath = "README.md" // already exists
fileResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
fileResponse, err := files_service.ChangeRepoFiles(t.Context(), repo, doer, opts)
assert.Nil(t, fileResponse)
assert.Error(t, err)
expectedError := "repository file already exists [path: " + opts.Files[0].TreePath + "]"

View File

@ -28,13 +28,13 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin
func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) {
return func(t *testing.T) {
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), fmt.Appendf(nil, "# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now()), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
assert.NoError(t, git.AddChanges(t.Context(), dstPath, true))
signature := git.Signature{
Email: "test@example.com",
Name: "test",
When: time.Now(),
}
assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{
assert.NoError(t, git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &signature,
Author: &signature,
Message: "Initial Commit",

View File

@ -41,7 +41,7 @@ func TestRepoCloneWiki(t *testing.T) {
u, _ = url.Parse(r)
u.User = url.UserPassword("user2", userPassword)
t.Run("Clone", func(t *testing.T) {
assert.NoError(t, git.CloneWithArgs(t.Context(), git.AllowLFSFiltersArgs(), u.String(), dstPath, git.CloneRepoOptions{}))
assert.NoError(t, git.Clone(t.Context(), u.String(), dstPath, git.CloneRepoOptions{}))
assertFileEqual(t, filepath.Join(dstPath, "Home.md"), []byte("# Home page\n\nThis is the home page!\n"))
assertFileExist(t, filepath.Join(dstPath, "Page-With-Image.md"))
assertFileExist(t, filepath.Join(dstPath, "Page-With-Spaced-Name.md"))