go-bitbucket

repository·master·Indexed 42 days ago

https://github.com/ktrysmt/go-bitbucket

A Go library for interacting with the Bitbucket Cloud REST API v2.0. It provides structured access to manage repositories, pull requests, issues, comments, pipelines, and branch restrictions. Supports multiple authentication methods including Atlassian API tokens, OAuth2 flows (Client Credentials, Authorization Code, Refresh Token), and legacy Basic Auth. Includes support for custom API base URLs and CA certificates for isolated or self-hosted instances.

Tokens
20.7K
Snippets
81
Records
130
Agent score
51%

What's inside go-bitbucket

  1. Workspace Pagination Structures

    master

    Several workspace-related methods return paginated results. The following structures define the pagination metadata:

    WorkspaceList (used by List()):

    • Page: Current page number.
    • Pagelen: Number of items per page.
    • MaxDepth: Maximum depth of the result set.
    • Size: Total number of items.
    • Next: URL for the next page.
    • Workspaces: Slice of Workspace objects.

    WorkspaceMembers (used by Members()):

    • Page: Current page number.
    • Pagelen: Number of items per page.
    • Size: Total number of items.
    • Members: Slice of User objects.

    ProjectsRes (used by Projects()):

    • Page: Current page number.
    • Pagelen: Number of items per page.
    • MaxDepth: Maximum depth.
    • Size: Total number of items.
    • Items: Slice of Project objects.
  2. How to use WithContext for API options

    master

    Many option structs in this library (e.g., RepositoryOptions, PullRequestsOptions, IssuesOptions, WebhooksOptions) include a context.Context field. You can pass a context to these options using the WithContext(ctx context.Context) method. This is useful for managing request timeouts and cancellations in your Go applications.

    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()
    
    opts := bitbucket.RepositoryOptions{
        Owner:    "my-workspace",
        RepoSlug: "my-repo",
    }.WithContext(ctx)
    
    repo, err := client.Repository.Get(opts)
  3. Configure custom API base URLs and CA certificates

    master

    For Isolated Cloud Instances, self-hosted instances, or proxies, you can specify a custom base URL.

    • Use *WithBaseUrlStr variants (available for NewAPITokenAuth, NewBasicAuth, and NewOAuthbearerToken) to provide a URL string.
    • Use *WithBaseUrlStrCaCert to provide a custom base URL along with a PEM bundle for private CAs.
    • For OAuth-handshake constructors, use the *WithEndpoint variants to override the default OAuth endpoints, and combine them with client.SetApiBaseURL to redirect REST traffic to the same host.
    • Alternatively, set the BITBUCKET_API_BASE_URL environment variable to override the default for any constructor that does not take a URL argument.
    // Custom Base URL
    c, err := bitbucket.NewAPITokenAuthWithBaseUrlStr(
        "you@example.com",
        "your-api-token",
        "https://api.your-isolated-instance.example.com/2.0",
    )
    
    // Custom Base URL with CA Cert
    caBundle, _ := os.ReadFile("/etc/ssl/private-ca.pem")
    c, err := bitbucket.NewAPITokenAuthWithBaseUrlStrCaCert(
        "you@example.com",
        "your-api-token",
        "https://api.your-isolated-instance.example.com/2.0",
        caBundle,
    )
  4. Repository Data Structures

    master

    The following types represent the core data models returned by the Bitbucket API:

    • Repository: Represents a Bitbucket repository, including metadata like Uuid, Name, Slug, Is_private, and Mainbranch.
    • RepositoryFile: Metadata for a file within a repository.
    • RepositoryBranch: Details about a branch, including its Name and Merge_Strategies.
    • RepositoryTag: Details about a git tag.
    • Pipeline: Configuration for repository pipelines.
    • Environment: Represents a deployment environment.
    • Group: Represents a Bitbucket group and its permissions.
  5. Configure Custom API Base URL and CA Certificates

    master

    When working with Isolated Cloud Instances or self-hosted Bitbucket instances behind a proxy, you can provide a custom API base URL and/or custom CA certificates in most constructor functions.

    Common patterns:

    • ...WithBaseUrlStr(..., urlStr): Sets a custom API endpoint.
    • ...WithCaCert(..., caCerts): Appends custom PEM-encoded CA certificates to the system cert pool.
    • ...WithBaseUrlStrCaCert(..., urlStr, caCerts): Combines both.

    Example using API Token with custom settings:

    client, err := bitbucket.NewAPITokenAuthWithBaseUrlStrCaCert(
        "email@example.com", 
        "token", 
        "https://custom-bitbucket.example.com/api/2.0", 
        caCertBytes,
    )
  6. Create a pull request

    master

    Use c.Repositories.PullRequests.Create(opt) with a *bitbucket.PullRequestsOptions object to create a new pull request.

    package main
    
    import (
            "fmt"
            "github.com/ktrysmt/go-bitbucket"
    )
    
    func main() {
            c := bitbucket.NewAPITokenAuth("you@example.com", "your-api-token")
    
            opt := &bitbucket.PullRequestsOptions{
                    Owner:             "your-team",
                    RepoSlug:          "awesome-project",
                    SourceBranch:      "develop",
                    DestinationBranch: "master",
                    Title:             "fix bug. #9999",
                    CloseSourceBranch: true,
            }
    
            res, err := c.Repositories.PullRequests.Create(opt)
            if err != nil {
                    panic(err)
            }
    
            fmt.Println(res)
    }
  7. Create a repository

    master

    Use c.Repositories.Repository.Create(opt) with a *bitbucket.RepositoryOptions object to create a new repository.

    package main
    
    import (
            "fmt"
            "github.com/ktrysmt/go-bitbucket"
    )
    
    func main() {
            c := bitbucket.NewAPITokenAuth("you@example.com", "your-api-token")
    
            opt := &bitbucket.RepositoryOptions{
                    Owner:    "project_name",
                    RepoSlug: "repo_name",
                    Scm:      "git",
            }
    
            res, err := c.Repositories.Repository.Create(opt)
            if err != nil {
                    panic(err)
            }
    
            fmt.Println(res)
    }
  8. Authenticate using an Atlassian API token (recommended)

    master

    Atlassian has deprecated app passwords. Use NewAPITokenAuth by passing your Atlassian account email as the username and the API token as the password. This is a thin alias over NewBasicAuth.

    c := bitbucket.NewAPITokenAuth("you@example.com", "your-api-token")
  9. Authenticate using OAuth flows

    master

    If you handle the OAuth handshake yourself, use the following constructors depending on your flow:

    • Client Credentials: NewOAuthClientCredentials(clientID, clientSecret)
    • Authorization Code: NewOAuthWithCode(clientID, clientSecret, authCode)
    • Refresh Token: NewOAuthWithRefreshToken(clientID, clientSecret, refreshToken)
    c, err := bitbucket.NewOAuthClientCredentials("client-id", "client-secret")
    c, accessToken, err := bitbucket.NewOAuthWithCode("client-id", "client-secret", "auth-code")
    c, accessToken, err := bitbucket.NewOAuthWithRefreshToken("client-id", "client-secret", "refresh-token")