From 1a244e17bbd75640b75470ad0a2243057e2d65b1 Mon Sep 17 00:00:00 2001 From: Julian Blacher Date: Sun, 8 Nov 2026 13:18:39 -0300 Subject: [PATCH] fix: address review findings on Bitbucket, the dashboard and auto-watch - Bitbucket: give each build-status key its own App.ID, so two statuses with the same display name aren't de-duplicated as reruns of one check. - dashboard: advance the --merged cutoff on every live refresh; filter GitHub PRs by merged_at rather than updated_at; keep reading CI while checks are still running next to a failed one. - Bitbucket auto-watch: between review scans Find reports nothing to apply instead of replaying the last result, which re-added PRs that had closed and notified about them again. - Pipelines logs: look up the pipeline's UUID when the steps response doesn't include it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++++++ cmd/prw/dashboard.go | 11 ++++++++++ cmd/prw/dashboard_test.go | 11 ++++++++++ internal/bitbucket/client.go | 8 ++++++- internal/bitbucket/client_test.go | 8 +++++++ internal/bitbucket/pipelines.go | 12 ++++++++++- internal/bitbucket/pipelines_test.go | 26 +++++++++++++++++++++++ internal/dashboard/collect.go | 2 +- internal/dashboard/collect_test.go | 15 +++++++++++++ internal/dashboard/model.go | 4 +++- internal/dashboard/sources.go | 13 +++++++++--- internal/dashboard/sources_test.go | 20 +++++++++++++++++ internal/github/client.go | 4 +++- internal/watcher/autowatch.go | 5 +++++ internal/watcher/bitbucket_finder.go | 18 +++++++++------- internal/watcher/bitbucket_finder_test.go | 26 ++++++++++++++++++++++- 16 files changed, 173 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df57ec3..32428a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,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. diff --git a/cmd/prw/dashboard.go b/cmd/prw/dashboard.go index 3126fa6..6b625a3 100644 --- a/cmd/prw/dashboard.go +++ b/cmd/prw/dashboard.go @@ -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 @@ -184,6 +186,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 diff --git a/cmd/prw/dashboard_test.go b/cmd/prw/dashboard_test.go index 7bfa474..a0f553b 100644 --- a/cmd/prw/dashboard_test.go +++ b/cmd/prw/dashboard_test.go @@ -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) diff --git a/internal/bitbucket/client.go b/internal/bitbucket/client.go index c502e51..4c38bf7 100644 --- a/internal/bitbucket/client.go +++ b/internal/bitbucket/client.go @@ -15,6 +15,7 @@ import ( "encoding/base64" "errors" "fmt" + "hash/fnv" "net/url" "strings" "sync" @@ -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) @@ -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" diff --git a/internal/bitbucket/client_test.go b/internal/bitbucket/client_test.go index 9422732..1237ec6 100644 --- a/internal/bitbucket/client_test.go +++ b/internal/bitbucket/client_test.go @@ -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) + } +} diff --git a/internal/bitbucket/pipelines.go b/internal/bitbucket/pipelines.go index e0881c4..4f109bc 100644 --- a/internal/bitbucket/pipelines.go +++ b/internal/bitbucket/pipelines.go @@ -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 diff --git a/internal/bitbucket/pipelines_test.go b/internal/bitbucket/pipelines_test.go index 207a43c..1f5814e 100644 --- a/internal/bitbucket/pipelines_test.go +++ b/internal/bitbucket/pipelines_test.go @@ -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) + } +} diff --git a/internal/dashboard/collect.go b/internal/dashboard/collect.go index 36c80da..77b6bda 100644 --- a/internal/dashboard/collect.go +++ b/internal/dashboard/collect.go @@ -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". diff --git a/internal/dashboard/collect_test.go b/internal/dashboard/collect_test.go index 1d8728a..70eb9fd 100644 --- a/internal/dashboard/collect_test.go +++ b/internal/dashboard/collect_test.go @@ -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") + } +} diff --git a/internal/dashboard/model.go b/internal/dashboard/model.go index b9946e8..92530fd 100644 --- a/internal/dashboard/model.go +++ b/internal/dashboard/model.go @@ -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. diff --git a/internal/dashboard/sources.go b/internal/dashboard/sources.go index 7a15887..1b5a202 100644 --- a/internal/dashboard/sources.go +++ b/internal/dashboard/sources.go @@ -93,7 +93,7 @@ func (s *GitHubSource) Discover(ctx context.Context, f Filter) ([]Item, []string found[i] = Item{ Ref: ref, URL: ref.URL(), Host: forge.GitHub, 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) } @@ -103,8 +103,8 @@ 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) } @@ -112,6 +112,13 @@ func (s *GitHubSource) Discover(ctx context.Context, f Filter) ([]Item, []string 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 { diff --git a/internal/dashboard/sources_test.go b/internal/dashboard/sources_test.go index b2ed5c6..080ae2e 100644 --- a/internal/dashboard/sources_test.go +++ b/internal/dashboard/sources_test.go @@ -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) + } +} diff --git a/internal/github/client.go b/internal/github/client.go index d2248fe..4b7189a 100644 --- a/internal/github/client.go +++ b/internal/github/client.go @@ -149,7 +149,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"` diff --git a/internal/watcher/autowatch.go b/internal/watcher/autowatch.go index e87b54a..1da1be6 100644 --- a/internal/watcher/autowatch.go +++ b/internal/watcher/autowatch.go @@ -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 + // 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) } @@ -121,6 +123,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)) diff --git a/internal/watcher/bitbucket_finder.go b/internal/watcher/bitbucket_finder.go index 536f296..97937cc 100644 --- a/internal/watcher/bitbucket_finder.go +++ b/internal/watcher/bitbucket_finder.go @@ -43,7 +43,6 @@ type BitbucketFinder struct { Now func() time.Time lastReviewScan time.Time - reviewFound *Found } func (f *BitbucketFinder) Host() string { return forge.Bitbucket } @@ -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) } diff --git a/internal/watcher/bitbucket_finder_test.go b/internal/watcher/bitbucket_finder_test.go index e587263..c90c00c 100644 --- a/internal/watcher/bitbucket_finder_test.go +++ b/internal/watcher/bitbucket_finder_test.go @@ -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) } @@ -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 {