feat(pr): list pull requests in a table and render issue and pr views as views

tea pr list prints a header, a "Showing N of M" line and the ID, TITLE,
BRANCH, STATE, AUTHOR and CREATED columns on a terminal, fit to its
width, and tab-separated rows when piped. Fork heads read
OWNER:BRANCH, drafts and merged pull requests have their own state,
and STATE appears on a terminal only when --state is not open. New
filters: --state merged, -d/--draft, -H/--head, -a/--assignee,
-S/--search and -w/--web, plus the gh shorthands -s, -A, -B, -l and
-m; --milestone takes a title or an ID, and @me works for --author and
--assignee. An empty list says so on stderr. draft, merged_at and
merged_by are exported in JSON, and reviewers, reviewer_teams and
merged_by, which Gitea's list leaves out, are read when --json names
them.

issue view and pr view render through terminal.View. Pull requests
show Draft and Merged badges, "alice merged into main from fix" with
the merge time, each reviewer's latest state ("bob (Approved), carol
(Requested)"), a checks summary pointing at tea pr checks, and why a
pull request cannot be merged. --comments includes reviews without a
body ("dave approved these changes") and comment IDs. Issues show
their due date and ref, and both kinds hint at --comments when there
are comments. pr view accepts #N, URLs and branch names, and its JSON
adds review_decision. Check links are absolute.

Signed-off-by: bircni <bircni@icloud.com>
This commit is contained in:
bircni committed 2026-10-11 23:54:47 +02:00
1 parent c5cf6b9ed9
commit 7930f80865
13 files changed
+817 -302

No files matched your search

+23 -3
View File
@@ -6,6 +6,7 @@ package services
import (
"context"
"errors"
"net/url"
"slices"
"sort"
"time"
@@ -51,13 +52,32 @@ func (s Pulls) checkHead(ctx context.Context, n int64) (string, error) {
return pull.Head.Sha, nil
}
func checkFrom(sha string, status *gitea.Status) Check {
func checkFrom(sha, instance string, status *gitea.Status) Check {
return Check{
SHA: sha, ID: status.ID, Name: status.Context, State: string(status.State), Description: status.Description,
URL: status.TargetURL, CreatedAt: timestamp(status.Created), UpdatedAt: timestamp(status.Updated),
URL: absoluteURL(instance, status.TargetURL), CreatedAt: timestamp(status.Created), UpdatedAt: timestamp(status.Updated),
}
}
// absoluteURL resolves a link that Gitea gives relative to its root, such as the job links of
// Actions statuses, against the instance URL.
func absoluteURL(instance, link string) string {
base, err := url.Parse(instance)
if err != nil || link == "" {
return link
}
ref, err := url.Parse(link)
if err != nil {
return link
}
return base.ResolveReference(ref).String()
}
// CommitChecks returns the latest status of each check context of a commit.
func (s Pulls) CommitChecks(ctx context.Context, sha string) ([]Check, error) {
return s.checksForCommit(ctx, sha)
}
func (s Pulls) checksForCommit(ctx context.Context, sha string) ([]Check, error) {
statuses, err := listAll(func(page int) ([]*gitea.Status, error) {
return repoCall(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, name string) ([]*gitea.Status, *gitea.Response, error) {
@@ -71,7 +91,7 @@ func (s Pulls) checksForCommit(ctx context.Context, sha string) ([]Check, error)
for _, status := range statuses {
current, exists := latest[status.Context]
if !exists || status.ID > current.ID {
latest[status.Context] = checkFrom(sha, status)
latest[status.Context] = checkFrom(sha, s.Client.BaseURL, status)
}
}
result := make([]Check, 0, len(latest))
+12 -1
View File
@@ -90,5 +90,16 @@ func TestCheckFromMapsCommitStatuses(t *testing.T) {
require.Equal(t, Check{
SHA: "abc", ID: 3, Name: "ci/build", State: "failure", Description: "Broken", URL: "https://ci.test/3",
CreatedAt: "2026-10-01T12:00:00Z", UpdatedAt: "2026-10-01T12:05:00Z",
}, checkFrom("abc", status))
}, checkFrom("abc", "http://instance.test", status))
}
func TestCheckLinksAreAbsolute(t *testing.T) {
for _, tc := range []struct{ instance, link, want string }{
{"http://instance.test", "/alice/x/actions/runs/18/jobs/18", "http://instance.test/alice/x/actions/runs/18/jobs/18"},
{"https://instance.test/sub", "/sub/alice/x/actions/runs/1", "https://instance.test/sub/alice/x/actions/runs/1"},
{"http://instance.test", "https://ci.test/3", "https://ci.test/3"},
{"http://instance.test", "", ""},
} {
require.Equal(t, tc.want, checkFrom("abc", tc.instance, &gitea.Status{TargetURL: tc.link}).URL, tc.link)
}
}
+95 -32
View File
@@ -11,6 +11,7 @@ import (
"io"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"time"
@@ -21,33 +22,40 @@ import (
// Pull is the stable command representation of a pull request.
type Pull struct {
Author string `json:"author"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Assignees []string `json:"assignees"`
Milestone *IssueMilestone `json:"milestone"`
Labels []Label `json:"labels"`
Deadline *string `json:"due_date"`
ID int64 `json:"id"`
Number int64 `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
URL string `json:"url"`
State string `json:"state"`
Merged bool `json:"merged"`
Mergeable bool `json:"mergeable"`
Draft bool `json:"-"`
Base string `json:"base"`
Head string `json:"head"`
HeadSHA string `json:"head_sha"`
HeadRepo string `json:"head_repo,omitempty"`
HeadRemoteDeleted bool `json:"head_remote_deleted"`
HeadCanPush bool `json:"-"`
HeadCloneURL string `json:"-"`
HeadSSHURL string `json:"-"`
Reviewers []string `json:"reviewers"`
ReviewerTeams []string `json:"reviewer_teams"`
Comments int64 `json:"comments"`
Author string `json:"author"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Assignees []string `json:"assignees"`
Milestone *IssueMilestone `json:"milestone"`
Labels []Label `json:"labels"`
Deadline *string `json:"due_date"`
ID int64 `json:"id"`
Number int64 `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
URL string `json:"url"`
State string `json:"state"`
Merged bool `json:"merged"`
MergedAt *string `json:"merged_at"`
// MergedBy, Reviewers and ReviewerTeams are only in responses for one pull request; lists
// leave them out.
MergedBy string `json:"merged_by"`
Mergeable bool `json:"mergeable"`
Draft bool `json:"draft"`
// ReviewDecision summarizes the reviews like gh: approved, changes_requested, review_required
// or "". Only commands that read the reviews fill it.
ReviewDecision string `json:"review_decision"`
Base string `json:"base"`
Head string `json:"head"`
HeadSHA string `json:"head_sha"`
HeadRepo string `json:"head_repo,omitempty"`
HeadRemoteDeleted bool `json:"head_remote_deleted"`
HeadCanPush bool `json:"-"`
HeadCloneURL string `json:"-"`
HeadSSHURL string `json:"-"`
Reviewers []string `json:"reviewers"`
ReviewerTeams []string `json:"reviewer_teams"`
Comments int64 `json:"comments"`
}
func pullHeadBranch(number int64, ref, label string) (branch string, deleted bool) {
@@ -74,7 +82,8 @@ func pullFrom(pull *gitea.PullRequest) Pull {
Author: login(pull.Poster), CreatedAt: timestamp(deref(pull.Created)), UpdatedAt: timestamp(deref(pull.Updated)),
Assignees: convertAll(pull.Assignees, login), Milestone: issueMilestoneFrom(pull.Milestone), Labels: convertAll(pull.Labels, labelFrom),
Deadline: optionalTimestamp(pull.Deadline), ID: pull.ID, Number: pull.Index, Title: pull.Title, Body: pull.Body,
URL: pull.HTMLURL, State: string(pull.State), Merged: pull.HasMerged, Mergeable: pull.Mergeable, Draft: pull.Draft,
URL: pull.HTMLURL, State: string(pull.State), Merged: pull.HasMerged, MergedAt: optionalTimestamp(pull.Merged), MergedBy: login(pull.MergedBy),
Mergeable: pull.Mergeable, Draft: pull.Draft,
Base: base.Ref, Head: headBranch, HeadSHA: head.Sha, HeadRemoteDeleted: remoteDeleted,
Reviewers: convertAll(pull.RequestedReviewers, login), Comments: int64(pull.Comments),
ReviewerTeams: convertAll(pull.RequestedReviewersTeams, func(team *gitea.Team) string { return team.Name }),
@@ -127,17 +136,71 @@ type Pulls struct {
Repository string
}
// PullListOptions supplies server-supported pull request filters.
// PullListOptions filters pull requests. State is open, closed, merged or all.
type PullListOptions struct {
State, Sort, Author, Base string
Limit, Page int
Milestone int64
Labels []int64
// Draft, Head (BRANCH or OWNER:BRANCH), Assignee, Search (text in the title or body) and the
// merged state have no server filter; List applies them to every pull request it reads.
Draft bool
Head, Assignee, Search string
}
// filtered reports whether a filter needs every pull request read.
func (o PullListOptions) filtered() bool {
return o.State == "merged" || o.Draft || o.Head != "" || o.Assignee != "" || o.Search != ""
}
// matches applies the filters without a server equivalent to item.
func (o PullListOptions) matches(item Pull) bool {
owner, branch, qualified := strings.Cut(o.Head, ":")
if !qualified {
owner, branch = "", o.Head
}
headOwner, _, _ := strings.Cut(item.HeadRepo, "/")
search := strings.ToLower(o.Search)
return (o.State != "merged" || item.Merged) && (!o.Draft || item.Draft) &&
(branch == "" || (item.Head == branch && (owner == "" || strings.EqualFold(owner, headOwner)))) &&
(o.Assignee == "" || slices.ContainsFunc(item.Assignees, func(name string) bool { return strings.EqualFold(name, o.Assignee) })) &&
(search == "" || strings.Contains(strings.ToLower(item.Title), search) || strings.Contains(strings.ToLower(item.Body), search))
}
// List returns a page of pull requests, even when the server caps its page size below the
// limit, and reports whether more pull requests follow.
func (s Pulls) List(ctx context.Context, options PullListOptions) ([]Pull, bool, error) {
page, err := s.ListPage(ctx, options)
return page.Items, page.More, err
}
// ListPage is List that also reports how many pull requests match, when the server counts them
// or every pull request was read for a filter without a server equivalent.
func (s Pulls) ListPage(ctx context.Context, options PullListOptions) (Page[Pull], error) {
if !options.filtered() {
return s.listPage(ctx, options)
}
query := options
if query.State == "merged" {
query.State = "closed"
}
all, err := listAll(func(page int) ([]Pull, error) {
query.Limit, query.Page = 50, page
window, err := s.listPage(ctx, query)
return window.Items, err
})
if err != nil {
return Page[Pull]{}, err
}
matching := slices.DeleteFunc(all, func(item Pull) bool { return !options.matches(item) })
items, err := pageOf(matching, options.Limit, options.Page)
if err != nil {
return Page[Pull]{}, err
}
return Page[Pull]{Items: items, More: options.Page*options.Limit < len(matching), Total: len(matching), Counted: true}, nil
}
func (s Pulls) listPage(ctx context.Context, options PullListOptions) (Page[Pull], error) {
query := url.Values{"state": {options.State}}
if options.Sort != "" {
query.Set("sort", options.Sort)
@@ -156,11 +219,11 @@ func (s Pulls) List(ctx context.Context, options PullListOptions) ([]Pull, bool,
}
// TODO(sdk): ListPullRequestsOptions lacks the poster, base_branch, and labels filters.
pulls, more, err := rawWindow[*gitea.PullRequest](ctx, s.Client, "repos/"+s.Repository+"/pulls", query, options.Limit, options.Page)
page, err := rawPage[*gitea.PullRequest](ctx, s.Client, "repos/"+s.Repository+"/pulls", query, options.Limit, options.Page)
if err != nil {
return nil, false, err
return Page[Pull]{}, err
}
return convertAll(pulls, pullFrom), more, nil
return Page[Pull]{Items: convertAll(page.Items, pullFrom), More: page.More, Total: page.Total, Counted: page.Counted}, nil
}
// View retrieves one pull request.
+53 -8
View File
@@ -4,10 +4,12 @@
package services
import (
"cmp"
"context"
"errors"
"fmt"
"net/http"
"slices"
"sort"
"strings"
@@ -105,7 +107,7 @@ func (s Reviews) List(ctx context.Context, n int64, limit, page int) ([]Review,
// Pending returns the reviews that login started on pull request n and has not submitted yet.
func (s Reviews) Pending(ctx context.Context, n int64, login string) ([]Review, error) {
reviews, err := listAll(func(page int) ([]Review, error) { return s.List(ctx, n, 100, page) })
reviews, err := s.All(ctx, n)
if err != nil {
return nil, err
}
@@ -208,14 +210,57 @@ func (s Reviews) Comments(ctx context.Context, n, reviewID int64, limit, page in
return pageOf(results, limit, page)
}
// Thread returns every review and every inline review comment of a pull request.
func (s Reviews) Thread(ctx context.Context, n int64) ([]Review, []ReviewComment, error) {
reviews, err := listAll(func(page int) ([]Review, error) { return s.List(ctx, n, 100, page) })
if err != nil {
return nil, nil, err
// All returns every review of a pull request, including requests for a review.
func (s Reviews) All(ctx context.Context, n int64) ([]Review, error) {
return listAll(func(page int) ([]Review, error) { return s.List(ctx, n, 100, page) })
}
// Inline returns the inline comments of the given reviews of pull request n.
func (s Reviews) Inline(ctx context.Context, n int64, reviews []Review) ([]ReviewComment, error) {
return s.reviewComments(ctx, n, reviews, true)
}
// LatestReviews returns each reviewer's latest review, in the order of their first review. Pending
// reviews, which only their author sees, are left out; a later request for a review replaces a review.
func LatestReviews(reviews []Review) []Review {
reviews = slices.Clone(reviews)
slices.SortStableFunc(reviews, func(x, y Review) int { return cmp.Compare(x.ID, y.ID) })
at := map[string]int{}
var latest []Review
for _, review := range reviews {
if review.Author == "" || review.State == string(gitea.ReviewStatePending) {
continue
}
if i, ok := at[review.Author]; ok {
latest[i] = review
continue
}
at[review.Author] = len(latest)
latest = append(latest, review)
}
comments, err := s.reviewComments(ctx, n, reviews, true)
return reviews, comments, err
return latest
}
// ReviewDecision summarizes the latest reviews like gh: changes_requested when a reviewer's latest
// review requests changes, else approved when one approves, else review_required while reviews
// are requested, else "". Dismissed reviews do not count.
func ReviewDecision(latest []Review, requested bool) string {
decision := ""
for _, review := range latest {
switch {
case review.Dismissed:
case review.State == string(gitea.ReviewStateRequestChanges):
return "changes_requested"
case review.State == string(gitea.ReviewStateApproved):
decision = "approved"
case review.State == string(gitea.ReviewStateRequestReview):
requested = true
}
}
if decision == "" && requested {
return "review_required"
}
return decision
}
func (s Reviews) reviewComments(ctx context.Context, n int64, reviews []Review, skipEmpty bool) ([]ReviewComment, error) {