Files
gitea-tea/internal/git/checkout.go
T
bircni 88b91faa54 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>
2026-10-11 17:09:37 +00:00

157 lines
6.1 KiB
Go

// 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
}