mirror of
https://gitea.com/gitea/tea.git
synced 2026-10-26 19:11:25 +01:00
refactor: add credential and Git packages (#1123)
- `internal/auth`: credentials in the OS keyring or a private file, OAuth login with token refresh, SSH HTTP-signature signers (key files with passphrase prompt, ssh-agent keys and certificates), and the Git credential helper protocol. - `internal/git`: cancellable Git subprocesses, repository and remote discovery (tracked remote via `branch.<name>.remote`), PR checkout by full ref, AGit push, branch cleanup. Nothing imports these packages yet. Reviewed-on: https://gitea.com/gitea/tea/pulls/1123 Reviewed-by: TheFox0x7 <95654+thefox0x7@noreply.gitea.com>
This commit is contained in:
1 parent
2b218a5bae
commit
88b91faa54
28 files changed
+3044
-3
No files matched your search
@@ -0,0 +1,68 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// AgitOptions creates a pull request through Gitea's AGit push convention.
|
||||
type AgitOptions struct {
|
||||
Directory, Remote, Head, Base, Topic, Title, Body string
|
||||
CredentialArgs []string
|
||||
Prompt bool
|
||||
}
|
||||
|
||||
// PushAgitPR pushes head to refs/for/<base>/<topic> with optional title/description options.
|
||||
func PushAgitPR(ctx context.Context, runner Runner, opts AgitOptions) error {
|
||||
if opts.Remote == "" || opts.Head == "" || opts.Base == "" || opts.Topic == "" {
|
||||
return errors.New("AGit pull creation requires remote, head, base, and topic")
|
||||
}
|
||||
if opts.Head == opts.Base || opts.Topic == opts.Base {
|
||||
return fmt.Errorf("cannot create an AGit pull from %s to %s", opts.Topic, opts.Base)
|
||||
}
|
||||
run := func(args ...string) (string, error) {
|
||||
return runner.Output(ctx, opts.Directory, opts.Prompt, args...)
|
||||
}
|
||||
if err := requireWorkTree(run, "AGit pull creation"); err != nil {
|
||||
return err
|
||||
}
|
||||
head := opts.Head
|
||||
if !strings.HasPrefix(head, "refs/") {
|
||||
head = "refs/heads/" + head
|
||||
}
|
||||
refspec := fmt.Sprintf("%s:refs/for/%s/%s", head, opts.Base, opts.Topic)
|
||||
args := append([]string{}, opts.CredentialArgs...)
|
||||
args = append(args, "push")
|
||||
if opts.Title != "" {
|
||||
args = append(args, "-o", "title="+agitPushOption(opts.Title))
|
||||
}
|
||||
if opts.Body != "" {
|
||||
args = append(args, "-o", "description="+agitPushOption(opts.Body))
|
||||
}
|
||||
args = append(args, "--", opts.Remote, refspec)
|
||||
_, err := run(args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func agitPushOption(value string) string {
|
||||
if strings.Contains(value, "\n") || !isASCII(value) {
|
||||
return "{base64}" + base64.StdEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func isASCII(value string) bool {
|
||||
for _, r := range value {
|
||||
if r > unicode.MaxASCII {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPushAgitPREncodesOptionsAndRefspec(t *testing.T) {
|
||||
runner := &checkoutRunner{}
|
||||
err := PushAgitPR(context.Background(), runner, AgitOptions{
|
||||
Directory: "/work", Remote: "origin", Head: "feature", Base: "main", Topic: "feature",
|
||||
Title: "Hello", Body: "line1\nline2", CredentialArgs: []string{"-c", "credential.helper=tea"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{
|
||||
"rev-parse --is-inside-work-tree",
|
||||
"-c credential.helper=tea push -o title=Hello -o description={base64}bGluZTEKbGluZTI= -- origin refs/heads/feature:refs/for/main/feature",
|
||||
}, runner.calls)
|
||||
}
|
||||
|
||||
func TestPushAgitPRRejectsSameBaseAndTopic(t *testing.T) {
|
||||
runner := &checkoutRunner{}
|
||||
err := PushAgitPR(context.Background(), runner, AgitOptions{Directory: "/work", Remote: "origin", Head: "main", Base: "main", Topic: "main"})
|
||||
require.ErrorContains(t, err, "cannot create")
|
||||
require.Empty(t, runner.calls)
|
||||
}
|
||||
|
||||
func TestPushAgitPRWithOptionsToRealRemote(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("Git is not installed")
|
||||
}
|
||||
root := t.TempDir()
|
||||
env := append(os.Environ(), "GIT_CONFIG_GLOBAL="+filepath.Join(root, "gitconfig"), "GIT_CONFIG_NOSYSTEM=1",
|
||||
"GIT_AUTHOR_NAME=tea", "GIT_AUTHOR_EMAIL=tea@example.invalid", "GIT_COMMITTER_NAME=tea", "GIT_COMMITTER_EMAIL=tea@example.invalid")
|
||||
runner := System{Env: env}
|
||||
remote, work := filepath.Join(root, "remote.git"), filepath.Join(root, "work")
|
||||
for _, step := range []struct {
|
||||
dir string
|
||||
args []string
|
||||
}{
|
||||
{root, []string{"init", "--bare", remote}},
|
||||
{remote, []string{"config", "receive.advertisePushOptions", "true"}},
|
||||
{root, []string{"init", "-b", "feature", work}},
|
||||
{work, []string{"commit", "--allow-empty", "-m", "initial"}},
|
||||
{work, []string{"remote", "add", "origin", remote}},
|
||||
} {
|
||||
_, err := runner.Output(context.Background(), step.dir, false, step.args...)
|
||||
require.NoError(t, err, step.args)
|
||||
}
|
||||
require.NoError(t, PushAgitPR(context.Background(), runner, AgitOptions{
|
||||
Directory: work, Remote: "origin", Head: "feature", Base: "main", Topic: "topic", Title: "Hello", Body: "line1\nline2",
|
||||
}))
|
||||
pushed, err := runner.Output(context.Background(), remote, false, "rev-parse", "refs/for/main/topic")
|
||||
require.NoError(t, err)
|
||||
local, err := runner.Output(context.Background(), work, false, "rev-parse", "HEAD")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, local, pushed)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CheckoutOptions identifies the base remote and how to check out the PR commit.
|
||||
type CheckoutOptions struct {
|
||||
// CredentialArgs contains per-operation Git configuration for the fetch only.
|
||||
CredentialArgs []string
|
||||
Directory string
|
||||
Remote string
|
||||
Number int64
|
||||
Branch string
|
||||
Detached bool
|
||||
Update bool
|
||||
Prompt bool
|
||||
ExpectedCommit string
|
||||
// HeadRemote and HeadBranch select fork tracking when the head branch still exists.
|
||||
// When HeadBranch is empty, checkout fetches the retained pull ref from Remote.
|
||||
HeadRemote string
|
||||
HeadBranch string
|
||||
}
|
||||
|
||||
// CheckoutResult describes the selected branch or detached PR commit.
|
||||
type CheckoutResult struct {
|
||||
Detached bool `json:"detached"`
|
||||
Branch string `json:"branch"`
|
||||
Commit string `json:"commit"`
|
||||
Remote string `json:"remote,omitempty"`
|
||||
Tracking string `json:"tracking,omitempty"`
|
||||
}
|
||||
|
||||
// CheckoutPull fetches a PR head and checks out its commit.
|
||||
// When HeadRemote and HeadBranch are set, it fetches that head branch and configures tracking.
|
||||
// Otherwise it fetches Gitea's retained pull ref from the base remote.
|
||||
func CheckoutPull(ctx context.Context, runner Runner, options CheckoutOptions) (CheckoutResult, error) {
|
||||
if options.Number < 1 || options.Remote == "" || (!options.Detached && options.Branch == "") {
|
||||
return CheckoutResult{}, errors.New("checkout requires a pull number, base remote, and either a branch or detached mode")
|
||||
}
|
||||
if options.Detached && (options.Branch != "" || options.Update) {
|
||||
return CheckoutResult{}, errors.New("detached checkout cannot select a branch or update an existing branch")
|
||||
}
|
||||
if options.HeadBranch != "" && options.HeadRemote == "" {
|
||||
return CheckoutResult{}, errors.New("tracked checkout requires a head remote")
|
||||
}
|
||||
run := func(args ...string) (string, error) {
|
||||
return runner.Output(ctx, options.Directory, options.Prompt, args...)
|
||||
}
|
||||
if err := requireWorkTree(run, "PR checkout"); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
if !options.Detached {
|
||||
if _, err := run("check-ref-format", "--branch", options.Branch); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("invalid checkout branch: %w", err)
|
||||
}
|
||||
}
|
||||
status, err := run("status", "--porcelain=v1", "--untracked-files=normal")
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
if status != "" {
|
||||
return CheckoutResult{}, errors.New("working tree has changes; commit or stash them before PR checkout")
|
||||
}
|
||||
existing := false
|
||||
previousCommit := ""
|
||||
if !options.Detached {
|
||||
branches, err := run("for-each-ref", "--format=%(refname)", "refs/heads/")
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
for branch := range strings.SplitSeq(branches, "\n") {
|
||||
if branch == "refs/heads/"+options.Branch {
|
||||
if options.ExpectedCommit == "" {
|
||||
return CheckoutResult{}, fmt.Errorf("branch %q already exists; choose another checkout branch", options.Branch)
|
||||
}
|
||||
commit, err := run("rev-parse", "--verify", branch+"^{commit}")
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
if commit != options.ExpectedCommit && !options.Update {
|
||||
return CheckoutResult{}, fmt.Errorf("branch %q already exists with a different commit; choose another checkout branch", options.Branch)
|
||||
}
|
||||
previousCommit = commit
|
||||
existing = true
|
||||
}
|
||||
}
|
||||
}
|
||||
fetchRemote := options.Remote
|
||||
fetchRef := fmt.Sprintf("refs/pull/%d/head", options.Number)
|
||||
tracking := ""
|
||||
if options.HeadBranch != "" {
|
||||
if _, err := run("check-ref-format", "--branch", options.HeadBranch); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("invalid head branch: %w", err)
|
||||
}
|
||||
fetchRemote = options.HeadRemote
|
||||
fetchRef = "refs/heads/" + options.HeadBranch
|
||||
tracking = options.HeadRemote + "/" + options.HeadBranch
|
||||
}
|
||||
fetchArgs := append([]string{}, options.CredentialArgs...)
|
||||
fetchArgs = append(fetchArgs, "fetch", "--no-tags", "--", fetchRemote, fetchRef)
|
||||
if _, err := run(fetchArgs...); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
commit, err := run("rev-parse", "--verify", "FETCH_HEAD^{commit}")
|
||||
if err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("PR was fetched, but its commit could not be resolved: %w", err)
|
||||
}
|
||||
if options.ExpectedCommit != "" && commit != options.ExpectedCommit {
|
||||
return CheckoutResult{}, errors.New("PR head changed while fetching; retry checkout")
|
||||
}
|
||||
if existing {
|
||||
localCommit, err := run("rev-parse", "--verify", "refs/heads/"+options.Branch+"^{commit}")
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
if localCommit != previousCommit {
|
||||
return CheckoutResult{}, errors.New("local branch changed while fetching; retry checkout")
|
||||
}
|
||||
if localCommit != commit {
|
||||
if _, err := run("merge-base", "--is-ancestor", localCommit, commit); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("existing branch cannot be fast-forwarded; choose another checkout branch: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
switchArgs := []string{"switch", "--detach", commit}
|
||||
if !options.Detached {
|
||||
switchArgs = []string{"switch", "--create", options.Branch, commit}
|
||||
if existing {
|
||||
switchArgs = []string{"switch", options.Branch}
|
||||
}
|
||||
}
|
||||
if _, err := run(switchArgs...); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("PR was fetched, but checkout failed: %w", err)
|
||||
}
|
||||
if existing && previousCommit != commit {
|
||||
if _, err := run("merge", "--ff-only", "--no-edit", commit); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("checked out the existing branch, but its fast-forward failed: %w", err)
|
||||
}
|
||||
}
|
||||
if tracking != "" && !options.Detached {
|
||||
if _, err := run("config", "branch."+options.Branch+".remote", options.HeadRemote); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("checked out the branch, but could not configure tracking: %w", err)
|
||||
}
|
||||
if _, err := run("config", "branch."+options.Branch+".merge", "refs/heads/"+options.HeadBranch); err != nil {
|
||||
return CheckoutResult{}, fmt.Errorf("checked out the branch, but could not configure tracking: %w", err)
|
||||
}
|
||||
}
|
||||
return CheckoutResult{Branch: options.Branch, Commit: commit, Detached: options.Detached, Remote: fetchRemote, Tracking: tracking}, nil
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type checkoutRunner struct {
|
||||
calls []string
|
||||
dirty, collision bool
|
||||
localCommit string
|
||||
diverged bool
|
||||
}
|
||||
|
||||
func (r *checkoutRunner) Output(_ context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
if dir != "/work" || prompt {
|
||||
return "", fmt.Errorf("unexpected Git execution policy")
|
||||
}
|
||||
command := strings.Join(args, " ")
|
||||
r.calls = append(r.calls, command)
|
||||
switch args[0] {
|
||||
case "merge-base":
|
||||
if r.diverged {
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
case "rev-parse":
|
||||
if len(args) > 2 && strings.HasPrefix(args[2], "refs/heads/") && r.localCommit != "" {
|
||||
return r.localCommit, nil
|
||||
}
|
||||
if args[1] == "--is-inside-work-tree" {
|
||||
return "true", nil
|
||||
}
|
||||
return "abc123", nil
|
||||
case "status":
|
||||
if r.dirty {
|
||||
return "?? file", nil
|
||||
}
|
||||
case "for-each-ref":
|
||||
if r.collision {
|
||||
return "refs/heads/pr/7", nil
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func TestPullCheckoutValidatesBeforeChangingGitState(t *testing.T) {
|
||||
options := CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7"}
|
||||
for _, tc := range []struct {
|
||||
dirty, collision bool
|
||||
message string
|
||||
}{{true, false, "working tree has changes"}, {false, true, "already exists"}} {
|
||||
runner := &checkoutRunner{dirty: tc.dirty, collision: tc.collision}
|
||||
_, err := CheckoutPull(context.Background(), runner, options)
|
||||
require.ErrorContains(t, err, tc.message)
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "fetch "))
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
}
|
||||
}
|
||||
runner := &checkoutRunner{}
|
||||
result, err := CheckoutPull(context.Background(), runner, options)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, CheckoutResult{Branch: "pr/7", Commit: "abc123", Remote: "origin"}, result)
|
||||
require.Equal(t, []string{"rev-parse --is-inside-work-tree", "check-ref-format --branch pr/7", "status --porcelain=v1 --untracked-files=normal", "for-each-ref --format=%(refname) refs/heads/", "fetch --no-tags -- origin refs/pull/7/head", "rev-parse --verify FETCH_HEAD^{commit}", "switch --create pr/7 abc123"}, runner.calls)
|
||||
}
|
||||
|
||||
func TestPullCheckoutRejectsChangedHead(t *testing.T) {
|
||||
runner := &checkoutRunner{}
|
||||
_, err := CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", ExpectedCommit: "different"})
|
||||
require.ErrorContains(t, err, "PR head changed")
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullCheckoutScopesCredentialArgumentsToFetch(t *testing.T) {
|
||||
runner := &checkoutRunner{}
|
||||
arguments := []string{"-c", "credential.https://example.test.helper=!tea-helper"}
|
||||
_, err := CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", CredentialArgs: arguments})
|
||||
require.NoError(t, err)
|
||||
credentialCalls := 0
|
||||
for _, call := range runner.calls {
|
||||
if strings.HasPrefix(call, "-c ") {
|
||||
credentialCalls++
|
||||
require.Equal(t, "-c credential.https://example.test.helper=!tea-helper fetch --no-tags -- origin refs/pull/7/head", call)
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, credentialCalls)
|
||||
require.Equal(t, []string{"-c", "credential.https://example.test.helper=!tea-helper"}, arguments)
|
||||
}
|
||||
|
||||
func TestDetachedCheckoutDoesNotCreateOrChangeBranches(t *testing.T) {
|
||||
runner := &checkoutRunner{collision: true}
|
||||
result, err := CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Detached: true, ExpectedCommit: "abc123"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, CheckoutResult{Detached: true, Commit: "abc123", Remote: "origin"}, result)
|
||||
require.Equal(t, "switch --detach abc123", runner.calls[len(runner.calls)-1])
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "for-each-ref"))
|
||||
require.False(t, strings.HasPrefix(call, "check-ref-format"))
|
||||
require.NotContains(t, call, "--create")
|
||||
}
|
||||
runner = &checkoutRunner{dirty: true}
|
||||
_, err = CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Detached: true})
|
||||
require.ErrorContains(t, err, "working tree has changes")
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "fetch "))
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
}
|
||||
runner = &checkoutRunner{}
|
||||
_, err = CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Detached: true, Branch: "existing"})
|
||||
require.ErrorContains(t, err, "cannot select a branch")
|
||||
require.Empty(t, runner.calls)
|
||||
}
|
||||
|
||||
func TestPullCheckoutReusesMatchingBranch(t *testing.T) {
|
||||
runner := &checkoutRunner{collision: true}
|
||||
result, err := CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", ExpectedCommit: "abc123"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "abc123", result.Commit)
|
||||
require.Contains(t, runner.calls, "rev-parse --verify refs/heads/pr/7^{commit}")
|
||||
require.Equal(t, "switch pr/7", runner.calls[len(runner.calls)-1])
|
||||
runner = &checkoutRunner{collision: true}
|
||||
_, err = CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", ExpectedCommit: "different"})
|
||||
require.ErrorContains(t, err, "already exists with a different commit")
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "fetch "))
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullCheckoutUpdatesOnlyByFastForward(t *testing.T) {
|
||||
for _, diverged := range []bool{false, true} {
|
||||
runner := &checkoutRunner{collision: true, localCommit: "previous", diverged: diverged}
|
||||
_, err := CheckoutPull(context.Background(), runner, CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", ExpectedCommit: "abc123", Update: true})
|
||||
require.Contains(t, runner.calls, "merge-base --is-ancestor previous abc123")
|
||||
if diverged {
|
||||
require.ErrorContains(t, err, "cannot be fast-forwarded")
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
require.False(t, strings.HasPrefix(call, "merge "))
|
||||
}
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"switch pr/7", "merge --ff-only --no-edit abc123"}, runner.calls[len(runner.calls)-2:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullCheckoutTracksHeadBranch(t *testing.T) {
|
||||
runner := &checkoutRunner{}
|
||||
result, err := CheckoutPull(context.Background(), runner, CheckoutOptions{
|
||||
Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", ExpectedCommit: "abc123",
|
||||
HeadRemote: "pulls/bob", HeadBranch: "feature",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, CheckoutResult{Branch: "pr/7", Commit: "abc123", Remote: "pulls/bob", Tracking: "pulls/bob/feature"}, result)
|
||||
require.Contains(t, runner.calls, "check-ref-format --branch feature")
|
||||
require.Contains(t, runner.calls, "fetch --no-tags -- pulls/bob refs/heads/feature")
|
||||
require.Contains(t, runner.calls, "config branch.pr/7.remote pulls/bob")
|
||||
require.Contains(t, runner.calls, "config branch.pr/7.merge refs/heads/feature")
|
||||
for _, call := range runner.calls {
|
||||
require.NotContains(t, call, "refs/pull/")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CleanOptions identifies a closed PR's local branch and optional remote head.
|
||||
type CleanOptions struct {
|
||||
Directory, DefaultBranch, LocalBranch, Remote, RemoteBranch string
|
||||
CredentialArgs []string
|
||||
Prompt, DeleteRemote bool
|
||||
}
|
||||
|
||||
// CleanResult reports which branches were removed.
|
||||
type CleanResult struct {
|
||||
LocalBranch string `json:"local_branch"`
|
||||
Remote string `json:"remote,omitempty"`
|
||||
RemoteBranch string `json:"remote_branch,omitempty"`
|
||||
DefaultBranch string `json:"default_branch"`
|
||||
RemoteDeleted bool `json:"remote_deleted"`
|
||||
RemoteSkipped bool `json:"remote_skipped"`
|
||||
RemoteSkipReason string `json:"remote_skip_reason,omitempty"`
|
||||
}
|
||||
|
||||
// FindCleanBranchOptions searches for a local branch belonging to a closed PR.
|
||||
type FindCleanBranchOptions struct {
|
||||
Directory, HeadSHA, HeadBranch string
|
||||
DefaultBranch string
|
||||
PreferredNames, MatchingRemotes []string
|
||||
IgnoreSHA bool
|
||||
}
|
||||
|
||||
// FindCleanBranch locates one local branch for PR cleanup without mutating Git state.
|
||||
func FindCleanBranch(ctx context.Context, runner Runner, opts FindCleanBranchOptions) (localBranch, remote string, err error) {
|
||||
run := func(args ...string) (string, error) {
|
||||
return runner.Output(ctx, opts.Directory, false, args...)
|
||||
}
|
||||
if err := requireWorkTree(run, "PR clean"); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
refs, err := run("for-each-ref", "--format=%(objectname)%09%(refname:short)%09%(upstream:short)", "refs/heads/")
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
type candidate struct {
|
||||
name, remote string
|
||||
matched bool
|
||||
}
|
||||
setOf := func(names []string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, name := range names {
|
||||
if name != "" {
|
||||
out[name] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
preferred := setOf(opts.PreferredNames)
|
||||
matching := setOf(opts.MatchingRemotes)
|
||||
candidates := []candidate{}
|
||||
for line := range strings.SplitSeq(refs, "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(line, "\t", 3)
|
||||
if len(parts) < 2 {
|
||||
continue
|
||||
}
|
||||
sha, name := parts[0], parts[1]
|
||||
if name == opts.DefaultBranch {
|
||||
continue
|
||||
}
|
||||
upstream := ""
|
||||
if len(parts) == 3 {
|
||||
upstream = parts[2]
|
||||
}
|
||||
if opts.IgnoreSHA {
|
||||
if name != opts.HeadBranch && !preferred[name] {
|
||||
continue
|
||||
}
|
||||
} else if opts.HeadSHA == "" || sha != opts.HeadSHA {
|
||||
continue
|
||||
}
|
||||
remoteName := ""
|
||||
matched := false
|
||||
if upstream != "" {
|
||||
remoteName = strings.SplitN(upstream, "/", 2)[0]
|
||||
matched = matching[remoteName]
|
||||
}
|
||||
if !matched {
|
||||
for remote := range matching {
|
||||
tracking, trackErr := run("rev-parse", "--verify", "refs/remotes/"+remote+"/"+opts.HeadBranch+"^{commit}")
|
||||
if trackErr == nil && (opts.IgnoreSHA || tracking == sha) {
|
||||
remoteName, matched = remote, true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matched && len(matching) == 1 {
|
||||
for remote := range matching {
|
||||
remoteName = remote
|
||||
}
|
||||
}
|
||||
candidates = append(candidates, candidate{name: name, remote: remoteName, matched: matched})
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
if opts.IgnoreSHA {
|
||||
return "", "", fmt.Errorf("local branch %q was not found for the selected pull request", opts.HeadBranch)
|
||||
}
|
||||
return "", "", fmt.Errorf(`local branch for commit %s was not found.
|
||||
Either this pull request was never checked out, or the local branch diverged.
|
||||
Retry with --ignore-sha to select by branch name`, opts.HeadSHA)
|
||||
}
|
||||
selected := []candidate{}
|
||||
for _, item := range candidates {
|
||||
if item.matched || preferred[item.name] || item.name == opts.HeadBranch {
|
||||
selected = append(selected, item)
|
||||
}
|
||||
}
|
||||
if len(selected) == 0 {
|
||||
selected = candidates
|
||||
}
|
||||
if len(selected) > 1 {
|
||||
strong := make([]candidate, 0, len(selected))
|
||||
for _, item := range selected {
|
||||
if item.matched {
|
||||
strong = append(strong, item)
|
||||
}
|
||||
}
|
||||
if len(strong) > 0 {
|
||||
selected = strong
|
||||
}
|
||||
}
|
||||
if len(selected) != 1 {
|
||||
names := make([]string, 0, len(selected))
|
||||
for _, item := range selected {
|
||||
names = append(names, item.name)
|
||||
}
|
||||
return "", "", fmt.Errorf("multiple local branches match this pull request (%s); check out or rename until one remains", strings.Join(names, ", "))
|
||||
}
|
||||
return selected[0].name, selected[0].remote, nil
|
||||
}
|
||||
|
||||
// CleanPull deletes the selected local branch and optionally its remote head.
|
||||
func CleanPull(ctx context.Context, runner Runner, opts CleanOptions) (CleanResult, error) {
|
||||
run := func(args ...string) (string, error) {
|
||||
return runner.Output(ctx, opts.Directory, opts.Prompt, args...)
|
||||
}
|
||||
if opts.LocalBranch == "" || opts.DefaultBranch == "" {
|
||||
return CleanResult{}, errors.New("clean requires a local branch and repository default branch")
|
||||
}
|
||||
if opts.LocalBranch == opts.DefaultBranch {
|
||||
return CleanResult{}, errors.New("refusing to delete the repository default branch")
|
||||
}
|
||||
if opts.DeleteRemote && (opts.Remote == "" || opts.RemoteBranch == "") {
|
||||
return CleanResult{}, errors.New("remote deletion requires a remote and branch name")
|
||||
}
|
||||
if err := requireWorkTree(run, "PR clean"); err != nil {
|
||||
return CleanResult{}, err
|
||||
}
|
||||
if _, err := run("check-ref-format", "--branch", opts.LocalBranch); err != nil {
|
||||
return CleanResult{}, fmt.Errorf("invalid local branch: %w", err)
|
||||
}
|
||||
if _, err := run("check-ref-format", "--branch", opts.DefaultBranch); err != nil {
|
||||
return CleanResult{}, fmt.Errorf("invalid default branch: %w", err)
|
||||
}
|
||||
status, err := run("status", "--porcelain=v1", "--untracked-files=normal")
|
||||
if err != nil {
|
||||
return CleanResult{}, err
|
||||
}
|
||||
if status != "" {
|
||||
return CleanResult{}, errors.New("working tree has changes; commit or stash them before cleaning")
|
||||
}
|
||||
if _, err := run("rev-parse", "--verify", "refs/heads/"+opts.LocalBranch+"^{commit}"); err != nil {
|
||||
return CleanResult{}, fmt.Errorf("local branch is unavailable: %w", err)
|
||||
}
|
||||
if _, err := run("rev-parse", "--verify", "refs/heads/"+opts.DefaultBranch+"^{commit}"); err != nil {
|
||||
return CleanResult{}, fmt.Errorf("default branch is unavailable; create or fetch it before cleaning: %w", err)
|
||||
}
|
||||
current, err := run("symbolic-ref", "--short", "HEAD")
|
||||
if err == nil && current == opts.LocalBranch {
|
||||
if _, err := run("switch", "--", opts.DefaultBranch); err != nil {
|
||||
return CleanResult{}, fmt.Errorf("could not switch to %s before deleting %s: %w", opts.DefaultBranch, opts.LocalBranch, err)
|
||||
}
|
||||
}
|
||||
if _, err := run("branch", "-D", "--", opts.LocalBranch); err != nil {
|
||||
return CleanResult{}, fmt.Errorf("local branch could not be deleted: %w", err)
|
||||
}
|
||||
result := CleanResult{LocalBranch: opts.LocalBranch, DefaultBranch: opts.DefaultBranch}
|
||||
if !opts.DeleteRemote {
|
||||
result.RemoteSkipped = true
|
||||
result.RemoteSkipReason = "remote head was already deleted or push is unavailable"
|
||||
return result, nil
|
||||
}
|
||||
push := append([]string{}, opts.CredentialArgs...)
|
||||
push = append(push, "push", "--delete", "--", opts.Remote, opts.RemoteBranch)
|
||||
if _, err := run(push...); err != nil {
|
||||
return result, fmt.Errorf("deleted local branch %s, but deleting remote branch %s failed: %w", opts.LocalBranch, opts.RemoteBranch, err)
|
||||
}
|
||||
result.Remote, result.RemoteBranch, result.RemoteDeleted = opts.Remote, opts.RemoteBranch, true
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type cleanRunner struct {
|
||||
calls []string
|
||||
dirty, missingLocal, missingDefault, onFeature bool
|
||||
branches string
|
||||
remoteTracking map[string]string
|
||||
}
|
||||
|
||||
func (r *cleanRunner) Output(_ context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
if dir != "/work" {
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
command := strings.Join(args, " ")
|
||||
r.calls = append(r.calls, command)
|
||||
switch args[0] {
|
||||
case "rev-parse":
|
||||
if len(args) > 1 && args[1] == "--is-inside-work-tree" {
|
||||
return "true", nil
|
||||
}
|
||||
if len(args) > 2 && strings.HasPrefix(args[2], "refs/heads/") {
|
||||
if r.missingLocal && strings.Contains(args[2], "feature") {
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
if r.missingDefault && strings.Contains(args[2], "main") {
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
return "abc123", nil
|
||||
}
|
||||
if len(args) > 2 && strings.HasPrefix(args[2], "refs/remotes/") {
|
||||
if sha, ok := r.remoteTracking[args[2]]; ok {
|
||||
return sha, nil
|
||||
}
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
case "status":
|
||||
if r.dirty {
|
||||
return " M file", nil
|
||||
}
|
||||
case "symbolic-ref":
|
||||
if r.onFeature {
|
||||
return "feature", nil
|
||||
}
|
||||
return "main", nil
|
||||
case "for-each-ref":
|
||||
return r.branches, nil
|
||||
case "check-ref-format", "switch", "branch", "push":
|
||||
return "", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func TestFindCleanBranchBySHAAndPreferredName(t *testing.T) {
|
||||
runner := &cleanRunner{branches: "abc123\tpr/7\torigin/feature\ndef456\tother\t\n"}
|
||||
branch, remote, err := FindCleanBranch(context.Background(), runner, FindCleanBranchOptions{
|
||||
Directory: "/work", HeadSHA: "abc123", HeadBranch: "feature", PreferredNames: []string{"pr/7"}, MatchingRemotes: []string{"origin"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pr/7", branch)
|
||||
require.Equal(t, "origin", remote)
|
||||
}
|
||||
|
||||
func TestFindCleanBranchIgnoreSHAUsesName(t *testing.T) {
|
||||
runner := &cleanRunner{branches: "deadbeef\tfeature\torigin/feature\n"}
|
||||
branch, remote, err := FindCleanBranch(context.Background(), runner, FindCleanBranchOptions{
|
||||
Directory: "/work", HeadSHA: "abc123", HeadBranch: "feature", IgnoreSHA: true, MatchingRemotes: []string{"origin"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "feature", branch)
|
||||
require.Equal(t, "origin", remote)
|
||||
}
|
||||
|
||||
func TestFindCleanBranchRejectsAmbiguity(t *testing.T) {
|
||||
runner := &cleanRunner{branches: "abc123\tone\t\nabc123\ttwo\t\n"}
|
||||
_, _, err := FindCleanBranch(context.Background(), runner, FindCleanBranchOptions{
|
||||
Directory: "/work", HeadSHA: "abc123", HeadBranch: "feature", MatchingRemotes: []string{"origin"},
|
||||
})
|
||||
require.ErrorContains(t, err, "multiple local branches")
|
||||
}
|
||||
|
||||
func TestFindCleanBranchSkipsDefaultBranch(t *testing.T) {
|
||||
runner := &cleanRunner{branches: "abc123\tmain\torigin/main\nabc123\tpr/7\t\n"}
|
||||
branch, _, err := FindCleanBranch(context.Background(), runner, FindCleanBranchOptions{
|
||||
Directory: "/work", HeadSHA: "abc123", HeadBranch: "feature", DefaultBranch: "main", PreferredNames: []string{"pr/7"}, MatchingRemotes: []string{"origin"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pr/7", branch)
|
||||
}
|
||||
|
||||
func TestCleanPullRejectsDefaultBranch(t *testing.T) {
|
||||
_, err := CleanPull(context.Background(), &cleanRunner{}, CleanOptions{Directory: "/work", DefaultBranch: "main", LocalBranch: "main"})
|
||||
require.ErrorContains(t, err, "default branch")
|
||||
}
|
||||
|
||||
func TestCleanPullValidatesBeforeMutation(t *testing.T) {
|
||||
runner := &cleanRunner{dirty: true}
|
||||
_, err := CleanPull(context.Background(), runner, CleanOptions{Directory: "/work", DefaultBranch: "main", LocalBranch: "feature"})
|
||||
require.ErrorContains(t, err, "working tree has changes")
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
require.False(t, strings.HasPrefix(call, "branch "))
|
||||
require.False(t, strings.HasPrefix(call, "push "))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanPullDeletesLocalAndRemoteBranches(t *testing.T) {
|
||||
runner := &cleanRunner{onFeature: true}
|
||||
result, err := CleanPull(context.Background(), runner, CleanOptions{
|
||||
Directory: "/work", DefaultBranch: "main", LocalBranch: "feature", Remote: "origin", RemoteBranch: "feature",
|
||||
DeleteRemote: true, CredentialArgs: []string{"-c", "credential.helper=tea"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, CleanResult{LocalBranch: "feature", Remote: "origin", RemoteBranch: "feature", DefaultBranch: "main", RemoteDeleted: true}, result)
|
||||
require.Contains(t, runner.calls, "switch -- main")
|
||||
require.Contains(t, runner.calls, "branch -D -- feature")
|
||||
require.Contains(t, runner.calls, "-c credential.helper=tea push --delete -- origin feature")
|
||||
}
|
||||
|
||||
func TestCleanPullSkipsRemoteWhenUnavailable(t *testing.T) {
|
||||
runner := &cleanRunner{}
|
||||
result, err := CleanPull(context.Background(), runner, CleanOptions{Directory: "/work", DefaultBranch: "main", LocalBranch: "feature"})
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.RemoteSkipped)
|
||||
require.Equal(t, "feature", result.LocalBranch)
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "push "))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/tea/internal/settings"
|
||||
"github.com/kballard/go-shellquote"
|
||||
)
|
||||
|
||||
// CredentialHelper builds a shell command for Git's helper protocol. Git itself
|
||||
// supplies the final get/store/erase argument. No credential enters this command.
|
||||
func CredentialHelper(instance, executable, user, configDir string) (string, error) {
|
||||
normalized, err := settings.NormalizeHost(instance)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !filepath.IsAbs(executable) || strings.ContainsAny(executable+user+configDir, "\x00\r\n") {
|
||||
return "", errors.New("credential helper requires a valid absolute executable path")
|
||||
}
|
||||
command := []string{executable, "auth", "git-credential", "--host", normalized}
|
||||
if user != "" {
|
||||
command = append(command, "--user", user)
|
||||
}
|
||||
helper := shellquote.Join(command...)
|
||||
if configDir != "" {
|
||||
if !filepath.IsAbs(configDir) {
|
||||
return "", errors.New("credential helper configuration directory must be absolute")
|
||||
}
|
||||
helper = "TEA_CONFIG_DIR=" + shellquote.Join(configDir) + " " + helper
|
||||
}
|
||||
return "!" + helper, nil
|
||||
}
|
||||
|
||||
// CredentialArguments scopes a helper to one Git operation instead of changing
|
||||
// Git configuration. The empty helper resets other helpers for this instance.
|
||||
func CredentialArguments(instance, executable, user, configDir string) ([]string, error) {
|
||||
helper, err := CredentialHelper(instance, executable, user, configDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalized, err := settings.NormalizeHost(instance)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefix := "credential." + normalized + "."
|
||||
return []string{"-c", prefix + "helper=", "-c", prefix + "helper=" + helper, "-c", prefix + "useHttpPath=true"}, nil
|
||||
}
|
||||
|
||||
// CredentialSetup specifies an explicit persistent helper installation.
|
||||
type CredentialSetup struct {
|
||||
Directory, Instance, Executable, User, ConfigDirectory string
|
||||
Local bool
|
||||
}
|
||||
|
||||
// SetupCredentials adds a scoped helper without removing other credential helpers.
|
||||
func SetupCredentials(ctx context.Context, runner Runner, options CredentialSetup) error {
|
||||
normalized, err := settings.NormalizeHost(options.Instance)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
helper, err := CredentialHelper(normalized, options.Executable, options.User, options.ConfigDirectory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cwd := options.Directory
|
||||
local := options.Local
|
||||
scope := "--global"
|
||||
if local {
|
||||
scope = "--local"
|
||||
}
|
||||
prefix := "credential." + normalized + "."
|
||||
readValues := func(key string) ([]string, error) {
|
||||
data, err := runner.Output(ctx, cwd, false, "config", scope, "--null", "--get-all", prefix+key)
|
||||
if err != nil {
|
||||
if failure, ok := errors.AsType[*CommandError](err); ok && failure.ExitCode == 1 {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return strings.Split(strings.TrimSuffix(data, "\x00"), "\x00"), nil
|
||||
}
|
||||
helpers, err := readValues("helper")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pathValues, err := readValues("useHttpPath")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Install path awareness first: the helper must see the installation base path.
|
||||
if len(pathValues) != 1 || pathValues[0] != "true" {
|
||||
if _, err := runner.Output(ctx, cwd, false, "config", scope, "--replace-all", prefix+"useHttpPath", "true"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if slices.Contains(helpers, helper) {
|
||||
return nil
|
||||
}
|
||||
_, err = runner.Output(ctx, cwd, false, "config", scope, "--add", prefix+"helper", helper)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kballard/go-shellquote"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSetupGitCredentialsPreservesHelpersAndIsIdempotent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cwd := t.TempDir()
|
||||
runner := System{}
|
||||
_, err := runner.Output(ctx, cwd, false, "init")
|
||||
require.NoError(t, err)
|
||||
instance := "https://example.test:8443/gitea"
|
||||
key := "credential." + instance + ".helper"
|
||||
_, err = runner.Output(ctx, cwd, false, "config", "--local", "--add", key, "existing-helper")
|
||||
require.NoError(t, err)
|
||||
executable := filepath.Join(cwd, "path with spaces and 'quote'", "tea")
|
||||
require.NoError(t, SetupCredentials(ctx, runner, CredentialSetup{Directory: cwd, Local: true, Instance: instance, Executable: executable, User: "alice"}))
|
||||
require.NoError(t, SetupCredentials(ctx, runner, CredentialSetup{Directory: cwd, Local: true, Instance: instance, Executable: executable, User: "alice"}))
|
||||
data, err := runner.Output(ctx, cwd, false, "config", "--local", "--get-all", key)
|
||||
require.NoError(t, err)
|
||||
helpers := strings.Split(data, "\n")
|
||||
require.Len(t, helpers, 2)
|
||||
require.Equal(t, "existing-helper", helpers[0])
|
||||
words, err := shellquote.Split(strings.TrimPrefix(helpers[1], "!"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{executable, "auth", "git-credential", "--host", instance, "--user", "alice"}, words)
|
||||
data, err = runner.Output(ctx, cwd, false, "config", "--local", "--get", "credential."+instance+".useHttpPath")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "true", data)
|
||||
}
|
||||
|
||||
func TestSetupGitCredentialsWorksWithoutAnExistingGlobalFile(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(home, "new.gitconfig"))
|
||||
executable, err := os.Executable()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, SetupCredentials(context.Background(), System{}, CredentialSetup{Directory: home, Instance: "https://example.test", Executable: executable}))
|
||||
data, err := os.ReadFile(filepath.Join(home, "new.gitconfig"))
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(data), "useHttpPath = true")
|
||||
require.Contains(t, string(data), "auth git-credential")
|
||||
}
|
||||
|
||||
func TestGitMissingConfigValueCarriesExitCode(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("Git is not installed")
|
||||
}
|
||||
_, err := (System{}).Output(context.Background(), t.TempDir(), false, "config", "--file", filepath.Join(t.TempDir(), "missing"), "--get", "not.present")
|
||||
var failure *CommandError
|
||||
require.ErrorAs(t, err, &failure)
|
||||
require.Equal(t, 1, failure.ExitCode)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrAmbiguousRemote reports that repository discovery cannot choose between several remotes.
|
||||
var ErrAmbiguousRemote = errors.New("ambiguous repository: select --remote or --repo")
|
||||
|
||||
// DiscoverRemote names the remote used for repository discovery: preferred when set, otherwise
|
||||
// the current branch's upstream remote, then upstream, origin, or the only remote.
|
||||
func DiscoverRemote(ctx context.Context, runner Runner, dir, preferred string) (string, error) {
|
||||
if preferred != "" {
|
||||
return preferred, nil
|
||||
}
|
||||
if _, remote := CurrentUpstreamRemote(ctx, runner, dir); remote != "" {
|
||||
return remote, nil
|
||||
}
|
||||
names, err := runner.Output(ctx, dir, false, "remote")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
available := strings.Fields(names)
|
||||
for _, name := range []string{"upstream", "origin"} {
|
||||
if slices.Contains(available, name) {
|
||||
return name, nil
|
||||
}
|
||||
}
|
||||
if len(available) == 1 {
|
||||
return available[0], nil
|
||||
}
|
||||
return "", ErrAmbiguousRemote
|
||||
}
|
||||
|
||||
// CurrentUpstreamRemote names the checked-out branch and the remote it tracks; each is "" when
|
||||
// HEAD is detached or the branch tracks no remote.
|
||||
func CurrentUpstreamRemote(ctx context.Context, runner Runner, dir string) (branch, remote string) {
|
||||
branch, err := runner.Output(ctx, dir, false, "symbolic-ref", "--short", "HEAD")
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
return branch, UpstreamRemote(ctx, runner, dir, branch)
|
||||
}
|
||||
|
||||
// UpstreamRemote names the remote branch tracks, or "" when it tracks none or a local branch.
|
||||
// Unlike splitting @{upstream}, it keeps remote names with slashes, such as the
|
||||
// pulls/<owner>/<repo> remotes pr checkout adds.
|
||||
func UpstreamRemote(ctx context.Context, runner Runner, dir, branch string) string {
|
||||
if branch == "" {
|
||||
return ""
|
||||
}
|
||||
remote, err := runner.Output(ctx, dir, false, "config", "--get", "branch."+branch+".remote")
|
||||
if err != nil || remote == "." {
|
||||
return ""
|
||||
}
|
||||
return remote
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type discoverRunner map[string]string
|
||||
|
||||
func (r discoverRunner) Output(_ context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
value, ok := r[strings.Join(args, " ")]
|
||||
if dir != "/work" || prompt || !ok {
|
||||
return "", errors.New("missing fake Git result")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func TestDiscoverRemote(t *testing.T) {
|
||||
const head, tracking = "symbolic-ref --short HEAD", "config --get branch.main.remote"
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
runner discoverRunner
|
||||
preferred string
|
||||
want string
|
||||
wantErr error
|
||||
}{
|
||||
{name: "preferred", preferred: "fork", want: "fork"},
|
||||
{name: "branch upstream", runner: discoverRunner{head: "main", tracking: "fork", "remote": "origin\nfork"}, want: "fork"},
|
||||
{name: "branch upstream with slashes", runner: discoverRunner{head: "main", tracking: "pulls/bob/project", "remote": "origin\npulls/bob/project"}, want: "pulls/bob/project"},
|
||||
{name: "local branch upstream", runner: discoverRunner{head: "main", tracking: ".", "remote": "origin\nfork"}, want: "origin"},
|
||||
{name: "upstream remote", runner: discoverRunner{"remote": "origin\nupstream"}, want: "upstream"},
|
||||
{name: "origin remote", runner: discoverRunner{"remote": "fork\norigin"}, want: "origin"},
|
||||
{name: "sole remote", runner: discoverRunner{"remote": "fork"}, want: "fork"},
|
||||
{name: "ambiguous", runner: discoverRunner{"remote": "one\ntwo"}, wantErr: ErrAmbiguousRemote},
|
||||
{name: "no remotes", runner: discoverRunner{"remote": ""}, wantErr: ErrAmbiguousRemote},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
remote, err := DiscoverRemote(context.Background(), test.runner, "/work", test.preferred)
|
||||
require.ErrorIs(t, err, test.wantErr)
|
||||
require.Equal(t, test.want, remote)
|
||||
})
|
||||
}
|
||||
_, err := DiscoverRemote(context.Background(), discoverRunner{}, "/work", "")
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package git contains subprocess boundaries, independent of command flags.
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Runner abstracts context-aware Git subprocess execution.
|
||||
type Runner interface {
|
||||
Output(context.Context, string, bool, ...string) (string, error)
|
||||
}
|
||||
|
||||
// CommandError carries Git's exit status without including command arguments or output.
|
||||
type CommandError struct{ ExitCode int }
|
||||
|
||||
func (*CommandError) Error() string {
|
||||
return "Git operation failed; check repository, remote, and credentials"
|
||||
}
|
||||
|
||||
// requireWorkTree fails unless run operates inside a Git working tree. action names the operation in the error.
|
||||
func requireWorkTree(run func(...string) (string, error), action string) error {
|
||||
inside, err := run("rev-parse", "--is-inside-work-tree")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if inside != "true" {
|
||||
return errors.New(action + " requires a Git working tree")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// System executes installed Git with explicit stream and prompting policy.
|
||||
type System struct {
|
||||
// Env overrides the subprocess environment when supplied.
|
||||
Env []string
|
||||
In io.Reader
|
||||
ErrOut io.Writer
|
||||
}
|
||||
|
||||
func setEnv(env []string, key, value string) []string {
|
||||
prefix := key + "="
|
||||
result := make([]string, 0, len(env)+1)
|
||||
for _, entry := range env {
|
||||
if !strings.HasPrefix(entry, prefix) {
|
||||
result = append(result, entry)
|
||||
}
|
||||
}
|
||||
return append(result, prefix+value)
|
||||
}
|
||||
|
||||
func networkSubcommand(args []string) bool {
|
||||
for index := 0; index < len(args); index++ {
|
||||
switch {
|
||||
case args[index] == "-c" || args[index] == "-C":
|
||||
index++
|
||||
case strings.HasPrefix(args[index], "-"):
|
||||
default:
|
||||
switch args[index] {
|
||||
case "push", "fetch", "pull", "ls-remote", "clone":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// batchSSHEnv makes SSH fail instead of prompting. A per-operation core.sshCommand
|
||||
// is preserved, and a GIT_SSH program (such as plink) is left untouched.
|
||||
func batchSSHEnv(ctx context.Context, dir string, env, args []string) []string {
|
||||
sshCommand, sshProgram := "", ""
|
||||
for _, entry := range env {
|
||||
if value, ok := strings.CutPrefix(entry, "GIT_SSH_COMMAND="); ok {
|
||||
sshCommand = value
|
||||
} else if value, ok := strings.CutPrefix(entry, "GIT_SSH="); ok {
|
||||
sshProgram = value
|
||||
}
|
||||
}
|
||||
if sshCommand == "" {
|
||||
configArgs := []string{}
|
||||
for index := 0; index+1 < len(args) && args[index] == "-c"; index += 2 {
|
||||
configArgs = append(configArgs, args[index:index+2]...)
|
||||
}
|
||||
configArgs = append(configArgs, "config", "--get", "core.sshCommand")
|
||||
config := exec.CommandContext(ctx, "git", configArgs...)
|
||||
config.Dir = dir
|
||||
config.Env = env
|
||||
data, _ := config.Output()
|
||||
sshCommand = strings.TrimSpace(string(data))
|
||||
}
|
||||
if sshCommand == "" {
|
||||
if sshProgram != "" {
|
||||
return env
|
||||
}
|
||||
sshCommand = "ssh"
|
||||
}
|
||||
if plink(env, sshCommand) {
|
||||
return setEnv(env, "GIT_SSH_COMMAND", sshCommand+" -batch")
|
||||
}
|
||||
return setEnv(env, "GIT_SSH_COMMAND", sshCommand+" -oBatchMode=yes")
|
||||
}
|
||||
|
||||
// plink reports whether Git treats sshCommand as PuTTY's plink, which rejects OpenSSH options.
|
||||
// Like Git, it honors GIT_SSH_VARIANT and otherwise looks at the program's base name.
|
||||
func plink(env []string, sshCommand string) bool {
|
||||
variant := ""
|
||||
for _, entry := range env {
|
||||
if value, ok := strings.CutPrefix(entry, "GIT_SSH_VARIANT="); ok {
|
||||
variant = value
|
||||
}
|
||||
}
|
||||
if variant == "" {
|
||||
program, _, _ := strings.Cut(sshCommand, " ")
|
||||
if quote := sshCommand[0]; quote == '"' || quote == '\'' {
|
||||
program, _, _ = strings.Cut(sshCommand[1:], string(quote))
|
||||
}
|
||||
variant = strings.TrimSuffix(strings.ToLower(program[strings.LastIndexAny(program, `/\`)+1:]), ".exe")
|
||||
}
|
||||
return variant == "plink" || variant == "tortoiseplink"
|
||||
}
|
||||
|
||||
// Output runs Git, suppressing credential prompts when interaction is disabled.
|
||||
func (s System) Output(ctx context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
cmd := exec.CommandContext(ctx, "git", args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Stderr = s.ErrOut
|
||||
env := append([]string(nil), s.Env...)
|
||||
if s.Env == nil {
|
||||
env = os.Environ()
|
||||
}
|
||||
if prompt {
|
||||
cmd.Stdin = s.In
|
||||
} else {
|
||||
env = setEnv(env, "GIT_TERMINAL_PROMPT", "0")
|
||||
env = setEnv(env, "GIT_ASKPASS", "")
|
||||
env = setEnv(env, "SSH_ASKPASS", "")
|
||||
env = setEnv(env, "SSH_ASKPASS_REQUIRE", "never")
|
||||
if networkSubcommand(args) {
|
||||
env = batchSSHEnv(ctx, dir, env, args)
|
||||
}
|
||||
}
|
||||
cmd.Env = env
|
||||
output, err := cmd.Output()
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
if failure, ok := errors.AsType[*exec.ExitError](err); ok {
|
||||
return "", &CommandError{ExitCode: failure.ExitCode()}
|
||||
}
|
||||
return "", errors.New("Git operation failed; check repository, remote, and credentials")
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kballard/go-shellquote"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNoInputPreservesPerOperationSSHCommand(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("fixture uses a POSIX shell executable")
|
||||
}
|
||||
directory := t.TempDir()
|
||||
log := filepath.Join(directory, "ssh-arguments")
|
||||
ssh := filepath.Join(directory, "ssh with spaces")
|
||||
require.NoError(t, os.WriteFile(ssh, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > "+shellquote.Join(log)+"\nexit 1\n"), 0o700))
|
||||
env := setEnv(os.Environ(), "GIT_SSH_COMMAND", "")
|
||||
env = setEnv(env, "GIT_SSH_VARIANT", "ssh")
|
||||
command := shellquote.Join(ssh, "-i", "/keys/key with spaces")
|
||||
_, err := (System{Env: env}).Output(context.Background(), directory, false, "-c", "core.sshCommand="+command, "ls-remote", "ssh://git@example.invalid/project.git")
|
||||
require.Error(t, err)
|
||||
data, err := os.ReadFile(log)
|
||||
require.NoError(t, err)
|
||||
args := strings.Split(strings.TrimSpace(string(data)), "\n")
|
||||
require.Contains(t, args, "/keys/key with spaces")
|
||||
require.Contains(t, args, "-oBatchMode=yes")
|
||||
}
|
||||
|
||||
func TestBatchSSHUsesPlinkOption(t *testing.T) {
|
||||
for _, tc := range []struct{ command, variant, want string }{
|
||||
{"ssh -i key", "", "ssh -i key -oBatchMode=yes"},
|
||||
{`"C:/Program Files/PuTTY/plink.exe" -P 2222`, "", `"C:/Program Files/PuTTY/plink.exe" -P 2222 -batch`},
|
||||
{`C:\PuTTY\TortoisePlink.exe`, "", `C:\PuTTY\TortoisePlink.exe -batch`},
|
||||
{"/usr/local/bin/wrapper", "plink", "/usr/local/bin/wrapper -batch"},
|
||||
{"/usr/bin/plink", "ssh", "/usr/bin/plink -oBatchMode=yes"},
|
||||
} {
|
||||
env := []string{"GIT_SSH_COMMAND=" + tc.command}
|
||||
if tc.variant != "" {
|
||||
env = append(env, "GIT_SSH_VARIANT="+tc.variant)
|
||||
}
|
||||
require.Contains(t, batchSSHEnv(context.Background(), "", env, []string{"fetch"}), "GIT_SSH_COMMAND="+tc.want, tc.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkSubcommand(t *testing.T) {
|
||||
for args, want := range map[string]bool{
|
||||
"push -- origin main": true, "-c core.sshCommand=ssh fetch origin": true, "-C /work ls-remote origin": true, "clone url": true,
|
||||
"rev-parse HEAD": false, "-c credential.helper=tea config --get core.sshCommand": false, "remote get-url origin": false, "": false,
|
||||
} {
|
||||
require.Equal(t, want, networkSubcommand(strings.Fields(args)), args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoInputKeepsGitSSHProgram(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("fixture uses a POSIX shell executable")
|
||||
}
|
||||
directory := t.TempDir()
|
||||
log := filepath.Join(directory, "ssh-arguments")
|
||||
ssh := filepath.Join(directory, "plink")
|
||||
require.NoError(t, os.WriteFile(ssh, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > "+shellquote.Join(log)+"\nexit 1\n"), 0o700))
|
||||
env := []string{}
|
||||
for _, entry := range os.Environ() {
|
||||
if !strings.HasPrefix(entry, "GIT_SSH_COMMAND=") {
|
||||
env = append(env, entry)
|
||||
}
|
||||
}
|
||||
env = setEnv(env, "GIT_CONFIG_GLOBAL", filepath.Join(directory, "gitconfig"))
|
||||
env = setEnv(env, "GIT_CONFIG_NOSYSTEM", "1")
|
||||
env = setEnv(env, "GIT_SSH_VARIANT", "ssh")
|
||||
env = setEnv(env, "GIT_SSH", ssh)
|
||||
_, err := (System{Env: env}).Output(context.Background(), directory, false, "ls-remote", "ssh://git@example.invalid/project.git")
|
||||
require.Error(t, err)
|
||||
data, err := os.ReadFile(log)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(data), "example.invalid")
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/kballard/go-shellquote"
|
||||
)
|
||||
|
||||
// SSHArguments selects a private key for one Git operation. Agent selection
|
||||
// retains the user's SSH configuration, as does an account without a key.
|
||||
func SSHArguments(key string, agent bool) ([]string, error) {
|
||||
if strings.ContainsAny(key, "\x00\r\n") {
|
||||
return nil, errors.New("SSH key path cannot contain NUL or line breaks")
|
||||
}
|
||||
if agent || key == "" {
|
||||
return nil, nil
|
||||
}
|
||||
command := shellquote.Join("ssh", "-i", key, "-oIdentitiesOnly=yes", "-oIdentityAgent=none")
|
||||
return []string{"-c", "core.sshCommand=" + command}, nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// SyncOptions selects one existing local branch and its source remote branch.
|
||||
type SyncOptions struct {
|
||||
Directory, Remote, Branch string
|
||||
CredentialArgs []string
|
||||
Prompt bool
|
||||
}
|
||||
|
||||
// SyncResult reports a completed local fast-forward.
|
||||
type SyncResult struct {
|
||||
Branch string `json:"branch"`
|
||||
Commit string `json:"commit"`
|
||||
Remote string `json:"remote"`
|
||||
}
|
||||
|
||||
// SyncBranch fetches and fast-forwards an existing branch without resetting commits.
|
||||
func SyncBranch(ctx context.Context, runner Runner, opts SyncOptions) (SyncResult, error) {
|
||||
run := func(args ...string) (string, error) { return runner.Output(ctx, opts.Directory, opts.Prompt, args...) }
|
||||
if opts.Remote == "" || opts.Branch == "" {
|
||||
return SyncResult{}, errors.New("sync requires a remote and branch")
|
||||
}
|
||||
if _, err := run("check-ref-format", "--branch", opts.Branch); err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
if err := requireWorkTree(run, "sync"); err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
status, err := run("status", "--porcelain=v1", "--untracked-files=normal")
|
||||
if err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
if status != "" {
|
||||
return SyncResult{}, errors.New("working tree has changes; commit or stash them before syncing")
|
||||
}
|
||||
localRef := "refs/heads/" + opts.Branch + "^{commit}"
|
||||
previous, err := run("rev-parse", "--verify", localRef)
|
||||
if err != nil {
|
||||
return SyncResult{}, fmt.Errorf("local branch is unavailable; create it before syncing: %w", err)
|
||||
}
|
||||
fetch := append([]string{}, opts.CredentialArgs...)
|
||||
fetch = append(fetch, "fetch", "--no-tags", "--", opts.Remote, "refs/heads/"+opts.Branch)
|
||||
if _, err := run(fetch...); err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
commit, err := run("rev-parse", "--verify", "FETCH_HEAD^{commit}")
|
||||
if err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
current, err := run("rev-parse", "--verify", localRef)
|
||||
if err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
if current != previous {
|
||||
return SyncResult{}, errors.New("local branch changed while fetching; retry sync")
|
||||
}
|
||||
if previous != commit {
|
||||
if _, err := run("merge-base", "--is-ancestor", previous, commit); err != nil {
|
||||
if failure, ok := errors.AsType[*CommandError](err); !ok || failure.ExitCode != 1 {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
if _, err := run("merge-base", "--is-ancestor", commit, previous); err != nil {
|
||||
return SyncResult{}, fmt.Errorf("branch cannot be fast-forwarded; resolve divergence before syncing: %w", err)
|
||||
}
|
||||
// The local branch already contains the remote history.
|
||||
commit = previous
|
||||
}
|
||||
}
|
||||
if _, err := run("switch", opts.Branch); err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
if previous != commit {
|
||||
if _, err := run("merge", "--ff-only", "--no-edit", commit); err != nil {
|
||||
return SyncResult{}, fmt.Errorf("branch was selected but sync failed: %w", err)
|
||||
}
|
||||
}
|
||||
actual, err := run("rev-parse", "--verify", "HEAD^{commit}")
|
||||
if err != nil {
|
||||
return SyncResult{}, fmt.Errorf("sync finished, but HEAD could not be verified: %w", err)
|
||||
}
|
||||
if actual != commit {
|
||||
return SyncResult{}, errors.New("HEAD changed during sync; inspect the working tree before retrying")
|
||||
}
|
||||
return SyncResult{Branch: opts.Branch, Commit: commit, Remote: opts.Remote}, nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSyncValidatesBeforeChangingBranches(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
dirty, diverged bool
|
||||
message string
|
||||
}{
|
||||
{true, false, "working tree has changes"},
|
||||
{false, true, "cannot be fast-forwarded"},
|
||||
} {
|
||||
runner := &checkoutRunner{dirty: test.dirty, diverged: test.diverged, localCommit: "previous"}
|
||||
_, err := SyncBranch(context.Background(), runner, SyncOptions{Directory: "/work", Remote: "origin", Branch: "main"})
|
||||
require.ErrorContains(t, err, test.message)
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
require.False(t, strings.HasPrefix(call, "merge "))
|
||||
if test.dirty {
|
||||
require.False(t, strings.HasPrefix(call, "fetch "))
|
||||
}
|
||||
}
|
||||
}
|
||||
runner := &checkoutRunner{localCommit: "previous"}
|
||||
result, err := SyncBranch(context.Background(), runner, SyncOptions{Directory: "/work", Remote: "origin", Branch: "main", CredentialArgs: []string{"-c", "credential.helper=tea"}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, SyncResult{Branch: "main", Commit: "abc123", Remote: "origin"}, result)
|
||||
require.Contains(t, runner.calls, "-c credential.helper=tea fetch --no-tags -- origin refs/heads/main")
|
||||
require.Equal(t, []string{"switch main", "merge --ff-only --no-edit abc123", "rev-parse --verify HEAD^{commit}"}, runner.calls[len(runner.calls)-3:])
|
||||
}
|
||||
|
||||
type syncFailureRunner struct {
|
||||
checkoutRunner
|
||||
missing, changed bool
|
||||
reads int
|
||||
}
|
||||
|
||||
func (r *syncFailureRunner) Output(ctx context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
if len(args) == 3 && args[0] == "rev-parse" && strings.HasPrefix(args[2], "refs/heads/") {
|
||||
r.reads++
|
||||
if r.missing {
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
if r.changed && r.reads == 2 {
|
||||
return "other-commit", nil
|
||||
}
|
||||
}
|
||||
return r.checkoutRunner.Output(ctx, dir, prompt, args...)
|
||||
}
|
||||
|
||||
func TestSyncRejectsMissingOrChangedBranch(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
missing, changed bool
|
||||
message string
|
||||
}{
|
||||
{true, false, "local branch is unavailable"},
|
||||
{false, true, "local branch changed while fetching"},
|
||||
} {
|
||||
runner := &syncFailureRunner{missing: test.missing, changed: test.changed}
|
||||
_, err := SyncBranch(context.Background(), runner, SyncOptions{Directory: "/work", Remote: "origin", Branch: "main"})
|
||||
require.ErrorContains(t, err, test.message)
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "switch "))
|
||||
require.False(t, strings.HasPrefix(call, "merge "))
|
||||
if test.missing {
|
||||
require.False(t, strings.HasPrefix(call, "fetch "))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type aheadSyncRunner struct{ checkoutRunner }
|
||||
|
||||
func (r *aheadSyncRunner) Output(ctx context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
if len(args) == 3 && args[2] == "HEAD^{commit}" {
|
||||
r.calls = append(r.calls, strings.Join(args, " "))
|
||||
return r.localCommit, nil
|
||||
}
|
||||
if len(args) == 4 && args[0] == "merge-base" && args[2] == "previous" {
|
||||
r.calls = append(r.calls, strings.Join(args, " "))
|
||||
return "", &CommandError{ExitCode: 1}
|
||||
}
|
||||
return r.checkoutRunner.Output(ctx, dir, prompt, args...)
|
||||
}
|
||||
|
||||
func TestSyncPreservesBranchAheadOfRemote(t *testing.T) {
|
||||
runner := &aheadSyncRunner{localCommit: "previous"}
|
||||
result, err := SyncBranch(context.Background(), runner, SyncOptions{Directory: "/work", Remote: "origin", Branch: "main"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "previous", result.Commit)
|
||||
require.Contains(t, runner.calls, "merge-base --is-ancestor abc123 previous")
|
||||
require.Equal(t, "switch main", runner.calls[len(runner.calls)-2])
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "merge "))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncEqualHistoryDoesNotMerge(t *testing.T) {
|
||||
runner := &checkoutRunner{}
|
||||
result, err := SyncBranch(context.Background(), runner, SyncOptions{Directory: "/work", Remote: "origin", Branch: "main"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "abc123", result.Commit)
|
||||
for _, call := range runner.calls {
|
||||
require.False(t, strings.HasPrefix(call, "merge-base "))
|
||||
require.False(t, strings.HasPrefix(call, "merge "))
|
||||
}
|
||||
}
|
||||
|
||||
type changedHeadRunner struct{ checkoutRunner }
|
||||
|
||||
func (r *changedHeadRunner) Output(ctx context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
if len(args) == 3 && args[2] == "HEAD^{commit}" {
|
||||
return "unexpected", nil
|
||||
}
|
||||
return r.checkoutRunner.Output(ctx, dir, prompt, args...)
|
||||
}
|
||||
|
||||
func TestSyncRejectsUnexpectedFinalHead(t *testing.T) {
|
||||
runner := &changedHeadRunner{}
|
||||
result, err := SyncBranch(context.Background(), runner, SyncOptions{Directory: "/work", Remote: "origin", Branch: "main"})
|
||||
require.ErrorContains(t, err, "HEAD changed during sync")
|
||||
require.Equal(t, SyncResult{}, result)
|
||||
}
|
||||
Reference in new issue
Block a user