feat(pr): merge with the repository's defaults, ready, gh flags and ✓ lines for pr mutations

pr merge takes the method from the repository's default merge style
instead of always merging (D22), accepts gh's --merge, --squash and
--rebase next to -s/--method, refuses methods the repository disables,
and adds -d/--delete-branch (defaulting to the repository setting),
--auto, -t, -b, -F and -e. On a terminal it asks for the method and
branch deletion with the defaults preselected, without a picker when
the current branch has a pull request. It reports "✓ Squashed and
merged pull request alice/x#3 (title)", the deleted remote branch, and
switches off and deletes the local head branch; --json returns the
merged pull request. Merged, closed and draft pull requests are
reported before anything is asked. -s without a value points at
--squash.

pr checkout names the local branch after the head branch when that
name is free or already at the head, falling back to OWNER/BRANCH for
forks and pr/NUMBER (D13), fetches and switches quietly, reports
"✓ Checked out #1 into feat/one", and has the alias co. pr clean
reports what it deleted and that a remote branch was already gone.

pr create asks for the title and body, then "What's next?": submit,
submit as a draft, add metadata or change the branches, without the
AGit question up front or a final confirmation. It pushes an unpushed
head with --set-upstream --quiet ("✓ Pushed feat/one to origin"),
prints "✓ Created pull request alice/x#9 (title)" and the URL, and
adds --fill, --web, the alias new, the gh shorthands, and milestones
by title.

New tea pr ready [--undo]. pr close and reopen take -c/--comment,
close takes -d/--delete-branch, and both say when the pull request
already is in that state. pr edit reports "✓ Edited", takes the
singular gh reviewer flags (the plurals still work), milestones by
title and --remove-milestone. pr diff is colored and paged on a
terminal and byte-exact when piped, with --name-only, --color and
--web. Every pull request argument accepts #N, URLs and branch names
and defaults to the current branch's pull request.

Signed-off-by: bircni <bircni@icloud.com>
This commit is contained in:
bircni committed 2026-10-11 23:55:11 +02:00
1 parent 2c5e005bcf
commit 4895aa089d
28 files changed
+1169 -504

No files matched your search

+52 -3
View File
@@ -17,9 +17,35 @@ type MergePullChoice struct {
Title, Head string
}
// MergeForm collects which pull request to merge.
// MergeMethodLabels describe Gitea's merge styles in the merge form.
var MergeMethodLabels = map[string]string{
"merge": "Create a merge commit", "rebase": "Rebase and merge", "rebase-merge": "Rebase and create a merge commit",
"squash": "Squash and merge", "fast-forward-only": "Fast-forward only",
}
// MergeFormChoices describes the pull request to merge and what the form asks about it.
type MergeFormChoices struct {
// Header introduces the form, such as `Merge #3 "Merge me" (feat/merge-me → main) in alice/x`.
Header string
// Methods are the merge styles the repository allows; Method preselects one. Without Methods,
// the form does not ask for one.
Methods []string
Method string
// DeleteBranch preselects whether to delete the head branch; Branch, when set, asks it.
DeleteBranch bool
Branch string
}
// MergeFormValues are the chosen merge style and whether to delete the head branch.
type MergeFormValues struct {
Method string
DeleteBranch bool
}
// MergeForm collects which pull request to merge, and how.
type MergeForm interface {
SelectPull(context.Context, []MergePullChoice) (int64, error)
MergeOptions(context.Context, MergeFormChoices) (MergeFormValues, error)
}
// SelectPull prompts for a pull request on stderr.
@@ -29,11 +55,34 @@ func (p *FormPrompter) SelectPull(ctx context.Context, choices []MergePullChoice
}
options := make([]huh.Option[int64], 0, len(choices))
for _, choice := range choices {
options = append(options, huh.NewOption(fmt.Sprintf("#%d: %s (%s)", choice.Number, choice.Title, choice.Head), choice.Number))
options = append(options, huh.NewOption(SafeLine(fmt.Sprintf("#%d %s (%s)", choice.Number, choice.Title, choice.Head)), choice.Number))
}
selected := choices[0].Number
err := p.runForm(ctx, huh.NewForm(huh.NewGroup(
huh.NewSelect[int64]().Title("Select a PR to merge:").Options(options...).Value(&selected),
huh.NewSelect[int64]().Title("Pull request to merge:").Options(options...).Value(&selected),
)))
return selected, err
}
// MergeOptions asks for the merge style and whether to delete the head branch, on stderr.
func (p *FormPrompter) MergeOptions(ctx context.Context, choices MergeFormChoices) (MergeFormValues, error) {
values := MergeFormValues{Method: choices.Method, DeleteBranch: choices.DeleteBranch}
var fields []huh.Field
if len(choices.Methods) > 0 {
options := make([]huh.Option[string], len(choices.Methods))
for i, method := range choices.Methods {
options[i] = huh.NewOption(MergeMethodLabels[method], method)
}
fields = append(fields, huh.NewSelect[string]().Title("Merge method:").Options(options...).Value(&values.Method))
}
if choices.Branch != "" {
fields = append(fields, huh.NewConfirm().Title(SafeLine(fmt.Sprintf("Delete branch %s locally and on Gitea?", choices.Branch))).Value(&values.DeleteBranch))
}
if choices.Header != "" {
fmt.Fprintln(p.Streams.ErrOut, SafeLine(choices.Header))
}
if len(fields) == 0 {
return values, nil
}
return values, p.runForm(ctx, huh.NewForm(huh.NewGroup(fields...)))
}
+123 -56
View File
@@ -5,6 +5,7 @@ package terminal
import (
"context"
"fmt"
"strings"
"unicode"
"unicode/utf8"
@@ -14,6 +15,8 @@ import (
// PullFormChoices supplies defaults and selectable options for interactive PR create.
type PullFormChoices struct {
// Repo is the base repository, named in the form's header.
Repo string
BaseOwner, Base, HeadOwner, HeadBranch string
// Title and Body seed the form; Title applies only while HeadBranch is kept.
Title, Body string
@@ -21,8 +24,9 @@ type PullFormChoices struct {
Assignees []string
Milestones []IssueMilestoneChoice
Labels []IssueLabelChoice
CanPush bool
EditBody BodyEditor
// CanPush offers metadata, which needs push access; without it, changing branches offers AGit.
CanPush bool
EditBody BodyEditor
}
// PullFormValues holds interactively collected pull request create fields.
@@ -31,6 +35,8 @@ type PullFormValues struct {
Agit bool
Base, Head, Topic string
AllowMaintainerEdits bool
// AsDraft submits the pull request as a draft.
AsDraft bool
}
// PullForm collects interactive pull create input.
@@ -38,69 +44,130 @@ type PullForm interface {
CreatePull(context.Context, PullFormChoices) (PullFormValues, error)
}
// CreatePull runs the interactive pull create form on stderr.
// pullNext is what the user does after writing a pull request's title and body.
type pullNext int
const (
pullSubmit pullNext = iota
pullSubmitDraft
pullMetadata
pullBranches
pullCancel
)
// CreatePull runs the interactive pull create form on stderr, like gh pr create: the title and
// body of a pull request from the current branch, then "What's next?" to submit it, submit it as a
// draft, add metadata, change the branches or cancel. Branches are asked first when unknown.
func (p *FormPrompter) CreatePull(ctx context.Context, choices PullFormChoices) (PullFormValues, error) {
agit, err := p.Confirm(ctx, "Do you want to create an agit flow pull request?")
if err != nil {
return PullFormValues{}, err
}
base := choices.Base
headOwner := choices.HeadOwner
headBranch := choices.HeadBranch
topic := headBranch
allowMaintainerEdits := choices.AllowMaintainerEdits
fields := []huh.Field{
huh.NewInput().Title("Target branch (required):").Value(&base).Validate(huh.ValidateNotEmpty()),
}
if agit {
fields = append(fields, huh.NewInput().Title("Topic branch (required):").Value(&topic).Validate(huh.ValidateNotEmpty()))
} else {
headField := huh.NewInput().Title("Source branch:").Value(&headBranch)
if strings.TrimSpace(headBranch) == "" {
headField = headField.Title("Source branch (required):").Validate(huh.ValidateNotEmpty())
branches := pullBranchFields{base: choices.Base, headOwner: choices.HeadOwner, headBranch: choices.HeadBranch, allowEdits: choices.AllowMaintainerEdits}
branches.topic = branches.headBranch
if strings.TrimSpace(branches.base) == "" || strings.TrimSpace(branches.headBranch) == "" {
if err := p.runForm(ctx, huh.NewForm(huh.NewGroup(branches.fields(!choices.CanPush)...))); err != nil {
return PullFormValues{}, err
}
fields = append(fields,
huh.NewInput().Title("Source repo owner:").Value(&headOwner),
headField,
huh.NewConfirm().Title("Allow maintainers to push to the source branch:").Value(&allowMaintainerEdits),
)
}
if err := p.runForm(ctx, huh.NewForm(huh.NewGroup(fields...))); err != nil {
return PullFormValues{}, err
}
fmt.Fprintln(p.Streams.ErrOut, SafeLine(branches.header(choices.Repo, choices.BaseOwner)))
title := DefaultPullTitle(headBranch)
if choices.Title != "" && headBranch == choices.HeadBranch {
title := DefaultPullTitle(branches.headBranch)
if choices.Title != "" && branches.headBranch == choices.HeadBranch {
title = choices.Title
}
// AGit pushes carry only a title and description.
properties, err := p.collectIssueProperties(ctx, title, choices.Body, IssueFormChoices{
Assignees: choices.Assignees, Milestones: choices.Milestones, Labels: choices.Labels, CanPush: choices.CanPush && !agit,
EditBody: choices.EditBody,
})
if err != nil {
return PullFormValues{IssueFormValues: properties}, err
fields := issueFields{title: title, body: choices.Body}
content := []huh.Field{titleField(&fields.title)}
if choices.EditBody == nil {
content = append(content, bodyField(BodyTitle, &fields.body))
}
if err := p.runForm(ctx, huh.NewForm(huh.NewGroup(content...))); err != nil {
return PullFormValues{}, err
}
values := PullFormValues{}
var err error
if values.Body, values.Draft, err = editBody(ctx, choices.EditBody, fields.body); err != nil {
return values, err
}
for next := pullMetadata; next == pullMetadata || next == pullBranches; {
metadata := choices.CanPush && !branches.agit && (len(choices.Assignees)+len(choices.Milestones)+len(choices.Labels) > 0)
options := []huh.Option[pullNext]{huh.NewOption("Submit", pullSubmit)}
if !branches.agit {
options = append(options, huh.NewOption("Submit as draft", pullSubmitDraft))
}
if metadata {
options = append(options, huh.NewOption("Add metadata (assignees, labels, milestone, due date)", pullMetadata))
}
options = append(options, huh.NewOption("Change branches", pullBranches), huh.NewOption("Cancel", pullCancel))
next = pullSubmit
if err := p.runForm(ctx, huh.NewForm(huh.NewGroup(huh.NewSelect[pullNext]().Title("What's next?").Options(options...).Value(&next)))); err != nil {
return values, err
}
switch next {
case pullMetadata:
groups := fields.groups(noBody, true, choices.Assignees, choices.Milestones, choices.Labels)[1:]
if err := p.runForm(ctx, huh.NewForm(groups...)); err != nil {
return values, err
}
case pullBranches:
if err := p.runForm(ctx, huh.NewForm(huh.NewGroup(branches.fields(!choices.CanPush)...))); err != nil {
return values, err
}
fmt.Fprintln(p.Streams.ErrOut, SafeLine(branches.header(choices.Repo, choices.BaseOwner)))
case pullCancel:
return values, ErrCanceled
}
values.AsDraft = next == pullSubmitDraft
}
values.Title, values.Assignees, values.Milestone, values.Labels = strings.TrimSpace(fields.title), fields.assignees, fields.milestone, fields.labels
if values.Deadline, err = parseDueDate(fields.deadline); err != nil {
return values, err
}
values.Agit, values.Base, values.Topic, values.AllowMaintainerEdits = branches.agit, strings.TrimSpace(branches.base), strings.TrimSpace(branches.topic), branches.allowEdits
values.Head = branches.head(choices.BaseOwner)
return values, nil
}
headBranch = strings.TrimSpace(headBranch)
headOwner = strings.TrimSpace(headOwner)
head := headBranch
switch {
case agit && head == "":
head = "HEAD"
case !agit && headOwner != "" && headOwner != choices.BaseOwner:
head = headOwner + ":" + headBranch
// noBody keeps the body out of issueFields.groups, which the pull request form asks separately.
func noBody(context.Context, string) (Draft, error) { return Draft{}, nil }
// pullBranchFields are the branches of a new pull request.
type pullBranchFields struct {
base, headOwner, headBranch, topic string
allowEdits, agit bool
}
// fields asks for the branches; offerAgit adds the choice of an AGit push for users who cannot
// push to the base repository.
func (b *pullBranchFields) fields(offerAgit bool) []huh.Field {
fields := []huh.Field{huh.NewInput().Title("Base branch (required):").Value(&b.base).Validate(huh.ValidateNotEmpty())}
if offerAgit {
fields = append(fields, huh.NewConfirm().Title("Push through AGit (refs/for) instead of a branch of your own?").Value(&b.agit))
}
return PullFormValues{
IssueFormValues: properties,
Agit: agit,
Base: strings.TrimSpace(base),
Head: head,
Topic: strings.TrimSpace(topic),
AllowMaintainerEdits: allowMaintainerEdits,
}, nil
return append(fields,
huh.NewInput().Title("Head repository owner:").Value(&b.headOwner),
huh.NewInput().Title("Head branch (required):").Value(&b.headBranch).Validate(huh.ValidateNotEmpty()),
huh.NewInput().Title("AGit topic (when pushing through AGit):").Value(&b.topic),
huh.NewConfirm().Title("Allow maintainers to push to the head branch?").Value(&b.allowEdits),
)
}
// head is the head of the pull request: BRANCH, OWNER:BRANCH for a head in another repository, or
// HEAD for an AGit push without a branch.
func (b *pullBranchFields) head(baseOwner string) string {
branch, owner := strings.TrimSpace(b.headBranch), strings.TrimSpace(b.headOwner)
switch {
case b.agit && branch == "":
return "HEAD"
case !b.agit && owner != "" && owner != baseOwner:
return owner + ":" + branch
}
return branch
}
// header introduces the pull request: "Creating pull request for feat/one into main in alice/x".
func (b *pullBranchFields) header(repo, baseOwner string) string {
text := fmt.Sprintf("Creating pull request for %s into %s", b.head(baseOwner), strings.TrimSpace(b.base))
if repo != "" {
text += " in " + repo
}
return text
}
// DefaultPullTitle turns a branch-like head into a readable pull title seed.
+45 -46
View File
@@ -7,7 +7,6 @@ import (
"context"
"errors"
"path/filepath"
"sync"
"testing"
"time"
@@ -26,73 +25,73 @@ func TestDefaultPullTitle(t *testing.T) {
}
}
func TestPullFormMarksRequiredFields(t *testing.T) {
func TestPullFormAsksTitleBodyThenWhatsNext(t *testing.T) {
known := PullFormChoices{Repo: "alice/x", BaseOwner: "alice", Base: "main", HeadOwner: "alice", HeadBranch: "feature", Title: "Seeded", Body: "Seeded body", AllowMaintainerEdits: true}
for _, tc := range []struct {
name, input string
choices PullFormChoices
want, without []string
name, input string
choices PullFormChoices
want PullFormValues
err error
rendered []string
hidden []string
}{
{
"without head", "n\nmain\nalice\nfeature\ny\nTitle\n",
PullFormChoices{},
[]string{"Target branch (required):", "Source branch (required):", "Title (required):"},
nil,
name: "submit", input: "Seeded\n\n1\n", choices: known,
want: PullFormValues{IssueFormValues: IssueFormValues{Title: "Seeded", Body: "Seeded body"}, Base: "main", Head: "feature", Topic: "feature", AllowMaintainerEdits: true},
rendered: []string{"Creating pull request for feature into main in alice/x", "Title (required):", BodyTitle, "What's next?", "Change branches"},
hidden: []string{"Base branch", "AGit", "Issue", "Add metadata"},
},
{
"with head", "n\n\n\n\n\nTitle\n",
PullFormChoices{Base: "main", HeadOwner: "alice", HeadBranch: "feature"},
[]string{"Source branch:", "Allow maintainers to push to the source branch:"},
[]string{"Source branch (required)"},
name: "submit as draft", input: "Add login\n\n2\n", choices: known,
want: PullFormValues{IssueFormValues: IssueFormValues{Title: "Add login", Body: "Seeded body"}, Base: "main", Head: "feature", Topic: "feature", AllowMaintainerEdits: true, AsDraft: true},
},
{name: "cancel", input: "Seeded\n\n4\n", choices: known, err: ErrCanceled},
{
name: "unknown head asks the branches first", input: "main\nn\nbob\nfix-typo\n\n\nFix Typo\n\n1\n", choices: PullFormChoices{Repo: "alice/x", BaseOwner: "alice", Base: "main"},
want: PullFormValues{IssueFormValues: IssueFormValues{Title: "Fix Typo"}, Base: "main", Head: "bob:fix-typo"},
rendered: []string{"Base branch (required):", "Push through AGit", "Head branch (required):", "Creating pull request for bob:fix-typo into main in alice/x"},
},
{
name: "metadata", input: "Seeded\n\n3\n2\n2026-12-24\n1\n", choices: func() PullFormChoices {
c := known
c.CanPush, c.Milestones = true, []IssueMilestoneChoice{{Title: "v1.0", ID: 4}}
return c
}(),
want: PullFormValues{IssueFormValues: IssueFormValues{Title: "Seeded", Body: "Seeded body", Milestone: 4, Deadline: mustDueDate(t, "2026-12-24")}, Base: "main", Head: "feature", Topic: "feature", AllowMaintainerEdits: true},
rendered: []string{"Add metadata (assignees, labels, milestone, due date)", "Milestone:", "Due date:"},
},
{"agit", "y\nmain\ntopic\nTitle\n", PullFormChoices{}, []string{"Topic branch (required):"}, nil},
} {
t.Run(tc.name, func(t *testing.T) {
p, rendered := accessiblePrompter(t, tc.input)
tc.choices.EditBody = noEdit
_, err := p.CreatePull(context.Background(), tc.choices)
p, rendered := linePrompter(t, tc.input)
values, err := p.CreatePull(context.Background(), tc.choices)
if tc.err != nil {
require.ErrorIs(t, err, tc.err)
return
}
require.NoError(t, err)
for _, want := range tc.want {
require.Equal(t, tc.want, values)
for _, want := range tc.rendered {
require.Contains(t, rendered.String(), want)
}
for _, unwanted := range tc.without {
for _, unwanted := range tc.hidden {
require.NotContains(t, rendered.String(), unwanted)
}
})
}
}
// stagedInput feeds one form's keystrokes per stage. A finished form's canceled read loop can still be inside Read,
// and bubbletea drops the byte that Read returns. When a stage runs dry, the finished form's loop blocks first and
// the next form's loop second, so the next stage is handed to that second reader and never to the stale one.
type stagedInput struct {
mu sync.Mutex
cur string
stages []string
idle int
}
func (s *stagedInput) Read(p []byte) (int, error) {
s.mu.Lock()
for s.cur == "" {
s.idle++
if s.idle < 2 || len(s.stages) == 0 {
s.mu.Unlock()
select {} // no more input for this reader; the loop is abandoned with its form
}
s.cur, s.stages, s.idle = s.stages[0], s.stages[1:], 0
}
p[0], s.cur = s.cur[0], s.cur[1:]
s.mu.Unlock()
return 1, nil
func mustDueDate(t *testing.T, raw string) *time.Time {
t.Helper()
due, err := parseDueDate(raw)
require.NoError(t, err)
return due
}
func TestCreatePullPreservesDraftOnEditorFailure(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
path := filepath.Join(t.TempDir(), "draft.md")
called := false
p, _ := testPrompter(&stagedInput{cur: "n\r", stages: []string{"main\ralice\rfeature\ry\r", "Title\r"}})
values, err := p.CreatePull(ctx, PullFormChoices{
p, _ := linePrompter(t, "Title\n")
values, err := p.CreatePull(context.Background(), PullFormChoices{
BaseOwner: "alice", Base: "main", HeadOwner: "alice", HeadBranch: "feature",
EditBody: func(context.Context, string) (Draft, error) {
called = true