Skip to content
Merged
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- `prw run` checks Bitbucket PRs less often as the watch list grows (every 18 seconds × the number of Bitbucket PRs, at least a minute), keeping checks around 600 of Bitbucket's 1,000 requests per hour.

### Fixed
- Bitbucket: two build statuses sharing a display name are no longer taken for reruns of one check; a newer success could hide a failed or running build.
- `prw dashboard --merged`: in live mode merged PRs now age out of the window, and on GitHub they are filtered by when they were merged rather than last updated.
- `prw dashboard`: CI keeps refreshing while checks are still running next to a failed one.
- Bitbucket auto-watch: a PR to review that closed between review scans is no longer added back and notified about again.
- Bitbucket Pipelines logs: no longer depend on the steps response naming its pipeline.

## [0.5.0] - 2026-10-31

prw now works with Bitbucket Cloud as well as GitHub, and `prw dashboard` shows all your PRs across repositories in one live table, grouped by task, with one column per target branch — handy when a change travels dev → rc → master as cherry-picks.
Expand Down
11 changes: 11 additions & 0 deletions cmd/prw/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ with 'prw config set branch_order dev,qa,main'.`,
}
view := dashboardView{grouper: grouper, order: cfg.BranchOrder, filter: filter, links: tty && !dashNoLinks}
for {
filter = advanceMergedCutoff(filter, mergedWindow, time.Now())
view.filter = filter
items, warnings := collector.Refresh(ctx, filter)
if ctx.Err() != nil {
return nil
Expand Down Expand Up @@ -191,6 +193,15 @@ func dashboardSources(cfg *config.Config) ([]dashboard.Source, error) {
return sources, nil
}

// advanceMergedCutoff moves the --merged cutoff to window before now, so that in live
// mode merged PRs age out of the window.
func advanceMergedCutoff(f dashboard.Filter, window time.Duration, now time.Time) dashboard.Filter {
if !f.MergedSince.IsZero() {
f.MergedSince = now.Add(-window)
}
return f
}

type dashboardView struct {
grouper *dashboard.Grouper
order []string
Expand Down
11 changes: 11 additions & 0 deletions cmd/prw/dashboard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@ func TestShortDuration(t *testing.T) {
}
}

func TestAdvanceMergedCutoff(t *testing.T) {
now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
f := advanceMergedCutoff(dashboard.Filter{MergedSince: now.Add(-72 * time.Hour)}, 24*time.Hour, now)
if !f.MergedSince.Equal(now.Add(-24 * time.Hour)) {
t.Errorf("cutoff = %s", f.MergedSince)
}
if f := advanceMergedCutoff(dashboard.Filter{}, 24*time.Hour, now); !f.MergedSince.IsZero() {
t.Errorf("without --merged the cutoff must stay unset: %s", f.MergedSince)
}
}

func TestSplitList(t *testing.T) {
if got := strings.Join(splitList(" dev, qa ,,main "), "|"); got != "dev|qa|main" {
t.Errorf("splitList = %s", got)
Expand Down
8 changes: 7 additions & 1 deletion internal/bitbucket/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"encoding/base64"
"errors"
"fmt"
"hash/fnv"
"net/url"
"strings"
"sync"
Expand Down Expand Up @@ -227,7 +228,7 @@ type buildStatus struct {

// GetCheckRuns returns the commit's build statuses (Bitbucket Pipelines, Jenkins, ...)
// as check runs. A status is updated in place when its build reruns, so each key
// appears once; IDs grow with the last update so the newest wins on duplicate names.
// appears once; each key gets its own App.ID so none is taken for a rerun of another.
func (c *Client) GetCheckRuns(ctx context.Context, workspace, repo, ref string) ([]github.CheckRun, error) {
var runs []github.CheckRun
path := fmt.Sprintf("%s/commit/%s/statuses?pagelen=%d", repoPath(workspace, repo), url.PathEscape(ref), statusesPageLen)
Expand All @@ -253,6 +254,11 @@ func toCheckRun(s buildStatus) github.CheckRun {
name = s.Key
}
run := github.CheckRun{ID: s.UpdatedOn.UnixNano(), Name: name, HTMLURL: s.URL, StartedAt: s.CreatedOn}
// A status is identified by its key: without this, two builds sharing a display name
// would look like reruns of one check and the newer would hide the other.
h := fnv.New64a()
h.Write([]byte(s.Key))
run.App.ID = int64(h.Sum64())
switch strings.ToUpper(s.State) {
case "INPROGRESS":
run.Status = "in_progress"
Expand Down
8 changes: 8 additions & 0 deletions internal/bitbucket/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,11 @@ func TestRelativeDoesNotFollowOtherHosts(t *testing.T) {
t.Errorf("relative = %q", got)
}
}

func TestGetCheckRuns_SameNameDifferentKeysStayApart(t *testing.T) {
failed := toCheckRun(buildStatus{Key: "lint", Name: "CI", State: "FAILED", UpdatedOn: time.Unix(100, 0)})
passed := toCheckRun(buildStatus{Key: "unit", Name: "CI", State: "SUCCESSFUL", UpdatedOn: time.Unix(200, 0)})
if got := github.LatestCheckRuns([]github.CheckRun{failed, passed}); len(got) != 2 {
t.Errorf("a newer status with another key must not hide the failed one: %+v", got)
}
}
12 changes: 11 additions & 1 deletion internal/bitbucket/pipelines.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,17 @@ func (c *Client) RunLog(ctx context.Context, workspace, repo string, run github.
}
reason := step.State.Result.Error.Message // e.g. "Exceeded build time limit of 120 minutes."

logPath := fmt.Sprintf("%s/pipelines/%s/steps/%s/log", repoPath(workspace, repo), url.PathEscape(step.Pipeline.UUID), url.PathEscape(step.UUID))
pipeline := step.Pipeline.UUID
if pipeline == "" { // Bitbucket sends it, but its API schema doesn't promise it
var p struct {
UUID string `json:"uuid"`
}
if err := c.http.GetJSON(ctx, fmt.Sprintf("%s/pipelines/%d?fields=uuid", repoPath(workspace, repo), number), &p); err != nil {
return github.LogExcerpt{}, fmt.Errorf("failed to read pipeline #%d: %w", number, err)
}
pipeline = p.UUID
}
logPath := fmt.Sprintf("%s/pipelines/%s/steps/%s/log", repoPath(workspace, repo), url.PathEscape(pipeline), url.PathEscape(step.UUID))
log, err := c.http.GetText(ctx, logPath, maxStepLogBytes)
if err != nil {
var apiErr *github.APIError
Expand Down
26 changes: 26 additions & 0 deletions internal/bitbucket/pipelines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,29 @@ func TestFailedJobLogs_UsesPipelinesLogs(t *testing.T) {
t.Errorf("Pipelines entry = %+v", logs[1])
}
}

func TestRunLog_StepsWithoutPipelineUUID(t *testing.T) {
var log string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.EscapedPath() {
case "/repositories/acme/api/pipelines/2435/steps/":
fmt.Fprint(w, `{"values": [{"uuid": "{s2}", "state": {"result": {"name": "FAILED"}}, "script_commands": [{"name": "npm test"}]}]}`)
case "/repositories/acme/api/pipelines/2435":
fmt.Fprint(w, `{"uuid": "{p1}"}`)
case "/repositories/acme/api/pipelines/%7Bp1%7D/steps/%7Bs2%7D/log":
log = r.URL.EscapedPath()
fmt.Fprint(w, stepLog)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
c := NewClient("me@example.com", "token")
c.SetBaseURL(srv.URL)

run := pipelineRun("p", "https://bitbucket.org/acme/api/addon/pipelines/home#!/results/2435")
got, err := c.RunLog(context.Background(), "acme", "api", run, 50)
if err != nil || got.Step != "npm test" || log == "" {
t.Errorf("got %+v, %v (log path %q)", got, err, log)
}
}
2 changes: 1 addition & 1 deletion internal/dashboard/collect.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func (c *Collector) applyCachedCI(it *Item) {
func (c *Collector) storeCI(it Item) {
c.mu.Lock()
defer c.mu.Unlock()
c.ci[it.Key()] = ciSnapshot{sha: it.HeadSHA, item: it, readAt: c.Now(), running: it.CI == "pending" || it.CI == ""}
c.ci[it.Key()] = ciSnapshot{sha: it.HeadSHA, item: it, readAt: c.Now(), running: it.CI == "pending" || it.CI == "" || it.CIDone < it.CITotal}
}

// Requests reports each source's requests in the last hour, e.g. "Bitbucket 312/h".
Expand Down
15 changes: 15 additions & 0 deletions internal/dashboard/collect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,18 @@ func TestCollector_Requests(t *testing.T) {
t.Errorf("Requests = %s", got)
}
}

func TestCollector_KeepsReadingCIWhileChecksRunNextToAFailure(t *testing.T) {
c := NewCollector(newFake())
it := pr(1, "a", StateOpen)
it.CI, it.CIDone, it.CITotal = "failure", 1, 3
c.storeCI(it)
if !c.needsCI(it) {
t.Error("a failed check with others still running must be read again")
}
it.CIDone = 3
c.storeCI(it)
if c.needsCI(it) {
t.Error("a finished failed suite must wait for the recheck interval")
}
}
4 changes: 3 additions & 1 deletion internal/dashboard/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ type Item struct {
State string `json:"state"` // open, merged, closed
Role string `json:"role"` // mine, review
UpdatedAt time.Time `json:"updated_at"`
HeadSHA string `json:"sha,omitempty"`
// MergedAt is when the PR was merged, where the host says so (GitHub).
MergedAt *time.Time `json:"merged_at,omitempty"`
HeadSHA string `json:"sha,omitempty"`

// CI is the aggregated state (success, failure, error, pending, no_ci), empty
// until known; CIDone/CITotal count finished checks.
Expand Down
13 changes: 10 additions & 3 deletions internal/dashboard/sources.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (s *GitHubSource) Discover(ctx context.Context, f Filter) ([]Item, []string
found[i] = Item{
Ref: ref, URL: ref.URL(), Host: host, Repo: r.Owner + "/" + r.Repo, Number: r.Number,
Title: pr.Title, Source: pr.Head.Ref, Target: pr.Base.Ref, State: q.state, Role: q.role,
UpdatedAt: pr.UpdatedAt, HeadSHA: pr.Head.SHA, Merge: github.MergeStatus(pr),
UpdatedAt: pr.UpdatedAt, MergedAt: pr.MergedAt, HeadSHA: pr.Head.SHA, Merge: github.MergeStatus(pr),
}
}(i, r)
}
Expand All @@ -106,15 +106,22 @@ func (s *GitHubSource) Discover(ctx context.Context, f Filter) ([]Item, []string
warnings = append(warnings, fmt.Sprintf("%s/%s#%d: %v", res.PRs[i].Owner, res.PRs[i].Repo, res.PRs[i].Number, errs[i]))
continue
}
if q.state == StateMerged && it.UpdatedAt.Before(f.MergedSince) {
continue
if q.state == StateMerged && mergedBefore(it, f.MergedSince) {
continue // the search only filters by day
}
items = append(items, it)
}
}
return items, warnings, nil
}

func mergedBefore(it Item, cutoff time.Time) bool {
if it.MergedAt != nil {
return it.MergedAt.Before(cutoff)
}
return it.UpdatedAt.Before(cutoff)
}

// Enrich reads CI (when needed) and reviews.
func (s *GitHubSource) Enrich(ctx context.Context, it *Item, needCI bool) error {
if needCI {
Expand Down
20 changes: 20 additions & 0 deletions internal/dashboard/sources_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,23 @@ func TestGitHubSource(t *testing.T) {
t.Errorf("enriched = %+v", it)
}
}

func TestGitHubSource_FiltersMergedByMergeTime(t *testing.T) {
cutoff := time.Date(2026, 10, 24, 12, 0, 0, 0, time.UTC)
before, after := cutoff.Add(-time.Hour), cutoff.Add(time.Hour)
oldMerge := ghPR(5, "old", "main", "closed", after) // commented on after the cutoff
oldMerge.MergedAt = &before
newMerge := ghPR(6, "new", "main", "closed", after)
newMerge.MergedAt = &after
api := &fakeGitHub{
results: map[string][]github.SearchResultPR{"author:@me merged:": {{Owner: "o", Repo: "r", Number: 5}, {Owner: "o", Repo: "r", Number: 6}}},
prs: map[int]*github.PullRequest{5: oldMerge, 6: newMerge},
}
items, _, err := (&GitHubSource{API: api}).Discover(context.Background(), Filter{MergedSince: cutoff})
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].Number != 6 {
t.Errorf("items = %+v, want only the PR merged after the cutoff", items)
}
}
4 changes: 3 additions & 1 deletion internal/github/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,9 @@ type PullRequest struct {
Title string `json:"title"`
State string `json:"state"` // open or closed
Merged bool `json:"merged"`
Head struct {
// MergedAt is when the PR was merged; nil if it wasn't.
MergedAt *time.Time `json:"merged_at"`
Head struct {
SHA string `json:"sha"`
Ref string `json:"ref"` // source branch
} `json:"head"`
Expand Down
5 changes: 5 additions & 0 deletions internal/watcher/autowatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ type Found struct {
// Finder finds the open PRs of an auto-watch source on one code host.
type Finder interface {
Host() string // forge.GitHub, forge.Bitbucket, or a GitHub Enterprise host
// Find returns nil, nil when the source isn't due for a new search, which leaves
// its PRs as they are.
Find(ctx context.Context, source string) (*Found, error)
GetPullRequest(ctx context.Context, owner, repo string, number int) (*github.PullRequest, error)
}
Expand Down Expand Up @@ -123,6 +125,9 @@ func Sync(ctx context.Context, finders []Finder, sources []string) (*SyncResult,
result.Warnings = append(result.Warnings, fmt.Sprintf("%s search for %s failed: %v", serviceName(f.Host()), AutoWatchDescription[source], err))
continue
}
if found == nil {
continue // not due: nothing new to add or remove
}
if found.Partial != "" {
result.Warnings = append(result.Warnings, fmt.Sprintf("%s search for %s %s; PRs that no longer match are kept",
serviceName(f.Host()), AutoWatchDescription[source], found.Partial))
Expand Down
18 changes: 10 additions & 8 deletions internal/watcher/bitbucket_finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ type BitbucketFinder struct {
Now func() time.Time

lastReviewScan time.Time
reviewFound *Found
}

func (f *BitbucketFinder) Host() string { return forge.Bitbucket }
Expand Down Expand Up @@ -88,14 +87,17 @@ func (f *BitbucketFinder) Find(ctx context.Context, source string) (*Found, erro
case config.AutoWatchMine:
return f.mine(ctx)
case config.AutoWatchReviewRequested:
if f.reviewFound == nil || f.now().Sub(f.lastReviewScan) >= BitbucketReviewScanEvery {
found, err := f.scanReviews(ctx)
if err != nil {
return nil, err
}
f.reviewFound, f.lastReviewScan = found, f.now()
// Between scans there is no result to replay: an old one would bring back PRs
// that closed since, and notify about them again.
if !f.lastReviewScan.IsZero() && f.now().Sub(f.lastReviewScan) < BitbucketReviewScanEvery {
return nil, nil
}
return f.reviewFound, nil
found, err := f.scanReviews(ctx)
if err != nil {
return nil, err
}
f.lastReviewScan = f.now()
return found, nil
}
return nil, fmt.Errorf("unknown auto-watch source %q", source)
}
Expand Down
26 changes: 25 additions & 1 deletion internal/watcher/bitbucket_finder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ func TestBitbucketFinder_ReviewsSkipReviewedAndRescanEvery15Minutes(t *testing.T
}

now = now.Add(BitbucketReviewScanEvery - time.Second)
f.Find(context.Background(), config.AutoWatchReviewRequested)
if got, err := f.Find(context.Background(), config.AutoWatchReviewRequested); got != nil || err != nil {
t.Errorf("between scans Find must report nothing to apply, got %+v, %v", got, err)
}
if api.scans != 1 {
t.Errorf("rescanned after %s: %d scans", BitbucketReviewScanEvery-time.Second, api.scans)
}
Expand Down Expand Up @@ -186,6 +188,28 @@ func TestSync_TwoHostsKeepTheirPRsApart(t *testing.T) {
}
}

func TestSync_ClosedReviewPRIsNotAddedBackBetweenScans(t *testing.T) {
useTempConfig(t)
saveConfig(t, &config.Config{AutoWatch: []string{config.AutoWatchReviewRequested}})
now := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
api := &fakeLister{
repos: map[string][]string{"acme": {"api"}},
reviews: map[string][]bitbucket.ListedPR{"acme/api": {listed("acme", "api", 1)}},
}
f := &BitbucketFinder{API: api, User: me, Workspaces: []string{"acme"}, Now: func() time.Time { return now }}
sources := []string{config.AutoWatchReviewRequested}
if res, err := Sync(context.Background(), []Finder{f}, sources); err != nil || len(res.Added) != 1 {
t.Fatalf("first sync: %+v, %v", res, err)
}

// prw run notified about the merge and dropped the PR.
config.Update(func(c *config.Config) error { c.WatchedPRs = nil; return nil })
now = now.Add(AutoWatchInterval)
if res, err := Sync(context.Background(), []Finder{f}, sources); err != nil || len(res.Added) != 0 {
t.Errorf("sync between scans must not add it back: %+v, %v", res, err)
}
}

func TestBitbucketInterval(t *testing.T) {
for n, want := range map[int]time.Duration{0: time.Minute, 3: time.Minute, 5: 90 * time.Second, 20: 6 * time.Minute, 30: 9 * time.Minute, 100: 30 * time.Minute} {
if got := BitbucketInterval(n); got != want {
Expand Down
Loading