sourcecraft

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2026 License: MIT Imports: 16 Imported by: 0

README

sourcecraft-sdk

A Go client library for the SourceCraft Public API.

About SourceCraft

SourceCraft is a comprehensive platform for software development lifecycle management. It provides:

  • Code Repository Management - Git-based version control with branching, pull requests, and code review
  • CI/CD Pipeline - Automated testing and deployment workflows
  • Error Tracking - Built-in issue tracking and monitoring
  • Code Assistant - AI-powered code editing, review, and vulnerability analysis
  • Security - Vulnerability scanning, secret detection, and dependency analysis
  • Package Management - Support for Maven, NPM, NuGet, PyPI, Docker registries
  • Access Control - Organization-based permissions and team collaboration

Learn more at https://sourcecraft.dev/portal/docs/en/

About the API

The SourceCraft REST API enables automation and integration with SourceCraft resources including repositories, pull requests, issues, organizations, and more.

Authentication

The API uses Personal Access Tokens (PAT) for authentication. Tokens are passed via the Authorization: Bearer header.

For CI/CD workflows, use the SOURCECRAFT_TOKEN predefined environment variable.

API Documentation

Installation

go get github.com/aalexzy/sourcecraft-sdk

Usage

Basic Example
package main

import (
    "context"
    "fmt"
    "log"

    sourcecraft "github.com/aalexzy/sourcecraft-sdk"
)

func main() {
    // Create a new client
    client, err := sourcecraft.NewClient(
        "https://api.sourcecraft.tech",
        sourcecraft.SetToken("your-personal-access-token"),
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()
    
    // Use the client to interact with the API
    // Example: List repositories, manage pull requests, etc.
}
Client Options
With Personal Access Token
client, err := sourcecraft.NewClient(
    "https://api.sourcecraft.tech",
    sourcecraft.SetToken("your-pat-token"),
)
With Custom HTTP Client
httpClient := &http.Client{
    Timeout: time.Second * 30,
}

client, err := sourcecraft.NewClient(
    "https://api.sourcecraft.tech",
    sourcecraft.SetToken("your-pat-token"),
    sourcecraft.SetHTTPClient(httpClient),
)
Skip TLS Verification (Development Only)
client, err := sourcecraft.NewClient(
    "https://api.sourcecraft.tech",
    sourcecraft.SetToken("your-pat-token"),
    sourcecraft.WithHTTPClient(true), // insecure=true
)

Webhook Support

The SDK provides comprehensive webhook parsing and verification capabilities, allowing you to easily handle SourceCraft webhook events in your applications.

Setting Up a Webhook Handler
package main

import (
    "fmt"
    "log"
    "net/http"

    sourcecraft "github.com/aalexzy/sourcecraft-sdk"
)

func main() {
    // Create a webhook parser with secret for HMAC verification
    hook, err := sourcecraft.New(
        sourcecraft.Options.Secret("your-webhook-secret"),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Set up HTTP handler
    http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
        payload, err := hook.Parse(r, sourcecraft.PushEvent, sourcecraft.PullRequestAggregate)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }

        // Handle the event
        switch p := payload.(type) {
        case sourcecraft.PushEventPayload:
            handlePushEvent(p)
        case sourcecraft.PullRequestEventPayload:
            handlePullRequestEvent(p)
        }

        w.WriteHeader(http.StatusOK)
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}
Handling Push Events
func handlePushEvent(payload sourcecraft.PushEventPayload) {
    fmt.Printf("Push event received for repository: %s\n", payload.Repository.Name)
    fmt.Printf("Pushed by: %s\n", payload.Pusher.Slug)
    fmt.Printf("Branch: %s\n", payload.RefUpdate.RefName)
    fmt.Printf("Default branch updated: %v\n", payload.IsDefaultBranchUpdated)
    
    // Process commits
    for _, commit := range payload.Commits {
        fmt.Printf("  Commit %s by %s: %s\n", 
            commit.Sha[:7], 
            commit.Author.Name, 
            commit.Message)
    }
}
Handling Pull Request Events

The SDK provides a convenient PullRequestEventPayload interface that all PR events implement, allowing you to handle all PR events uniformly:

func handlePullRequestEvent(payload sourcecraft.PullRequestEventPayload) {
    pr := payload.GetPullRequest()
    repo := payload.GetRepository()
    eventType := payload.GetEventType()
    
    fmt.Printf("Pull Request event: %s\n", eventType)
    fmt.Printf("Repository: %s\n", repo.Name)
    fmt.Printf("PR #%d: %s\n", pr.Number, pr.Title)
    fmt.Printf("Status: %s\n", pr.Status)
    fmt.Printf("From: %s -> %s\n", pr.SourceBranch, pr.TargetBranch)
    
    // Handle specific event types
    switch eventType {
    case sourcecraft.PullRequestCreateEvent:
        fmt.Println("New pull request created")
    case sourcecraft.PullRequestMergeEvent:
        fmt.Println("Pull request merged")
    case sourcecraft.PullRequestPublishEvent:
        fmt.Println("Pull request published")
    }
}
Handling Specific Pull Request Events

You can also handle specific PR event types individually:

// Parse only specific events
payload, err := hook.Parse(r, 
    sourcecraft.PullRequestCreateEvent,
    sourcecraft.PullRequestMergeEvent,
)
if err != nil {
    log.Printf("Error parsing webhook: %v", err)
    return
}

// Type assert to specific payload type
switch p := payload.(type) {
case sourcecraft.PullRequestCreateEventPayload:
    fmt.Printf("New PR created: %s\n", p.PullRequest.Title)
    fmt.Printf("Created at: %s\n", p.CreatedAt)
    
case sourcecraft.PullRequestMergeEventPayload:
    fmt.Printf("PR merged: %s\n", p.PullRequest.Title)
    fmt.Printf("Merged SHA: %s\n", p.MergeSha)
}
Using Event Aggregates

Event aggregates allow you to subscribe to all events of a certain type without listing each one:

// Listen to all pull request events using aggregate
payload, err := hook.Parse(r, sourcecraft.PullRequestAggregate)
if err != nil {
    log.Printf("Error: %v", err)
    return
}

// All PR events implement PullRequestEventPayload interface
if prPayload, ok := payload.(sourcecraft.PullRequestEventPayload); ok {
    handlePullRequestEvent(prPayload)
}
Supported Events
Individual Events
  • PingEvent - Webhook ping/test event
  • PushEvent - Git push to repository
  • PullRequestCreateEvent - Pull request created
  • PullRequestUpdateEvent - Pull request updated
  • PullRequestPublishEvent - Pull request published
  • PullRequestRefreshEvent - Pull request refreshed
  • PullRequestMergeEvent - Pull request merged
  • PullRequestMergeFailureEvent - Pull request merge failed
  • PullRequestNewIterationEvent - New iteration added to PR
  • PullRequestReviewAssignmentEvent - Reviewer assigned to PR
  • PullRequestReviewDecisionEvent - Review decision made on PR
Event Aggregates
  • PullRequestAggregate - Matches all pull_request.* events
HMAC Signature Verification

The webhook parser automatically verifies HMAC signatures when a secret is provided:

// Single secret
hook, err := sourcecraft.New(
    sourcecraft.Options.Secret("your-webhook-secret"),
)

// Multiple secrets for secret rotation (comma-separated)
hook, err := sourcecraft.New(
    sourcecraft.Options.Secret("secret1,secret2,secret3"),
)

The parser will verify the X-Src-Signature header against the request payload using SHA-256 HMAC.

Without Signature Verification

If you don't need signature verification (not recommended for production):

hook, err := sourcecraft.New()
// No secret option provided

Features

This SDK provides Go bindings for the SourceCraft API, including:

  • Organization management
  • Repository operations
  • Pull request handling
  • Webhook parsing and verification with HMAC signature support
  • Issue tracking
  • Thread-safe client with concurrent access support

Development

Running Tests
go test ./...
Requirements
  • Go 1.25.5 or later

License

See LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

Documentation

Overview

Package sourcecraft provides a Go client library for the SourceCraft API.

SourceCraft is a comprehensive platform for software development lifecycle management, providing code repository management, CI/CD pipelines, error tracking, and more.

API Client

The Client type provides methods to interact with the SourceCraft REST API. Create a client using NewClient with your API endpoint and authentication token:

client, err := sourcecraft.NewClient(
    "https://api.sourcecraft.tech",
    sourcecraft.SetToken("your-personal-access-token"),
)

Webhook Support

The package includes comprehensive webhook parsing and verification capabilities. Create a webhook parser to handle incoming webhook events:

hook, err := sourcecraft.New(
    sourcecraft.Options.Secret("your-webhook-secret"),
)

Parse incoming webhook requests and handle events:

payload, err := hook.Parse(r, sourcecraft.PushEvent, sourcecraft.PullRequestAggregate)
if err != nil {
    // handle error
}

switch p := payload.(type) {
case sourcecraft.PushEventPayload:
    // handle push event
case sourcecraft.PullRequestEventPayload:
    // handle pull request event
}

The webhook parser automatically verifies HMAC signatures using SHA-256 when a secret is configured, ensuring webhook authenticity.

Thread Safety

All Client methods are safe for concurrent use. The Client type uses internal synchronization to protect shared state.

Resources

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEventNotSpecifiedToParse = errors.New("no Event specified to parse")
	ErrInvalidHTTPMethod        = errors.New("invalid HTTP Method")
	ErrMissingSrcEventHeader    = errors.New("missing X-Src-Event Header")
	ErrMissingSignatureHeader   = errors.New("missing X-Src-Signature Header")
	ErrEventNotFound            = errors.New("event not defined to be parsed")
	ErrParsingPayload           = errors.New("error parsing payload")
	ErrHMACVerificationFailed   = errors.New("HMAC verification failed")
)

Webhook parsing errors.

View Source
var Options = WebhookOptions{}

Options provides a namespace for webhook configuration options.

Functions

This section is empty.

Types

type Branch

type Branch struct {
	// Name is the name of the branch.
	Name string `json:"name"`
	// Commit is the latest commit on the branch.
	Commit *Commit `json:"commit"`
}

Branch represents a Git branch with its latest commit.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an HTTP client for interacting with the Sourcecraft API. It manages authentication, HTTP connections, and provides thread-safe access to API endpoints. All methods are safe for concurrent use.

func NewClient

func NewClient(url string, options ...ClientOption) (*Client, error)

NewClient initializes and returns a API client. Usage of all Client methods is thread safe.

func (*Client) GetRepoBranch

func (c *Client) GetRepoBranch(ctx context.Context, orgSlug, repoSlug, branch string) (*Branch, *Response, error)

GetRepoBranch retrieves a specific branch by name from the repository. It filters the branch list by name and returns the first matching branch.

func (*Client) ListOrgRepos

func (c *Client) ListOrgRepos(ctx context.Context, orgSlug string, opt ListOrgReposOptions) (*ListOrgReposResponse, *Response, error)

ListOrgRepos lists all repositories for the specified organization. It returns a paginated list of repositories along with a next page token for pagination.

Parameters:

  • ctx: The context for the request
  • orgSlug: The organization slug identifier
  • opt: Optional parameters for pagination and filtering

Returns the list of repositories, HTTP response metadata, and any error encountered.

func (*Client) ListRepoBranches

func (c *Client) ListRepoBranches(ctx context.Context, orgSlug, repoSlug string, opt ListRepoBranchesOptions) (*ListRepoBranchesResponse, *Response, error)

ListRepoBranches lists all branches in the specified repository. It returns a paginated list of branches for the given organization and repository slugs.

func (*Client) ListRepoFileTree

func (c *Client) ListRepoFileTree(ctx context.Context, orgSlug, repoSlug string, revision string, path string, opt ListRepoFileTreeOptions) (*ListRepoFileTreeResponse, *Response, error)

ListRepoFileTree lists files and directories in the repository at a specific revision and path. The revision parameter specifies the branch, tag, or commit SHA to query. The path parameter specifies the directory path within the repository.

func (*Client) ListRepoLabels

func (c *Client) ListRepoLabels(ctx context.Context, orgSlug, repoSlug string, opt ListLabelsOptions) (*ListRepoLabelsResponse, *Response, error)

ListRepoLabels lists all labels in the specified repository. It returns a paginated list of labels for the given organization and repository slugs.

func (*Client) ListRepoPullRequests

func (c *Client) ListRepoPullRequests(ctx context.Context, orgSlug, repoSlug string, opt ListRepoPullRequestsOptions) (*ListRepoPullRequestsResponse, *Response, error)

ListRepoPullRequests lists all pull requests in the specified repository. It returns a paginated list of pull requests for the given organization and repository slugs.

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(client *http.Client)

SetHTTPClient replaces the default http.Client with a user-provided one. This method is thread-safe and can be called concurrently.

type ClientOption

type ClientOption func(*Client) error

ClientOption are functions used to init a new client

func SetHTTPClient

func SetHTTPClient(httpClient *http.Client) ClientOption

SetHTTPClient returns a ClientOption that replaces the default http.Client with a user-provided one during client initialization.

func SetToken

func SetToken(token string) ClientOption

SetToken is an option for NewClient to set token

func WithHTTPClient

func WithHTTPClient(insecure bool) ClientOption

WithHTTPClient returns a ClientOption that configures the HTTP client with optional TLS verification settings. When insecure is true, it creates a client that skips TLS certificate verification (useful for testing but not recommended for production).

type CloneURL

type CloneURL struct {
	// Https is the HTTPS clone URL.
	Https string `json:"https"`
	// Ssh is the SSH clone URL.
	Ssh string `json:"ssh"`
}

CloneURL contains the URLs for cloning a repository via different protocols.

type Commit

type Commit struct {
	// Hash is the SHA-1 hash of the commit.
	Hash string `json:"hash"`
	// Message is the commit message.
	Message string `json:"message"`
	// Author is the author of the commit.
	Author *Signature `json:"author"`
	// Committer is the committer of the commit.
	Committer *Signature `json:"committer"`
	// TreeHash is the SHA-1 hash of the commit's tree object.
	TreeHash string `json:"tree_hash"`
	// ParentHashes are the SHA-1 hashes of the parent commits.
	ParentHashes []string `json:"parent_hashes"`
	// MergeTag is the merge tag, if this is a merge commit.
	MergeTag string `json:"merge_tag"`
	// FileChanges contains the files that were changed in this commit.
	FileChanges *CommitFileChanges `json:"file_changes"`
}

Commit represents a Git commit with its metadata and changes.

type CommitFileChanges

type CommitFileChanges struct {
	// Added contains the paths of files that were added.
	Added []string `json:"added"`
	// Modified contains the paths of files that were modified.
	Modified []string `json:"modified"`
	// Removed contains the paths of files that were removed.
	Removed []string `json:"removed"`
}

CommitFileChanges represents the files changed in a commit.

type Event

type Event string

Event represents a webhook event type from SourceCraft.

const (
	// PingEvent is sent when a webhook is first created or tested.
	PingEvent Event = "webhook.ping"
	// PushEvent is sent when commits are pushed to a repository.
	PushEvent Event = "repository.push"
	// PullRequestCreateEvent is sent when a pull request is created.
	PullRequestCreateEvent Event = "pull_request.create"
	// PullRequestUpdateEvent is sent when a pull request is updated.
	PullRequestUpdateEvent Event = "pull_request.update"
	// PullRequestPublishEvent is sent when a pull request is published.
	PullRequestPublishEvent Event = "pull_request.publish"
	// PullRequestRefreshEvent is sent when a pull request is refreshed.
	PullRequestRefreshEvent Event = "pull_request.refresh"
	// PullRequestMergeFailureEvent is sent when a pull request merge fails.
	PullRequestMergeFailureEvent Event = "pull_request.merge_failure"
	// PullRequestMergeEvent is sent when a pull request is merged.
	PullRequestMergeEvent Event = "pull_request.merge"
	// PullRequestNewIterationEvent is sent when a new iteration is added to a pull request.
	PullRequestNewIterationEvent Event = "pull_request.new_iteration"
	// PullRequestReviewAssignmentEvent is sent when a reviewer is assigned to a pull request.
	PullRequestReviewAssignmentEvent Event = "pull_request.review_assignment"
	// PullRequestReviewDecisionEvent is sent when a review decision is made on a pull request.
	PullRequestReviewDecisionEvent Event = "pull_request.review_decision"
)

Supported webhook event types.

type EventAggregate

type EventAggregate string

EventAggregate represents an aggregate type that matches multiple related events.

const (
	// PullRequestAggregate matches all pull request events (pull_request.*).
	// Use this to subscribe to all pull request events without listing each one.
	PullRequestAggregate EventAggregate = "pull_request"
)

Supported webhook event aggregates.

type EventHeader

type EventHeader struct {
	// Id is the unique identifier for this event instance.
	Id string `json:"id"`
	// Type is the event type.
	Type string `json:"type"`
	// OccurredAt is when the event occurred.
	OccurredAt time.Time `json:"occurred_at"`
	// AggregateId is the ID of the primary entity this event is about.
	AggregateId string `json:"aggregate_id"`
	// AggregateType is the type of the primary entity (derived from event_type).
	AggregateType string `json:"aggregate_type"`
	// Metadata is the public metadata.
	Metadata map[string]string `json:"metadata"`
	// OrganizationId is the organization context.
	OrganizationId string `json:"organization_id"`
	// RepositoryId is the repository context.
	RepositoryId *string `json:"repository_id"`
	// TriggeredBy is the user that triggered event.
	TriggeredBy *UserEmbedded `json:"triggered_by"`
}

EventHeader is the common header included in all public events.

type EventMatcher

type EventMatcher interface {
	// contains filtered or unexported methods
}

EventMatcher is an interface that both Event and EventAggregate implement. This allows the Parse method to accept both specific events and event aggregates.

type Image

type Image struct {
	// Url is the URL where the image can be accessed.
	Url string `json:"url"`
}

Image represents an image with its URL.

type IssueEmbedded

type IssueEmbedded struct {
	// Id is the unique identifier of the issue.
	Id string `json:"id"`
	// Slug is the URL-friendly identifier of the issue.
	Slug string `json:"slug"`
}

IssueEmbedded represents a minimal issue reference with ID and slug.

type Label

type Label struct {
	// Id is the unique identifier of the label.
	Id string `json:"id"`
	// Name is the display name of the label.
	Name string `json:"name"`
	// Slug is the URL-friendly identifier of the label.
	Slug string `json:"slug"`
	// Color is the hex color code for the label.
	Color string `json:"color"`
	// Author is the user who created the label.
	Author *UserEmbedded `json:"author"`
	// UpdatedBy is the user who last updated the label.
	UpdatedBy *UserEmbedded `json:"updated_by"`
	// CreatedAt is the timestamp when the label was created.
	CreatedAt *time.Time `json:"created_at"`
	// UpdatedAt is the timestamp when the label was last updated.
	UpdatedAt *time.Time `json:"updated_at"`
}

Label represents a label that can be applied to issues and pull requests.

type Language

type Language struct {
	// Name is the name of the programming language.
	Name string `json:"name"`
	// Color is the hex color code associated with the language.
	Color string `json:"color"`
}

Language represents a programming language with its display properties.

type Link struct {
	// Link is the URL of the link.
	Link string `json:"link"`
	// Type specifies the type or category of the link.
	Type string `json:"type"`
}

Link represents a related link with its type.

type ListLabelsOptions

type ListLabelsOptions struct {
	ListOptions
}

ListLabelsOptions specifies options for listing repository labels.

type ListOptions

type ListOptions struct {
	// PageToken is the token for retrieving the next page of results.
	// Leave empty for the first page.
	PageToken string

	// PageSize specifies the maximum number of items to return per page.
	// If zero or negative, the server's default page size will be used.
	PageSize int

	// Filter is a filter expression to narrow down the results.
	// The syntax depends on the specific API endpoint being called.
	Filter string

	// SortBy specifies the field(s) to sort results by.
	// The format depends on the specific API endpoint being called.
	SortBy string
}

ListOptions contains pagination and filtering options for list operations. It supports token-based pagination, page size control, filtering, and sorting.

type ListOrgReposOptions

type ListOrgReposOptions struct {
	ListOptions
}

ListOrgReposOptions specifies optional parameters for listing organization repositories.

type ListOrgReposResponse

type ListOrgReposResponse struct {
	Repositories  []*Repository `json:"repositories"`
	NextPageToken string        `json:"next_page_token"`
}

ListOrgReposResponse represents the response from listing organization repositories.

type ListRepoBranchesOptions

type ListRepoBranchesOptions struct {
	ListOptions
}

ListRepoBranchesOptions specifies options for listing repository branches.

type ListRepoBranchesResponse

type ListRepoBranchesResponse struct {
	Branches      []*Branch `json:"branches"`
	NextPageToken string    `json:"next_page_token"`
}

ListRepoBranchesResponse contains the result of listing repository branches.

type ListRepoFileTreeOptions

type ListRepoFileTreeOptions struct {
	ListOptions

	// Recursive determines whether to recursively list subdirectories.
	Recursive *bool
}

ListRepoFileTreeOptions specifies options for listing repository file trees.

type ListRepoFileTreeResponse

type ListRepoFileTreeResponse struct {
	Trees         []*TreeEntry `json:"trees"`
	NextPageToken string       `json:"next_page_token"`
}

ListRepoFileTreeResponse contains the result of listing repository file trees.

type ListRepoLabelsResponse

type ListRepoLabelsResponse struct {
	Labels        []*Label `json:"items"`
	NextPageToken string   `json:"next_page_token"`
}

ListRepoLabelsResponse contains the result of listing repository labels.

type ListRepoPullRequestsOptions

type ListRepoPullRequestsOptions struct {
	ListOptions
}

ListRepoPullRequestsOptions specifies options for listing repository pull requests.

type ListRepoPullRequestsResponse

type ListRepoPullRequestsResponse struct {
	PullRequests  []*PullRequest `json:"pull_requests"`
	NextPageToken string         `json:"next_page_token"`
}

ListRepoPullRequestsResponse contains the result of listing repository pull requests.

type MergeInfo

type MergeInfo struct {
	// Merger is the user who performed the merge.
	Merger *UserEmbedded `json:"merger"`
	// MergeParameters contains the parameters used for the merge operation.
	MergeParameters *MergeParameters `json:"merge_parameters"`
	// TargetCommitHash is the commit hash of the target branch at merge time.
	TargetCommitHash string `json:"target_commit_hash"`
	// Error contains the error message if the merge failed.
	Error *string `json:"error"`
	// MergeCommitHash is the commit hash created by the merge, if successful.
	MergeCommitHash *string `json:"merge_commit_hash"`
}

MergeInfo contains information about a pull request merge operation.

type MergeParameters

type MergeParameters struct {
	// Rebase indicates whether to rebase the source branch before merging.
	Rebase *bool `json:"rebase"`
	// Squash indicates whether to squash commits before merging.
	Squash *bool `json:"squash"`
	// DeleteBranch indicates whether to delete the source branch after merging.
	DeleteBranch *bool `json:"delete_branch"`
}

MergeParameters specifies the options for merging a pull request.

type OrganizationEmbedded

type OrganizationEmbedded struct {
	// Id is the unique identifier of the organization.
	Id string `json:"id"`
	// Slug is the URL-friendly identifier of the organization.
	Slug string `json:"slug"`
}

OrganizationEmbedded represents a minimal organization reference with ID and slug.

type PingEventPayload

type PingEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository that the webhook is attached to.
	Repository *RepositoryEmbedded `json:"repository"`
	// WebhookSlug is the webhook slug identifier.
	WebhookSlug string `json:"webhook_slug"`
	// PingedAt is when the ping was sent.
	PingedAt *time.Time `json:"pinged_at"`
	// Organization is the organization that the repository belongs to.
	Organization *OrganizationEmbedded `json:"organization"`
}

PingEventPayload is sent when a webhook is tested.

type PullRequest

type PullRequest struct {
	// Id is the unique identifier of the pull request.
	Id string `json:"id"`
	// Slug is the URL-friendly identifier of the pull request.
	Slug string `json:"slug"`
	// Author is the user who created the pull request.
	Author *UserEmbedded `json:"author"`
	// UpdatedBy is the user who last updated the pull request.
	UpdatedBy *UserEmbedded `json:"updated_by"`
	// Title is the title of the pull request.
	Title string `json:"title"`
	// Description is the description text of the pull request.
	Description string `json:"description"`
	// Repository is the repository where the pull request exists.
	Repository *RepositoryEmbedded `json:"repository"`
	// MergeInfo contains information about the merge status and parameters.
	MergeInfo *MergeInfo `json:"merge_info"`
	// SourceBranch is the branch being merged from.
	SourceBranch string `json:"source_branch"`
	// TargetBranch is the branch being merged into.
	TargetBranch string `json:"target_branch"`
	// Status is the current status of the pull request (e.g., "open", "merged", "closed").
	Status string `json:"status"`
	// CreatedAt is the timestamp when the pull request was created.
	CreatedAt *time.Time `json:"created_at"`
	// UpdatedAt is the timestamp when the pull request was last updated.
	UpdatedAt *time.Time `json:"updated_at"`
	// LinkedIssues contains issues linked to this pull request.
	LinkedIssues []*IssueEmbedded `json:"linked_issues"`
}

PullRequest represents a pull request with its metadata and status.

type PullRequestCreateEventPayload

type PullRequestCreateEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request was created.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that was created.
	PullRequest *PullRequest `json:"pull_request"`
	// CreatedAt is when the pull request was created.
	CreatedAt *time.Time `json:"created_at"`
}

PullRequestCreateEventPayload represents creation of a new pull request.

func (PullRequestCreateEventPayload) GetEventType

func (p PullRequestCreateEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestCreateEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestCreateEventPayload) GetPullRequest

func (p PullRequestCreateEventPayload) GetPullRequest() *PullRequest

GetPullRequest returns the pull request.

func (PullRequestCreateEventPayload) GetRepository

func (p PullRequestCreateEventPayload) GetRepository() *Repository

GetRepository returns the repository.

type PullRequestEventPayload

type PullRequestEventPayload interface {
	// GetHeader returns the event header with common fields.
	GetHeader() *EventHeader
	// GetRepository returns the repository where the pull request is located.
	GetRepository() *Repository
	// GetPullRequest returns the pull request.
	GetPullRequest() *PullRequest
	// GetEventType returns the event type.
	GetEventType() Event
}

PullRequestEventPayload is a common interface for all pull request event payloads. This interface allows using Go type switch to handle all PR events in a single case branch.

type PullRequestMergeEventPayload

type PullRequestMergeEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that is being refreshed.
	PullRequest *PullRequest `json:"pull_request"`
	// MergeHash is the merge hash of the pull request.
	MergeHash string `json:"merge_hash"`
}

PullRequestMergeEventPayload represents merge success of a pull request.

func (PullRequestMergeEventPayload) GetEventType

func (p PullRequestMergeEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestMergeEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestMergeEventPayload) GetPullRequest

func (p PullRequestMergeEventPayload) GetPullRequest() *PullRequest

GetPullRequest returns the pull request.

func (PullRequestMergeEventPayload) GetRepository

func (p PullRequestMergeEventPayload) GetRepository() *Repository

GetRepository returns the repository.

type PullRequestMergeFailureEventPayload

type PullRequestMergeFailureEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that is being refreshed.
	PullRequest *PullRequest `json:"pull_request"`
	// ErrorMessage is the error message of the merge failure.
	ErrorMessage string `json:"error_message"`
}

PullRequestMergeFailureEventPayload represents merge failure of a pull request.

func (PullRequestMergeFailureEventPayload) GetEventType

func (p PullRequestMergeFailureEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestMergeFailureEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestMergeFailureEventPayload) GetPullRequest

GetPullRequest returns the pull request.

func (PullRequestMergeFailureEventPayload) GetRepository

GetRepository returns the repository.

type PullRequestNewIterationEventPayload

type PullRequestNewIterationEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that is being refreshed.
	PullRequest *PullRequest `json:"pull_request"`
	// CommitSha is the commit SHA of the iteration.
	CommitSha string `json:"commit_sha"`
	// MergeBaseSha is the merge base SHA of the iteration.
	MergeBaseSha string `json:"merge_base_sha"`
	// CreatedAt is the iteration created at timestamp.
	CreatedAt *time.Time `json:"created_at"`
	// UpdatedAt is the iteration updated at timestamp.
	UpdatedAt *time.Time `json:"updated_at"`
}

PullRequestNewIterationEventPayload represents new iteration on a pull request.

func (PullRequestNewIterationEventPayload) GetEventType

func (p PullRequestNewIterationEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestNewIterationEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestNewIterationEventPayload) GetPullRequest

GetPullRequest returns the pull request.

func (PullRequestNewIterationEventPayload) GetRepository

GetRepository returns the repository.

type PullRequestPublishEventPayload

type PullRequestPublishEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request was published.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that was published.
	PullRequest *PullRequest `json:"pull_request"`
	// PreviousStatus is the pull request previous status.
	PreviousStatus string `json:"previous_status"`
}

PullRequestPublishEventPayload represents publish of a pull request.

func (PullRequestPublishEventPayload) GetEventType

func (p PullRequestPublishEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestPublishEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestPublishEventPayload) GetPullRequest

func (p PullRequestPublishEventPayload) GetPullRequest() *PullRequest

GetPullRequest returns the pull request.

func (PullRequestPublishEventPayload) GetRepository

func (p PullRequestPublishEventPayload) GetRepository() *Repository

GetRepository returns the repository.

type PullRequestRefreshEventPayload

type PullRequestRefreshEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that is being refreshed.
	PullRequest *PullRequest `json:"pull_request"`
	// PreviousStatus is the pull request previous status.
	PreviousStatus string `json:"previous_status"`
	// HeadSha is the head SHA of the pull request.
	HeadSha string `json:"head_sha"`
	// MergeBaseSha is the merge base SHA of the pull request.
	MergeBaseSha string `json:"merge_base_sha"`
}

PullRequestRefreshEventPayload represents refresh of a pull request.

func (PullRequestRefreshEventPayload) GetEventType

func (p PullRequestRefreshEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestRefreshEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestRefreshEventPayload) GetPullRequest

func (p PullRequestRefreshEventPayload) GetPullRequest() *PullRequest

GetPullRequest returns the pull request.

func (PullRequestRefreshEventPayload) GetRepository

func (p PullRequestRefreshEventPayload) GetRepository() *Repository

GetRepository returns the repository.

type PullRequestReviewAssignmentEventPayload

type PullRequestReviewAssignmentEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that had reviewers modified.
	PullRequest *PullRequest `json:"pull_request"`
	// User is the user who made the assignment.
	User *UserEmbedded `json:"user"`
	// ReviewerDeltas is the reviewers deltas.
	ReviewerDeltas []*ReviewerDelta `json:"reviewer_deltas"`
}

PullRequestReviewAssignmentEventPayload represents changes to pull request reviewers.

func (PullRequestReviewAssignmentEventPayload) GetEventType

GetEventType returns the event type.

func (PullRequestReviewAssignmentEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestReviewAssignmentEventPayload) GetPullRequest

GetPullRequest returns the pull request.

func (PullRequestReviewAssignmentEventPayload) GetRepository

GetRepository returns the repository.

type PullRequestReviewDecisionEventPaylaod

type PullRequestReviewDecisionEventPaylaod struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that received the decision.
	PullRequest *PullRequest `json:"pull_request"`
	// User is the user who made the decision.
	User *UserEmbedded `json:"user"`
	// Decision is the review decision (ship, sticky_ship, block, abstain, or null for withdrawal).
	Decision string `json:"decision"`
}

PullRequestReviewDecisionEventPaylaod represents a review decision on a pull request.

func (PullRequestReviewDecisionEventPaylaod) GetEventType

GetEventType returns the event type.

func (PullRequestReviewDecisionEventPaylaod) GetHeader

GetHeader returns the event header.

func (PullRequestReviewDecisionEventPaylaod) GetPullRequest

GetPullRequest returns the pull request.

func (PullRequestReviewDecisionEventPaylaod) GetRepository

GetRepository returns the repository.

type PullRequestUpdateEventPayload

type PullRequestUpdateEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository where the pull request is located.
	Repository *Repository `json:"repository"`
	// PullRequest is the pull request that was updated.
	PullRequest *PullRequest `json:"pull_request"`
}

PullRequestUpdateEventPayload represents update of a pull request.

func (PullRequestUpdateEventPayload) GetEventType

func (p PullRequestUpdateEventPayload) GetEventType() Event

GetEventType returns the event type.

func (PullRequestUpdateEventPayload) GetHeader

GetHeader returns the event header.

func (PullRequestUpdateEventPayload) GetPullRequest

func (p PullRequestUpdateEventPayload) GetPullRequest() *PullRequest

GetPullRequest returns the pull request.

func (PullRequestUpdateEventPayload) GetRepository

func (p PullRequestUpdateEventPayload) GetRepository() *Repository

GetRepository returns the repository.

type PushEventPayload

type PushEventPayload struct {
	// Header is the event header with common fields.
	Header *EventHeader `json:"header"`
	// Repository is the repository that received the push.
	Repository *Repository `json:"repository"`
	// RefUpdate is the push details - single ref update in a single push.
	RefUpdate *RefUpdate `json:"ref_update"`
	// Pusher is who performed the push.
	Pusher *UserEmbedded `json:"pusher"`
	// PushedAt is the timestamp when the push occurred.
	PushedAt *time.Time `json:"pushed_at"`
	// Commits contains commit details for this event, from before_sha to after_sha.
	// In case of tag push or new branch creation before_sha is zero
	// and commits contain only single commit.
	Commits []*Commit `json:"commits"`
	// IsDefaultBranchUpdated indicates whether the default branch was updated in this push.
	IsDefaultBranchUpdated bool `json:"is_default_branch_updated"`
	// DefaultBranch is the default branch reference name (e.g., "refs/heads/main").
	DefaultBranch string `json:"default_branch"`
	// HasMoreCommits indicates whether there are more commits (due to commits limit).
	HasMoreCommits bool `json:"has_more_commits"`
}

PushEventPayload represents git push operation to a repository.

type RefUpdate

type RefUpdate struct {
	// Ref is the git reference being updated (e.g., "refs/heads/main").
	Ref string `json:"ref"`
	// Operation is the operation type.
	Operation string `json:"operation"`
	// BeforeSha is the commit SHA before the update (zeros for new ref).
	BeforeSha string `json:"before_sha"`
	// AfterSha is the commit SHA after the update (zeros for deleted ref).
	AfterSha string `json:"after_sha"`
	// CheckoutSha is for annotated tags: the peeled SHA (commit the tag points to).
	CheckoutSha string `json:"checkout_sha"`
}

RefUpdate represents a single ref update within a push.

type Repository

type Repository struct {
	// Id is the unique identifier of the repository.
	Id string `json:"id"`
	// Name is the display name of the repository.
	Name string `json:"name"`
	// DefaultBranch is the name of the default branch (e.g., "main" or "master").
	DefaultBranch string `json:"default_branch"`
	// Organization is the organization that owns the repository.
	Organization *OrganizationEmbedded `json:"organization"`
	// Slug is the URL-friendly identifier of the repository.
	Slug string `json:"slug"`
	// TemplateType specifies the template used to create the repository, if any.
	TemplateType string `json:"template_type"`
	// IsEmpty indicates whether the repository has no commits.
	IsEmpty bool `json:"is_empty"`
	// Description is the repository's description text.
	Description string `json:"description"`
	// Visibility specifies the repository's visibility (e.g., "public", "private").
	Visibility string `json:"visibility"`
	Logo *Image `json:"logo"`
	// CloneUrl contains the URLs for cloning the repository.
	CloneUrl *CloneURL `json:"clone_url"`
	// WebUrl is the URL to view the repository in a web browser.
	WebUrl string `json:"web_url"`
	// Links contains additional related links for the repository.
	Links []*Link `json:"links"`
	// Counters contains various statistics about the repository.
	Counters *RepositoryCounters `json:"counters"`
	// LastUpdated is the timestamp of the last update to the repository.
	LastUpdated *time.Time `json:"last_updated"`
	// Language is the primary programming language used in the repository.
	Language *Language `json:"language"`
	// Parent is the parent repository if this is a fork.
	Parent *RepositoryEmbedded `json:"parent"`
}

Repository represents a source code repository with its metadata and settings.

type RepositoryCounters

type RepositoryCounters struct {
	// Forks is the number of forks of the repository.
	Forks string `json:"forks"`
	// PullRequests is the number of pull requests in the repository.
	PullRequests string `json:"pull_requests"`
	// Issues is the number of issues in the repository.
	Issues string `json:"issues"`
	// Tags is the number of tags in the repository.
	Tags string `json:"tags"`
	// Branches is the number of branches in the repository.
	Branches string `json:"branches"`
}

RepositoryCounters contains various statistics about a repository.

type RepositoryEmbedded

type RepositoryEmbedded struct {
	// Id is the unique identifier of the repository.
	Id string `json:"id"`
	// Slug is the URL-friendly identifier of the repository.
	Slug string `json:"slug"`
}

RepositoryEmbedded represents a minimal repository reference with ID and slug.

type Response

type Response struct {
	*http.Response
}

Response wraps the standard http.Response to provide additional functionality for API responses.

type ReviewerDelta

type ReviewerDelta struct {
	// Action is the action performed.
	Action string `json:"action"`
	// UserId is the user ID.
	UserId string `json:"user_id"`
}

ReviewerDelta represents a change in the reviewer list for a pull request.

type Signature

type Signature struct {
	// Name is the name of the person.
	Name string `json:"name"`
	// Email is the email address of the person.
	Email string `json:"email"`
	// Date is the timestamp of the signature.
	Date *time.Time `json:"date"`
}

Signature represents a Git signature (author or committer) with timestamp.

type TreeEntry

type TreeEntry struct {
	// Name is the name of the file or directory.
	Name string `json:"name"`
	// Path is the full path to the file or directory.
	Path string `json:"path"`
	// Type specifies whether this is a file, directory, or other type.
	Type string `json:"type"`
}

TreeEntry represents an entry in a Git tree (file or directory).

type UserEmbedded

type UserEmbedded struct {
	// Id is the unique identifier of the user.
	Id string `json:"id"`
	// Slug is the URL-friendly identifier of the user.
	Slug string `json:"slug"`
}

UserEmbedded represents a minimal user reference with ID and slug.

type Webhook

type Webhook struct {
	// contains filtered or unexported fields
}

Webhook handles parsing and verification of SourceCraft webhook requests.

func New

func New(options ...WebhookOption) (*Webhook, error)

New creates a new Webhook instance with the provided options. Returns an error if any option fails to apply.

func (Webhook) Parse

func (hook Webhook) Parse(r *http.Request, events ...EventMatcher) (interface{}, error)

Parse parses a webhook HTTP request and returns the corresponding event payload. It validates the HTTP method, event type, and HMAC signature (if a secret is configured). The events parameter specifies which event types or aggregates are allowed to be parsed. You can pass specific Event types (e.g., PullRequestCreateEvent) or EventAggregate types (e.g., PullRequestAggregate) to match multiple events at once. Returns the parsed payload as an interface{} that can be type-asserted to the specific payload type, or an error if validation or parsing fails.

type WebhookOption

type WebhookOption func(*Webhook) error

WebhookOption is a functional option for configuring a Webhook.

type WebhookOptions

type WebhookOptions struct{}

WebhookOptions provides methods for creating webhook configuration options.

func (WebhookOptions) Secret

func (WebhookOptions) Secret(secret string) WebhookOption

Secret returns an Option that sets the webhook secret for HMAC signature verification. Multiple secrets can be provided as a comma-separated string to support secret rotation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL