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
111 changes: 105 additions & 6 deletions bitbucket/commit_statuses.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
234 changes: 223 additions & 11 deletions bitbucket/commit_statuses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
18 changes: 18 additions & 0 deletions bitbucket/replay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading
Loading