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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ repo, err := client.FetchRepository(ctx, "https://github.com/octocat/hello-world

The `Forge` interface exposes services for repos, issues, pull requests, reviews, releases, CI, branches, labels, milestones, deploy keys, webhooks, secrets, notifications, files, collaborators, commit statuses, commits and artifact attestations. Each backend implements these using its native SDK.

On Bitbucket Cloud, secrets are the repository's Bitbucket Pipelines variables. Listing returns every variable, secured or not, and setting one stores a secured variable, updating and securing any existing variable with that name. Bitbucket deploy keys can only read, so creating one with `ReadOnly` unset (`forge deploy-key add --read-only=false`) returns `forges.ErrNotSupported`.

Under TinyGo, `gitlab.New` retains its signature and returns a backend whose API operations report `forges.ErrNotSupported`. GitLab URL parsing, web link builders and webhook parsing remain available. Native Go retains the full GitLab implementation.

```go
Expand Down
47 changes: 3 additions & 44 deletions bitbucket/branches.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ import (
forge "github.com/git-pkgs/forge"
)

// maxBranchPageLen is the largest page Bitbucket serves from the refs
// endpoints.
const maxBranchPageLen = 100

type bitbucketBranchService struct {
token string
httpClient *http.Client
Expand All @@ -29,11 +25,6 @@ type bbBranch struct {
} `json:"target"`
}

type bbBranchesResponse struct {
Values []bbBranch `json:"values"`
Next string `json:"next"`
}

// convertBitbucketBranch maps a Bitbucket branch. Branch objects don't say
// whether the branch is the main branch or has restrictions, so Default and
// Protected stay false.
Expand All @@ -50,41 +41,9 @@ func (s *bitbucketBranchService) doJSON(ctx context.Context, method, url string,
}

func (s *bitbucketBranchService) List(ctx context.Context, owner, repo string, opts forge.ListBranchOpts) ([]forge.Branch, error) {
perPage := opts.PerPage
if perPage <= 0 || perPage > maxBranchPageLen {
perPage = maxBranchPageLen
}
// A start page is counted in pages of perPage, so the page size can only
// shrink to the limit when listing from the first page.
if opts.Limit > 0 && perPage > opts.Limit && opts.Page <= 1 {
perPage = opts.Limit
}

u := fmt.Sprintf("%s/repositories/%s/%s/refs/branches?pagelen=%d", bitbucketAPI, owner, repo, perPage)
if opts.Page > 1 {
u += fmt.Sprintf("&page=%d", opts.Page)
}

var all []forge.Branch
for u != "" {
var page bbBranchesResponse
if err := s.doJSON(ctx, http.MethodGet, u, nil, &page); err != nil {
return nil, err
}
for _, bb := range page.Values {
all = append(all, convertBitbucketBranch(bb))
}
if opts.Limit > 0 && len(all) >= opts.Limit {
break
}
u = page.Next
}

if opts.Limit > 0 && len(all) > opts.Limit {
all = all[:opts.Limit]
}

return all, nil
u := fmt.Sprintf("%s/repositories/%s/%s/refs/branches?%s", bitbucketAPI, owner, repo, pageQuery(opts.Page, opts.PerPage, opts.Limit))
rs := &bitbucketRepoService{token: s.token, httpClient: s.httpClient}
return listPages(ctx, rs, u, opts.Limit, convertBitbucketBranch)
}

// Create creates branch name at the head of branch from, or at from itself
Expand Down
80 changes: 70 additions & 10 deletions bitbucket/deploy_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,88 @@ package bitbucket

import (
"context"
"fmt"
"net/http"
"time"

forge "github.com/git-pkgs/forge"
)

type bitbucketDeployKeyService struct{}
type bitbucketDeployKeyService struct {
token string
httpClient *http.Client
}

func (f *bitbucketForge) DeployKeys() forge.DeployKeyService {
return &bitbucketDeployKeyService{}
return &bitbucketDeployKeyService{token: f.token, httpClient: f.httpClient}
}

type bbDeployKey struct {
ID int64 `json:"id"`
Key string `json:"key"`
Label string `json:"label"`
CreatedOn string `json:"created_on"`
}

// convertBitbucketDeployKey maps a Bitbucket deploy key. Bitbucket deploy
// keys can only read, so ReadOnly is always true.
func convertBitbucketDeployKey(bb bbDeployKey) forge.DeployKey {
result := forge.DeployKey{
ID: bb.ID,
Title: bb.Label,
Key: bb.Key,
ReadOnly: true,
}
if t, err := time.Parse(time.RFC3339, bb.CreatedOn); err == nil {
result.CreatedAt = t
}
return result
}

func (s *bitbucketDeployKeyService) List(_ context.Context, _, _ string, _ forge.ListDeployKeyOpts) ([]forge.DeployKey, error) {
return nil, forge.ErrNotSupported
func (s *bitbucketDeployKeyService) repoService() *bitbucketRepoService {
return &bitbucketRepoService{token: s.token, httpClient: s.httpClient}
}

func (s *bitbucketDeployKeyService) Get(_ context.Context, _, _ string, _ int64) (*forge.DeployKey, error) {
return nil, forge.ErrNotSupported
func deployKeysURL(owner, repo string) string {
return fmt.Sprintf("%s/repositories/%s/%s/deploy-keys", bitbucketAPI, owner, repo)
}

func (s *bitbucketDeployKeyService) Create(_ context.Context, _, _ string, _ forge.CreateDeployKeyOpts) (*forge.DeployKey, error) {
return nil, forge.ErrNotSupported
func (s *bitbucketDeployKeyService) List(ctx context.Context, owner, repo string, opts forge.ListDeployKeyOpts) ([]forge.DeployKey, error) {
u := deployKeysURL(owner, repo) + "?" + pageQuery(opts.Page, opts.PerPage, opts.Limit)
return listPages(ctx, s.repoService(), u, opts.Limit, convertBitbucketDeployKey)
}

func (s *bitbucketDeployKeyService) Get(ctx context.Context, owner, repo string, id int64) (*forge.DeployKey, error) {
var bb bbDeployKey
u := fmt.Sprintf("%s/%d", deployKeysURL(owner, repo), id)
if err := s.repoService().doJSON(ctx, http.MethodGet, u, nil, &bb); err != nil {
return nil, err
}
result := convertBitbucketDeployKey(bb)
return &result, nil
}

// Create adds a deploy key. Bitbucket has no deploy keys with write access,
// so asking for one fails with forge.ErrNotSupported instead of silently
// creating a key that can only read.
func (s *bitbucketDeployKeyService) Create(ctx context.Context, owner, repo string, opts forge.CreateDeployKeyOpts) (*forge.DeployKey, error) {
if !opts.ReadOnly {
return nil, fmt.Errorf("creating a deploy key with write access: %w", forge.ErrNotSupported)
}

body := map[string]string{
"key": opts.Key,
"label": opts.Title,
}
var bb bbDeployKey
if err := s.repoService().doJSON(ctx, http.MethodPost, deployKeysURL(owner, repo), body, &bb); err != nil {
return nil, err
}
result := convertBitbucketDeployKey(bb)
return &result, nil
}

func (s *bitbucketDeployKeyService) Delete(_ context.Context, _, _ string, _ int64) error {
return forge.ErrNotSupported
func (s *bitbucketDeployKeyService) Delete(ctx context.Context, owner, repo string, id int64) error {
u := fmt.Sprintf("%s/%d", deployKeysURL(owner, repo), id)
return s.repoService().doJSON(ctx, http.MethodDelete, u, nil, nil)
}
170 changes: 156 additions & 14 deletions bitbucket/deploy_keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,173 @@ package bitbucket

import (
"context"
"encoding/json"
"errors"
forge "github.com/git-pkgs/forge"
"net/http"
"testing"
"time"

forge "github.com/git-pkgs/forge"
)

func TestBitbucketDeployKeyNotSupported(t *testing.T) {
svc := &bitbucketDeployKeyService{}
const deployKeyTestKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKoJlWbTSIfrkeBd3Ti0FbfIEe4kmYVnrIBzMrVAzuhk"

_, err := svc.List(context.Background(), "owner", "repo", forge.ListDeployKeyOpts{})
if !errors.Is(err, forge.ErrNotSupported) {
t.Errorf("List: expected forge.ErrNotSupported, got %v", err)
func deployKeyJSON(id int64, label string) map[string]any {
return map[string]any{
"type": "deploy_key",
"id": id,
"key": deployKeyTestKey,
"label": label,
"comment": "ci@example.com",
"created_on": "2024-03-05T10:20:30.123456+00:00",
"last_used": nil,
}
}

_, err = svc.Get(context.Background(), "owner", "repo", 1)
if !errors.Is(err, forge.ErrNotSupported) {
t.Errorf("Get: expected forge.ErrNotSupported, got %v", err)
func TestBitbucketListDeployKeys(t *testing.T) {
var srvURL string
mux := http.NewServeMux()
mux.HandleFunc("GET /2.0/repositories/atlassian/stash/deploy-keys", 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") == "" {
assertEqual(t, "pagelen", "100", r.URL.Query().Get("pagelen"))
_ = json.NewEncoder(w).Encode(map[string]any{
"values": []any{deployKeyJSON(11, "ci")},
"next": srvURL + "/2.0/repositories/atlassian/stash/deploy-keys?pagelen=100&page=2",
})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{
"values": []any{deployKeyJSON(12, "mirror")},
})
})
f, u := newTestForge(t, mux)
srvURL = u

keys, err := f.DeployKeys().List(context.Background(), "atlassian", "stash", forge.ListDeployKeyOpts{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

_, err = svc.Create(context.Background(), "owner", "repo", forge.CreateDeployKeyOpts{})
if !errors.Is(err, forge.ErrNotSupported) {
t.Errorf("Create: expected forge.ErrNotSupported, got %v", err)
created := time.Date(2024, 3, 5, 10, 20, 30, 123456000, time.UTC)
want := []forge.DeployKey{
{ID: 11, Title: "ci", Key: deployKeyTestKey, ReadOnly: true, CreatedAt: created},
{ID: 12, Title: "mirror", Key: deployKeyTestKey, ReadOnly: true, CreatedAt: created},
}
if len(keys) != len(want) {
t.Fatalf("got %d keys, want %d: %+v", len(keys), len(want), keys)
}
for i := range want {
if keys[i].ID != want[i].ID || keys[i].Title != want[i].Title || keys[i].Key != want[i].Key ||
keys[i].ReadOnly != want[i].ReadOnly || !keys[i].CreatedAt.Equal(want[i].CreatedAt) {
t.Errorf("keys[%d] = %+v, want %+v", i, keys[i], want[i])
}
}
}

func TestBitbucketListDeployKeysLimit(t *testing.T) {
var requests int
mux := http.NewServeMux()
mux.HandleFunc("GET /2.0/repositories/atlassian/stash/deploy-keys", func(w http.ResponseWriter, r *http.Request) {
requests++
assertEqual(t, "pagelen", "1", r.URL.Query().Get("pagelen"))
_ = json.NewEncoder(w).Encode(map[string]any{
"values": []any{deployKeyJSON(11, "ci")},
"next": "http://unused.invalid/next",
})
})
f, _ := newTestForge(t, mux)

keys, err := f.DeployKeys().List(context.Background(), "atlassian", "stash", forge.ListDeployKeyOpts{Limit: 1})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
assertEqualInt(t, "len", 1, len(keys))
assertEqualInt(t, "requests", 1, requests)
}

func TestBitbucketGetDeployKey(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /2.0/repositories/atlassian/stash/deploy-keys/11", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(deployKeyJSON(11, "ci"))
})
f, _ := newTestForge(t, mux)

key, err := f.DeployKeys().Get(context.Background(), "atlassian", "stash", 11)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
assertEqualInt(t, "ID", 11, int(key.ID))
assertEqual(t, "Title", "ci", key.Title)
assertEqual(t, "Key", deployKeyTestKey, key.Key)
assertEqualBool(t, "ReadOnly", true, key.ReadOnly)

if _, err := f.DeployKeys().Get(context.Background(), "atlassian", "stash", 99); !errors.Is(err, forge.ErrNotFound) {
t.Errorf("Get missing key: err = %v, want ErrNotFound", err)
}
}

func TestBitbucketCreateDeployKey(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("POST /2.0/repositories/atlassian/stash/deploy-keys", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decoding body: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
want := map[string]any{"key": deployKeyTestKey, "label": "ci"}
if len(body) != len(want) || body["key"] != want["key"] || body["label"] != want["label"] {
t.Errorf("body = %v, want %v", body, want)
}
_ = json.NewEncoder(w).Encode(deployKeyJSON(11, "ci"))
})
f, _ := newTestForge(t, mux)

key, err := f.DeployKeys().Create(context.Background(), "atlassian", "stash", forge.CreateDeployKeyOpts{
Title: "ci",
Key: deployKeyTestKey,
ReadOnly: true,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
assertEqualInt(t, "ID", 11, int(key.ID))
assertEqual(t, "Title", "ci", key.Title)
assertEqualBool(t, "ReadOnly", true, key.ReadOnly)
}

func TestBitbucketCreateDeployKeyWithWriteAccess(t *testing.T) {
f, _ := newTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}))

err = svc.Delete(context.Background(), "owner", "repo", 1)
_, err := f.DeployKeys().Create(context.Background(), "atlassian", "stash", forge.CreateDeployKeyOpts{
Title: "ci",
Key: deployKeyTestKey,
})
if !errors.Is(err, forge.ErrNotSupported) {
t.Errorf("Delete: expected forge.ErrNotSupported, got %v", err)
t.Errorf("err = %v, want ErrNotSupported", err)
}
}

func TestBitbucketDeleteDeployKey(t *testing.T) {
var deleted bool
mux := http.NewServeMux()
mux.HandleFunc("DELETE /2.0/repositories/atlassian/stash/deploy-keys/11", func(w http.ResponseWriter, r *http.Request) {
deleted = true
w.WriteHeader(http.StatusNoContent)
})
f, _ := newTestForge(t, mux)

if err := f.DeployKeys().Delete(context.Background(), "atlassian", "stash", 11); err != nil {
t.Fatalf("unexpected error: %v", err)
}
assertEqualBool(t, "deleted", true, deleted)

if err := f.DeployKeys().Delete(context.Background(), "atlassian", "stash", 99); !errors.Is(err, forge.ErrNotFound) {
t.Errorf("Delete missing key: err = %v, want ErrNotFound", err)
}
}
21 changes: 20 additions & 1 deletion bitbucket/helpers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package bitbucket

import "testing"
import (
"net/http"
"net/http/httptest"
"testing"

forge "github.com/git-pkgs/forge"
)

func assertEqual[T ~string](t *testing.T, field, want string, got T) {
t.Helper()
Expand All @@ -22,3 +28,16 @@ func assertEqualInt(t *testing.T, field string, want, got int) {
t.Errorf("%s: want %d, got %d", field, want, got)
}
}

// newTestForge points the Bitbucket API at a test server running h and
// returns a forge that authenticates with "test-token", along with the
// server's URL.
func newTestForge(t *testing.T, h http.Handler) (forge.Forge, string) {
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.URL
}
Loading
Loading