Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 125 additions & 9 deletions internal/cli/pr.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"os/exec"
"regexp"
"strconv"
"strings"

Expand Down Expand Up @@ -48,20 +49,32 @@ func prViewCmd() *cobra.Command {
)

cmd := &cobra.Command{
Use: "view <number>",
Use: "view [<number>]",
Short: "View a pull request",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
number, err := strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("invalid PR number: %s", args[0])
}
Long: `View a pull request by number, or view the PR for the current branch.

If no number is given, finds and displays the pull request whose head
branch matches the current git branch.`,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
forge, owner, repoName, _, err := resolve.Repo(flagRepo, flagForgeType)
if err != nil {
return err
}

var number int
if len(args) > 0 {
number, err = strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("invalid PR number: %s", args[0])
}
} else {
number, err = findPRForCurrentBranch(cmd.Context(), forge, owner, repoName)
if err != nil {
return err
}
}

pr, err := forge.PullRequests().Get(cmd.Context(), owner, repoName, number)
if err != nil {
return fmt.Errorf("getting PR #%d: %w", number, err)
Expand Down Expand Up @@ -611,10 +624,20 @@ The argument can be a PR number or a full URL:
}

if pr.Head.Fork != nil {
return checkoutForkPR(ctx, domain, pr, remoteRef, localBranch, flagRemoteName, flagDetach, flagForce)
err = checkoutForkPR(ctx, domain, pr, remoteRef, localBranch, flagRemoteName, flagDetach, flagForce)
} else {
err = checkoutSameRepoPR(ctx, remoteRef, localBranch, flagDetach, flagForce)
}
if err != nil {
return err
}

return checkoutSameRepoPR(ctx, remoteRef, localBranch, flagDetach, flagForce)
// Cache the PR number for the branch only after a successful
// checkout, so a failed checkout doesn't leave a stale entry.
if !flagDetach {
_ = storePRForBranch(ctx, localBranch, number)
}
return nil
},
}

Expand Down Expand Up @@ -744,3 +767,96 @@ func gitCheckout(ctx context.Context, remote, remoteRef, localBranch string, det
resetCmd.Stderr = os.Stderr
return resetCmd.Run()
}

func findPRForCurrentBranch(ctx context.Context, f forges.Forge, owner, repo string) (int, error) {
out, err := exec.CommandContext(ctx, "git", "branch", "--show-current").Output()
if err != nil {
return 0, fmt.Errorf("getting current branch: %w (not in a git repository?)", err)
}
localBranch := strings.TrimSpace(string(out))
if localBranch == "" {
return 0, fmt.Errorf("not on a branch (detached HEAD state)")
}

// Check cache first (set by 'pr checkout')
if n, err := loadPRForBranch(ctx, localBranch); err == nil {
return n, nil
}

// If that yields nothing, fall back to API query. This API call is really
// slow for Gitea since the Head filter is not actually implemented.
headOwner := owner
if remoteOwner, err := resolve.OwnerForBranch(ctx, localBranch); err == nil {
headOwner = remoteOwner
}

// TODO: Limit 100 with no pagination means repos with >100 PRs may miss
// the match on a fresh checkout (cache hides this in normal use).
prs, err := f.PullRequests().List(ctx, owner, repo, forges.ListPROpts{
Head: headOwner + ":" + localBranch,
State: "all",
Limit: 100,
})
if err != nil {
return 0, fmt.Errorf("listing PRs for branch %q: %w", localBranch, err)
}

// Need to filter the results again for owner:branch since the API results
// don't respect the filter in case of Gitea.
var matching []forges.PullRequest
for _, pr := range prs {
prHeadOwner := owner
if pr.Head.Fork != nil {
prHeadOwner = pr.Head.Fork.Owner
}
if pr.Head.Ref == localBranch && prHeadOwner == headOwner {
matching = append(matching, pr)
}
}

if len(matching) < 1 {
return 0, fmt.Errorf("no pull request found for branch %q", localBranch)
}

// Prefer open PRs over closed/merged ones (a branch may be reused)
for _, pr := range matching {
if pr.State == "open" {
// Store the PR number into local git config so that the next 'forge
// pr view' call is a lot faster.
_ = storePRForBranch(ctx, localBranch, pr.Number)
return pr.Number, nil
}
}

// No open PR, return the first match (closed/merged) but don't cache it
return matching[0].Number, nil
}

func storePRForBranch(ctx context.Context, branch string, number int) error {
key := fmt.Sprintf("branch.%s.forge-pr", branch)
return exec.CommandContext(ctx, "git", "config", "--local", key, strconv.Itoa(number)).Run()
}

var prRefRE = regexp.MustCompile(`^refs/pull/(\d+)/head$`)

func loadPRForBranch(ctx context.Context, branch string) (int, error) {
key := fmt.Sprintf("branch.%s.forge-pr", branch)
out, err := exec.CommandContext(ctx, "git", "config", "--get", key).Output()
if err == nil {
return strconv.Atoi(strings.TrimSpace(string(out)))
}

// Fall back to gh CLI's format (refs/pull/<n>/head in branch.<name>.merge).
// The regex only matches refs/pull/<n>/head, so refs/heads/* values are
// safely rejected.
mergeKey := fmt.Sprintf("branch.%s.merge", branch)
out, err = exec.CommandContext(ctx, "git", "config", "--get", mergeKey).Output()
if err != nil {
return 0, err
}
m := prRefRE.FindStringSubmatch(strings.TrimSpace(string(out)))
if m == nil {
return 0, fmt.Errorf("not a PR ref")
}
return strconv.Atoi(m[1])
}
96 changes: 23 additions & 73 deletions internal/cli/pr_checkout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,18 @@ import (

// mockPRService implements forges.PullRequestService for testing.
type mockPRService struct {
pr *forges.PullRequest
err error
pr *forges.PullRequest
err error
listResult []forges.PullRequest
listErr error
}

func (m *mockPRService) Get(_ context.Context, _, _ string, _ int) (*forges.PullRequest, error) {
return m.pr, m.err
}

func (m *mockPRService) List(_ context.Context, _, _ string, _ forges.ListPROpts) ([]forges.PullRequest, error) {
return nil, nil
return m.listResult, m.listErr
}

func (m *mockPRService) Create(_ context.Context, _, _ string, _ forges.CreatePROpts) (*forges.PullRequest, error) {
Expand Down Expand Up @@ -110,39 +112,19 @@ func setupTestRepo(t *testing.T, originURL string) string {
t.Helper()
dir := t.TempDir()

commands := [][]string{
{"git", "init"},
{"git", "config", "user.email", "test@test.com"},
{"git", "config", "user.name", "Test User"},
}

for _, args := range commands {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git command %v failed: %v\n%s", args, err, out)
}
}
mustGit(t, dir, "init")
mustGit(t, dir, "config", "user.email", "test@test.com")
mustGit(t, dir, "config", "user.name", "Test User")

// Create an initial commit so we have a valid HEAD
testFile := filepath.Join(dir, "README.md")
if err := os.WriteFile(testFile, []byte("# Test\n"), 0644); err != nil {
t.Fatalf("writing test file: %v", err)
}

commands = [][]string{
{"git", "add", "README.md"},
{"git", "commit", "-m", "Initial commit"},
{"git", "remote", "add", "origin", originURL},
}

for _, args := range commands {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git command %v failed: %v\n%s", args, err, out)
}
}
mustGit(t, dir, "add", "README.md")
mustGit(t, dir, "commit", "-m", "Initial commit")
mustGit(t, dir, "remote", "add", "origin", originURL)

return dir
}
Expand All @@ -152,11 +134,7 @@ func setupBareRepo(t *testing.T) string {
t.Helper()
dir := t.TempDir()

cmd := exec.Command("git", "init", "--bare")
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git init --bare failed: %v\n%s", err, out)
}
mustGit(t, dir, "init", "--bare")

return dir
}
Expand All @@ -171,21 +149,11 @@ func pushBranchToRemote(t *testing.T, repoDir, remoteName, branchName string) {
t.Fatalf("writing test file: %v", err)
}

commands := [][]string{
{"git", "checkout", "-b", branchName},
{"git", "add", "."},
{"git", "commit", "-m", "Add " + branchName},
{"git", "push", remoteName, branchName},
{"git", "checkout", "-"},
}

for _, args := range commands {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = repoDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git command %v failed: %v\n%s", args, err, out)
}
}
mustGit(t, repoDir, "checkout", "-b", branchName)
mustGit(t, repoDir, "add", ".")
mustGit(t, repoDir, "commit", "-m", "Add "+branchName)
mustGit(t, repoDir, "push", remoteName, branchName)
mustGit(t, repoDir, "checkout", "-")
}

func TestEnsureRemote(t *testing.T) {
Expand Down Expand Up @@ -249,20 +217,10 @@ func TestEnsureRemote(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
dir := t.TempDir()

commands := [][]string{
{"git", "init"},
{"git", "config", "user.email", "test@test.com"},
{"git", "config", "user.name", "Test User"},
{"git", "remote", "add", "origin", tt.existingURL},
}

for _, args := range commands {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git command %v failed: %v\n%s", args, err, out)
}
}
mustGit(t, dir, "init")
mustGit(t, dir, "config", "user.email", "test@test.com")
mustGit(t, dir, "config", "user.name", "Test User")
mustGit(t, dir, "remote", "add", "origin", tt.existingURL)

t.Chdir(dir)

Expand Down Expand Up @@ -448,17 +406,9 @@ func TestPRCheckout(t *testing.T) {
tt.pr.Head.Fork.CloneURL = forkDir

branchName := tt.pr.Head.Ref
cmd := exec.Command("git", "remote", "add", "tempfork", forkDir)
cmd.Dir = workDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("adding temp fork remote: %v\n%s", err, out)
}
mustGit(t, workDir, "remote", "add", "tempfork", forkDir)
pushBranchToRemote(t, workDir, "tempfork", branchName)
cmd = exec.Command("git", "remote", "remove", "tempfork")
cmd.Dir = workDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("removing temp fork remote: %v\n%s", err, out)
}
mustGit(t, workDir, "remote", "remove", "tempfork")
}
} else if tt.pr != nil {
// For error tests that still need a git context, create a minimal repo
Expand Down
Loading
Loading