diff --git a/bitbucket/commit_statuses.go b/bitbucket/commit_statuses.go index 8c038d7..d3aabbc 100644 --- a/bitbucket/commit_statuses.go +++ b/bitbucket/commit_statuses.go @@ -2,20 +2,119 @@ package bitbucket import ( "context" + "fmt" + "net/http" + "net/url" + "strings" + "time" forge "github.com/git-pkgs/forge" ) -type bitbucketCommitStatusService struct{} +type bitbucketCommitStatusService struct { + token string + httpClient *http.Client +} func (f *bitbucketForge) CommitStatuses() forge.CommitStatusService { - return &bitbucketCommitStatusService{} + return &bitbucketCommitStatusService{token: f.token, httpClient: f.httpClient} +} + +// bbCommitStatus is a Bitbucket build status. Key identifies the status on +// its commit, and setting a status with an existing key replaces it, so it +// plays the part of the context on other forges. +type bbCommitStatus struct { + Key string `json:"key"` + Name string `json:"name"` + State string `json:"state"` // SUCCESSFUL, FAILED, INPROGRESS, STOPPED + Description string `json:"description"` + URL string `json:"url"` + CreatedOn string `json:"created_on"` +} + +type bbCommitStatusesResponse struct { + Values []bbCommitStatus `json:"values"` + Next string `json:"next"` +} + +func convertBitbucketCommitStatus(bb bbCommitStatus) forge.CommitStatus { + result := forge.CommitStatus{ + State: forge.NormalizeCommitStatusState(bb.State), + Context: bb.Key, + Description: bb.Description, + TargetURL: bb.URL, + } + if t, err := time.Parse(time.RFC3339, bb.CreatedOn); err == nil { + result.CreatedAt = t + } + return result } -func (s *bitbucketCommitStatusService) List(_ context.Context, _, _, _ string) ([]forge.CommitStatus, error) { - return nil, forge.ErrNotSupported +// bitbucketCommitStatusState maps a commit status state, normalized or +// Bitbucket's own, to the one Bitbucket takes. Bitbucket has no separate +// error state, so errors are reported as FAILED. A state with no Bitbucket +// equivalent, such as skipped, is sent upper-cased for Bitbucket to reject +// with its own validation error. +func bitbucketCommitStatusState(state string) string { + switch forge.NormalizeCommitStatusState(state) { + case forge.CommitStatusSuccess: + return "SUCCESSFUL" + case forge.CommitStatusFailure, forge.CommitStatusError: + return "FAILED" + case forge.CommitStatusPending: + return "INPROGRESS" + case forge.CommitStatusCancelled: + return "STOPPED" + default: + return strings.ToUpper(state) + } } -func (s *bitbucketCommitStatusService) Set(_ context.Context, _, _, _ string, _ forge.SetCommitStatusOpts) (*forge.CommitStatus, error) { - return nil, forge.ErrNotSupported +func (s *bitbucketCommitStatusService) doJSON(ctx context.Context, method, url string, body any, v any) error { + rs := &bitbucketRepoService{token: s.token, httpClient: s.httpClient} + return rs.doJSON(ctx, method, url, body, v) +} + +func commitStatusesURL(owner, repo, sha string) string { + return fmt.Sprintf("%s/repositories/%s/%s/commit/%s/statuses", bitbucketAPI, owner, repo, url.PathEscape(sha)) +} + +func (s *bitbucketCommitStatusService) List(ctx context.Context, owner, repo, sha string) ([]forge.CommitStatus, error) { + u := commitStatusesURL(owner, repo, sha) + "?pagelen=100" + var all []forge.CommitStatus + for u != "" { + var page bbCommitStatusesResponse + if err := s.doJSON(ctx, http.MethodGet, u, nil, &page); err != nil { + return nil, err + } + for _, bb := range page.Values { + all = append(all, convertBitbucketCommitStatus(bb)) + } + u = page.Next + } + return all, nil +} + +// Set creates a build status on the commit, or replaces the one with the +// same context. The context is used as both the key and the name Bitbucket +// shows for the status. +func (s *bitbucketCommitStatusService) Set(ctx context.Context, owner, repo, sha string, opts forge.SetCommitStatusOpts) (*forge.CommitStatus, error) { + body := map[string]any{ + "key": opts.Context, + "name": opts.Context, + "state": bitbucketCommitStatusState(opts.State), + } + if opts.Description != "" { + body["description"] = opts.Description + } + if opts.TargetURL != "" { + body["url"] = opts.TargetURL + } + + var bb bbCommitStatus + if err := s.doJSON(ctx, http.MethodPost, commitStatusesURL(owner, repo, sha)+"/build", body, &bb); err != nil { + return nil, err + } + result := convertBitbucketCommitStatus(bb) + return &result, nil } diff --git a/bitbucket/commit_statuses_test.go b/bitbucket/commit_statuses_test.go index 511c662..b67ee42 100644 --- a/bitbucket/commit_statuses_test.go +++ b/bitbucket/commit_statuses_test.go @@ -2,22 +2,234 @@ package bitbucket import ( "context" - forge "github.com/git-pkgs/forge" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" "testing" + "time" + + forge "github.com/git-pkgs/forge" ) -func TestBitbucketListCommitStatusesNotSupported(t *testing.T) { - s := New("", nil).CommitStatuses() - _, err := s.List(context.Background(), "owner", "repo", "abc123") - if err != forge.ErrNotSupported { - t.Errorf("List: expected forge.ErrNotSupported, got %v", err) +const statusTestSHA = "fd61ca641c0db3ab42ad10bc1b2b7190033aee77" + +// newStatusTestForge points the Bitbucket API at a test server running h. +func newStatusTestForge(t *testing.T, h http.Handler) (forge.Forge, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + origAPI := bitbucketAPI + setBitbucketAPI(srv.URL + "/2.0") + t.Cleanup(func() { setBitbucketAPI(origAPI) }) + return New("test-token", srv.Client()), srv +} + +func TestBitbucketListCommitStatuses(t *testing.T) { + var srvURL string + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/commit/"+statusTestSHA+"/statuses", func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer test-token" { + t.Errorf("Authorization = %q, want bearer token", got) + } + if r.URL.Query().Get("page") == "" { + if got := r.URL.Query().Get("pagelen"); got != "100" { + t.Errorf("pagelen = %q, want 100", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []map[string]any{{ + "key": "default", + "name": "Pipeline - default", + "state": "FAILED", + "description": "2 tests failed", + "url": "https://bitbucket.org/atlassian/stash/pipelines/results/2865", + "created_on": "2026-04-30T04:38:20.636159+00:00", + }}, + "next": srvURL + "/2.0/repositories/atlassian/stash/commit/" + statusTestSHA + "/statuses?pagelen=100&page=2", + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []map[string]any{ + {"key": "lint", "state": "SUCCESSFUL"}, + {"key": "deploy", "state": "INPROGRESS"}, + {"key": "e2e", "state": "STOPPED"}, + }, + }) + }) + f, srv := newStatusTestForge(t, mux) + srvURL = srv.URL + + statuses, err := f.CommitStatuses().List(context.Background(), "atlassian", "stash", statusTestSHA) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + want := []forge.CommitStatus{ + { + State: forge.CommitStatusFailure, + Context: "default", + Description: "2 tests failed", + TargetURL: "https://bitbucket.org/atlassian/stash/pipelines/results/2865", + CreatedAt: time.Date(2026, 4, 30, 4, 38, 20, 636159000, time.UTC), + }, + {State: forge.CommitStatusSuccess, Context: "lint"}, + {State: forge.CommitStatusPending, Context: "deploy"}, + {State: forge.CommitStatusCancelled, Context: "e2e"}, + } + if len(statuses) != len(want) { + t.Fatalf("got %d statuses, want %d: %+v", len(statuses), len(want), statuses) + } + for i := range want { + got := statuses[i] + if got.State != want[i].State || got.Context != want[i].Context || + got.Description != want[i].Description || got.TargetURL != want[i].TargetURL || + !got.CreatedAt.Equal(want[i].CreatedAt) { + t.Errorf("status %d = %+v, want %+v", i, got, want[i]) + } + } +} + +func TestBitbucketListCommitStatusesNotFound(t *testing.T) { + f, _ := newStatusTestForge(t, http.NotFoundHandler()) + _, err := f.CommitStatuses().List(context.Background(), "atlassian", "stash", "missing") + if !errors.Is(err, forge.ErrNotFound) { + t.Errorf("error = %v, want ErrNotFound", err) + } +} + +func TestBitbucketSetCommitStatus(t *testing.T) { + var body map[string]any + mux := http.NewServeMux() + mux.HandleFunc("POST /2.0/repositories/atlassian/stash/commit/"+statusTestSHA+"/statuses/build", func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Content-Type"); got != "application/json" { + t.Errorf("Content-Type = %q, want application/json", got) + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decoding body: %v", err) + } + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{ + "key": "ci/test", + "name": "ci/test", + "state": "SUCCESSFUL", + "description": "42 tests passed", + "url": "https://ci.example.com/build/1", + "created_on": "2026-11-19T10:00:00+00:00", + }) + }) + f, _ := newStatusTestForge(t, mux) + + status, err := f.CommitStatuses().Set(context.Background(), "atlassian", "stash", statusTestSHA, forge.SetCommitStatusOpts{ + State: "success", + Context: "ci/test", + Description: "42 tests passed", + TargetURL: "https://ci.example.com/build/1", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + wantBody := map[string]any{ + "key": "ci/test", + "name": "ci/test", + "state": "SUCCESSFUL", + "description": "42 tests passed", + "url": "https://ci.example.com/build/1", + } + if len(body) != len(wantBody) { + t.Errorf("body = %v, want %v", body, wantBody) + } + for k, v := range wantBody { + if body[k] != v { + t.Errorf("body[%q] = %v, want %v", k, body[k], v) + } + } + + assertEqual(t, "State", "success", status.State) + assertEqual(t, "Context", "ci/test", status.Context) + assertEqual(t, "Description", "42 tests passed", status.Description) + assertEqual(t, "TargetURL", "https://ci.example.com/build/1", status.TargetURL) + if !status.CreatedAt.Equal(time.Date(2026, 11, 19, 10, 0, 0, 0, time.UTC)) { + t.Errorf("CreatedAt = %v", status.CreatedAt) + } +} + +func TestBitbucketSetCommitStatusOmitsEmptyFields(t *testing.T) { + var keys []string + mux := http.NewServeMux() + mux.HandleFunc("POST /2.0/repositories/atlassian/stash/commit/"+statusTestSHA+"/statuses/build", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + for k := range body { + keys = append(keys, k) + } + _ = json.NewEncoder(w).Encode(map[string]any{"key": "lint", "state": "INPROGRESS"}) + }) + f, _ := newStatusTestForge(t, mux) + + if _, err := f.CommitStatuses().Set(context.Background(), "atlassian", "stash", statusTestSHA, forge.SetCommitStatusOpts{ + State: "pending", + Context: "lint", + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + slices.Sort(keys) + if want := []string{"key", "name", "state"}; !slices.Equal(keys, want) { + t.Errorf("body keys = %v, want %v", keys, want) + } +} + +func TestBitbucketCommitStatusState(t *testing.T) { + tests := []struct { + in string + want string + }{ + {"success", "SUCCESSFUL"}, + {"SUCCESSFUL", "SUCCESSFUL"}, + {"failure", "FAILED"}, + {"error", "FAILED"}, + {"FAILED", "FAILED"}, + {"pending", "INPROGRESS"}, + {"INPROGRESS", "INPROGRESS"}, + {"cancelled", "STOPPED"}, + {"stopped", "STOPPED"}, + {"skipped", "SKIPPED"}, + {"bogus", "BOGUS"}, + } + for _, tt := range tests { + if got := bitbucketCommitStatusState(tt.in); got != tt.want { + t.Errorf("bitbucketCommitStatusState(%q) = %q, want %q", tt.in, got, tt.want) + } + } +} + +func TestBitbucketSetCommitStatusRejected(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("POST /2.0/repositories/atlassian/stash/commit/"+statusTestSHA+"/statuses/build", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"type": "error", "error": {"message": "state: Value must be one of FAILED, INPROGRESS, STOPPED, SUCCESSFUL"}}`)) + }) + f, _ := newStatusTestForge(t, mux) + + _, err := f.CommitStatuses().Set(context.Background(), "atlassian", "stash", statusTestSHA, forge.SetCommitStatusOpts{ + State: "skipped", + Context: "lint", + }) + var httpErr *forge.HTTPError + if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusBadRequest { + t.Errorf("error = %v, want HTTP 400", err) } } -func TestBitbucketSetCommitStatusNotSupported(t *testing.T) { - s := New("", nil).CommitStatuses() - _, err := s.Set(context.Background(), "owner", "repo", "abc123", forge.SetCommitStatusOpts{}) - if err != forge.ErrNotSupported { - t.Errorf("Set: expected forge.ErrNotSupported, got %v", err) +func TestBitbucketSetCommitStatusReadOnly(t *testing.T) { + f := New("test-token", forge.ReadOnlyHTTPClient(nil)) + _, err := f.CommitStatuses().Set(context.Background(), "atlassian", "stash", statusTestSHA, forge.SetCommitStatusOpts{ + State: "success", + Context: "lint", + }) + if !errors.Is(err, forge.ErrReadOnly) { + t.Errorf("error = %v, want ErrReadOnly", err) } } diff --git a/bitbucket/replay_test.go b/bitbucket/replay_test.go index c9edbd1..e7d44df 100644 --- a/bitbucket/replay_test.go +++ b/bitbucket/replay_test.go @@ -12,6 +12,24 @@ import ( // These tests replay responses recorded from api.bitbucket.org. Re-record // them with FORGE_RECORD=1 go test ./bitbucket -run TestReplay. +func TestReplayListCommitStatuses(t *testing.T) { + f := New("", httpreplay.Client(t)) + statuses, err := f.CommitStatuses().List(context.Background(), "atlassian", "atlassian-connect-express", "fd61ca641c0db3ab42ad10bc1b2b7190033aee77") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if len(statuses) != 1 { + t.Fatalf("got %d statuses, want 1", len(statuses)) + } + assertEqual(t, "State", "failure", statuses[0].State) + assertEqual(t, "Context", "default", statuses[0].Context) + assertEqual(t, "TargetURL", "https://bitbucket.org/atlassian/atlassian-connect-express/pipelines/results/2865", statuses[0].TargetURL) + if statuses[0].CreatedAt.IsZero() { + t.Error("CreatedAt is zero") + } +} + func TestReplayGetRepo(t *testing.T) { f := New("", httpreplay.Client(t)) repo, err := f.Repos().Get(context.Background(), "tutorials", "markdowndemo") diff --git a/bitbucket/testdata/replay/TestReplayListCommitStatuses.json b/bitbucket/testdata/replay/TestReplayListCommitStatuses.json new file mode 100644 index 0000000..c2990d6 --- /dev/null +++ b/bitbucket/testdata/replay/TestReplayListCommitStatuses.json @@ -0,0 +1,17 @@ +[ + { + "request": { + "method": "GET", + "url": "https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/statuses?pagelen=100" + }, + "response": { + "status_code": 200, + "header": { + "Content-Type": [ + "application/json; charset=utf-8" + ] + }, + "body": "{\"values\": [{\"key\": \"default\", \"type\": \"build\", \"state\": \"FAILED\", \"name\": \"Pipeline - default\", \"refname\": \"release/12.2.3\", \"commit\": {\"hash\": \"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}}, \"type\": \"commit\"}, \"url\": \"https://bitbucket.org/atlassian/atlassian-connect-express/pipelines/results/2865\", \"repository\": {\"type\": \"repository\", \"full_name\": \"atlassian/atlassian-connect-express\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express\"}, \"avatar\": {\"href\": \"https://bytebucket.org/ravatar/%7B47b154f6-a82d-4e03-99ce-44fb75b4827c%7D?ts=138914\"}}, \"name\": \"atlassian-connect-express\", \"uuid\": \"{47b154f6-a82d-4e03-99ce-44fb75b4827c}\"}, \"description\": \"\", \"created_on\": \"2026-04-30T04:38:20.636159+00:00\", \"updated_on\": \"2026-04-30T06:38:22.087954+00:00\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/statuses/build/default\"}, \"commit\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}}}], \"pagelen\": 100, \"size\": 1, \"page\": 1}" + } + } +] diff --git a/statuses.go b/statuses.go index d3dda77..e794e8a 100644 --- a/statuses.go +++ b/statuses.go @@ -170,11 +170,11 @@ func NormalizeCommitStatusState(state string) CommitStatusState { return CommitStatusSuccess case "failure", "failed", "fail", "failing", "declined", "rejected": return CommitStatusFailure - case "pending", "queued", "running", "in_progress", "created", "waiting": + case "pending", "queued", "running", "in_progress", "inprogress", "created", "waiting": return CommitStatusPending case "error", "errored", "broken": return CommitStatusError - case "cancelled", "canceled": + case "cancelled", "canceled", "stopped": return CommitStatusCancelled case "skipped", "skip": return CommitStatusSkipped diff --git a/statuses_test.go b/statuses_test.go index 1e32d7f..0c246a6 100644 --- a/statuses_test.go +++ b/statuses_test.go @@ -53,8 +53,12 @@ func TestNormalizeCommitStatusState(t *testing.T) { {"approved", CommitStatusSuccess}, {"failed", CommitStatusFailure}, {"in_progress", CommitStatusPending}, + {"INPROGRESS", CommitStatusPending}, {"errored", CommitStatusError}, {"canceled", CommitStatusCancelled}, + {"STOPPED", CommitStatusCancelled}, + {"SUCCESSFUL", CommitStatusSuccess}, + {"FAILED", CommitStatusFailure}, {"unexpected", CommitStatusUnknown}, }