README

go-circleci

GoDoc Circle CI Go Report Card coverage

Go library for interacting with CircleCI's API. Supports all current API endpoints allowing you do do things like:

  • Query for recent builds
  • Get build details
  • Retry builds
  • Manipulate checkout keys, environment variables, and other settings for a project

The CircleCI HTTP API response schemas are not well documented so please file an issue if you run into something that doesn't match up.

Example usage:

package main

import (
        "fmt"

        "github.com/jszwedko/go-circleci"
)

func main() {
        client := &circleci.Client{Token: "YOUR TOKEN"} // Token not required to query info for public projects

        builds, _ := client.ListRecentBuildsForProject("jszwedko", "circleci-cli", "master", "", -1, 0)

        for _, build := range builds {
                fmt.Printf("%d: %s\n", build.BuildNum, build.Status)
        }
}

For the CLI that uses this library (or to see more example usages), please see circleci-cli.

See GoDoc for API usage.

Feature requests and issues welcome!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	HTTPStatusCode int
	Message        string
}

APIError represents an error from CircleCI

func (*APIError) Error

func (e *APIError) Error() string

type AWSConfig

type AWSConfig struct {
	AWSKeypair *AWSKeypair `json:"keypair"`
}

AWSConfig represents AWS configuration for a project

type AWSKeypair

type AWSKeypair struct {
	AccessKeyID     string `json:"access_key_id"`
	SecretAccessKey string `json:"secret_access_key_id"`
}

AWSKeypair represents the AWS access/secret key for a project SecretAccessKey will be a masked value

type Action

type Action struct {
	Background         bool       `json:"background"`
	BashCommand        *string    `json:"bash_command"`
	Canceled           *bool      `json:"canceled"`
	Continue           *string    `json:"continue"`
	EndTime            *time.Time `json:"end_time"`
	ExitCode           *int       `json:"exit_code"`
	Failed             *bool      `json:"failed"`
	HasOutput          bool       `json:"has_output"`
	Index              int        `json:"index"`
	InfrastructureFail *bool      `json:"infrastructure_fail"`
	Messages           []string   `json:"messages"`
	Name               string     `json:"name"`
	OutputURL          string     `json:"output_url"`
	Parallel           bool       `json:"parallel"`
	RunTimeMillis      int        `json:"run_time_millis"`
	StartTime          *time.Time `json:"start_time"`
	Status             string     `json:"status"`
	Step               int        `json:"step"`
	Timedout           *bool      `json:"timedout"`
	Truncated          bool       `json:"truncated"`
	Type               string     `json:"type"`
}

Action represents an individual action within a build step

type Artifact

type Artifact struct {
	NodeIndex  int    `json:"node_index"`
	Path       string `json:"path"`
	PrettyPath string `json:"pretty_path"`
	URL        string `json:"url"`
}

Artifact represents a build artifact

type Branch

type Branch struct {
	LastSuccess   *BuildSummary   `json:"last_success"`
	PusherLogins  []string        `json:"pusher_logins"`
	RecentBuilds  []*BuildSummary `json:"recent_builds"`
	RunningBuilds []*BuildSummary `json:"running_builds"`
}

Branch represents a repository branch

type Build

type Build struct {
	AllCommitDetails        []*CommitDetails  `json:"all_commit_details"`
	AuthorDate              *time.Time        `json:"author_date"`
	AuthorEmail             string            `json:"author_email"`
	AuthorName              string            `json:"author_name"`
	Body                    string            `json:"body"`
	Branch                  string            `json:"branch"`
	BuildNum                int               `json:"build_num"`
	BuildParameters         map[string]string `json:"build_parameters"`
	BuildTimeMillis         *int              `json:"build_time_millis"`
	BuildURL                string            `json:"build_url"`
	Canceled                bool              `json:"canceled"`
	CircleYML               *CircleYML        `json:"circle_yml"`
	CommitterDate           *time.Time        `json:"committer_date"`
	CommitterEmail          string            `json:"committer_email"`
	CommitterName           string            `json:"committer_name"`
	Compare                 *string           `json:"compare"`
	DontBuild               *string           `json:"dont_build"`
	Failed                  *bool             `json:"failed"`
	FeatureFlags            map[string]string `json:"feature_flags"`
	InfrastructureFail      bool              `json:"infrastructure_fail"`
	IsFirstGreenBuild       bool              `json:"is_first_green_build"`
	JobName                 *string           `json:"job_name"`
	Lifecycle               string            `json:"lifecycle"`
	Messages                []*Message        `json:"messages"`
	Node                    []*Node           `json:"node"`
	OSS                     bool              `json:"oss"`
	Outcome                 string            `json:"outcome"`
	Parallel                int               `json:"parallel"`
	Picard                  *Picard           `json:"picard"`
	Platform                string            `json:"platform"`
	Previous                *BuildStatus      `json:"previous"`
	PreviousSuccessfulBuild *BuildStatus      `json:"previous_successful_build"`
	PullRequests            []*PullRequest    `json:"pull_requests"`
	QueuedAt                string            `json:"queued_at"`
	Reponame                string            `json:"reponame"`
	Retries                 []int             `json:"retries"`
	RetryOf                 *int              `json:"retry_of"`
	SSHEnabled              *bool             `json:"ssh_enabled"`
	SSHUsers                []*SSHUser        `json:"ssh_users"`
	StartTime               *time.Time        `json:"start_time"`
	Status                  string            `json:"status"`
	Steps                   []*Step           `json:"steps"`
	StopTime                *time.Time        `json:"stop_time"`
	Subject                 string            `json:"subject"`
	Timedout                bool              `json:"timedout"`
	UsageQueuedAt           string            `json:"usage_queued_at"`
	User                    *BuildUser        `json:"user"`
	Username                string            `json:"username"`
	VcsRevision             string            `json:"vcs_revision"`
	VcsTag                  string            `json:"vcs_tag"`
	VCSURL                  string            `json:"vcs_url"`
	Workflows               *Workflow         `json:"workflows"`
	Why                     string            `json:"why"`
}

Build represents the details of a build

type BuildAgent

type BuildAgent struct {
	Image      *string               `json:"image"`
	Properties *BuildAgentProperties `json:"properties"`
}

BuildAgent represents an agent's information

type BuildAgentProperties

type BuildAgentProperties struct {
	BuildAgent string `json:"image"`
	Executor   string `json:"executor"`
}

BuildAgentProperties represents agent properties

type BuildStatus

type BuildStatus struct {
	BuildTimeMillis int    `json:"build_time_millis"`
	Status          string `json:"status"`
	BuildNum        int    `json:"build_num"`
}

BuildStatus represents status information about the build Used when a short summary of previous builds is included

type BuildSummary

type BuildSummary struct {
	AddedAt     time.Time `json:"added_at"`
	BuildNum    int       `json:"build_num"`
	Outcome     string    `json:"outcome"`
	PushedAt    time.Time `json:"pushed_at"`
	Status      string    `json:"status"`
	VCSRevision string    `json:"vcs_revision"`
}

BuildSummary represents the subset of build information returned with a Project

type BuildUser

type BuildUser struct {
	Email  *string `json:"email"`
	IsUser bool    `json:"is_user"`
	Login  string  `json:"login"`
	Name   *string `json:"name"`
}

BuildUser represents the user that triggered the build

type CheckoutKey

type CheckoutKey struct {
	PublicKey   string    `json:"public_key"`
	Type        string    `json:"type"` // github-user-key or deploy-key
	Fingerprint string    `json:"fingerprint"`
	Login       *string   `json:"login"` // github username if this is a user key
	Preferred   bool      `json:"preferred"`
	Time        time.Time `json:"time"` // time key was created
}

CheckoutKey represents an SSH checkout key for a project

type CircleYML

type CircleYML struct {
	String string `json:"string"`
}

CircleYML represents the serialized CircleCI YML file for a given build

type Client

type Client struct {
	BaseURL    *url.URL     // CircleCI API endpoint (defaults to DefaultEndpoint)
	Token      string       // CircleCI API token (needed for private repositories and mutative actions)
	HTTPClient *http.Client // HTTPClient to use for connecting to CircleCI (defaults to http.DefaultClient)

	Debug  bool   // debug logging enabled
	Logger Logger // logger to send debug messages on (if enabled), defaults to logging to stderr with the standard flags
}

Client is a CircleCI client Its zero value is a usable client for examining public CircleCI repositories

func (*Client) AddEnvVar

func (c *Client) AddEnvVar(account, repo, name, value string) (*EnvVar, error)

AddEnvVar adds a new environment variable to the specified project Returns the added env var (the value will be masked)

func (*Client) AddHerokuKey

func (c *Client) AddHerokuKey(key string) error

AddHerokuKey associates a Heroku key with the user's API token to allow CircleCI to deploy to Heroku on your behalf

The API token being used must be a user API token

NOTE: It doesn't look like there is currently a way to dissaccociate your Heroku key, so use with care

func (*Client) AddSSHKey

func (c *Client) AddSSHKey(account, repo, hostname, privateKey string) error

AddSSHKey adds a new SSH key to the project

func (*Client) AddSSHUser

func (c *Client) AddSSHUser(account, repo string, buildNum int) (*Build, error)

AddSSHUser adds the user associated with the API token to the list of valid SSH users for a build.

The API token being used must be a user API token

func (*Client) Build

func (c *Client) Build(account, repo, branch string) (*Build, error)

Build triggers a new build for the given project for the given project on the given branch. Returns the new build information

func (*Client) BuildOpts

func (c *Client) BuildOpts(account, repo, branch string, opts map[string]interface{}) (*Build, error)

BuildOpts triggeres a new build for the givent project on the given branch, Marshaling the struct into json and passing in the post body. Returns the new build information

func (*Client) CancelBuild

func (c *Client) CancelBuild(account, repo string, buildNum int) (*Build, error)

CancelBuild triggers a cancel of the specified build Returns the new build information

func (*Client) ClearCache

func (c *Client) ClearCache(account, repo string) (string, error)

ClearCache clears the cache of the specified project Returns the status returned by CircleCI

func (*Client) CreateCheckoutKey

func (c *Client) CreateCheckoutKey(account, repo, keyType string) (*CheckoutKey, error)

CreateCheckoutKey creates a new checkout key for a project Valid key types are currently deploy-key and github-user-key

The github-user-key type requires that the API token being used be a user API token

func (*Client) DeleteCheckoutKey

func (c *Client) DeleteCheckoutKey(account, repo, fingerprint string) error

DeleteCheckoutKey fetches the checkout key for the given project by fingerprint

func (*Client) DeleteEnvVar

func (c *Client) DeleteEnvVar(account, repo, name string) error

DeleteEnvVar deletes the specified environment variable from the project

func (*Client) DisableProject

func (c *Client) DisableProject(account, repo string) error

DisableProject disables a project

func (*Client) EnableProject

func (c *Client) EnableProject(account, repo string) error

EnableProject enables a project - generates a deploy SSH key used to checkout the Github repo. The Github user tied to the Circle API Token must have "admin" access to the repo.

func (*Client) FollowProject

func (c *Client) FollowProject(account, repo string) (*Project, error)

FollowProject follows a project

func (*Client) GetActionOutputs

func (c *Client) GetActionOutputs(a *Action) ([]*Output, error)

GetActionOutputs fetches the output for the given action If the action has no output, returns nil

func (*Client) GetBuild

func (c *Client) GetBuild(account, repo string, buildNum int) (*Build, error)

GetBuild fetches a given build by number

func (*Client) GetCheckoutKey

func (c *Client) GetCheckoutKey(account, repo, fingerprint string) (*CheckoutKey, error)

GetCheckoutKey fetches the checkout key for the given project by fingerprint

func (*Client) GetProject

func (c *Client) GetProject(account, repo string) (*Project, error)

GetProject retrieves a specific project Returns nil of the project is not in the list of watched projects

func (*Client) ListBuildArtifacts

func (c *Client) ListBuildArtifacts(account, repo string, buildNum int) ([]*Artifact, error)

ListBuildArtifacts fetches the build artifacts for the given build

func (*Client) ListCheckoutKeys

func (c *Client) ListCheckoutKeys(account, repo string) ([]*CheckoutKey, error)

ListCheckoutKeys fetches the checkout keys associated with the given project

func (*Client) ListEnvVars

func (c *Client) ListEnvVars(account, repo string) ([]EnvVar, error)

ListEnvVars list environment variable to the specified project Returns the env vars (the value will be masked)

func (*Client) ListProjects

func (c *Client) ListProjects() ([]*Project, error)

ListProjects returns the list of projects the user is watching

func (*Client) ListRecentBuilds

func (c *Client) ListRecentBuilds(limit, offset int) ([]*Build, error)

ListRecentBuilds fetches the list of recent builds for all repositories the user is watching If limit is -1, fetches all builds

func (*Client) ListRecentBuildsForProject

func (c *Client) ListRecentBuildsForProject(account, repo, branch, status string, limit, offset int) ([]*Build, error)

ListRecentBuildsForProject fetches the list of recent builds for the given repository The status and branch parameters are used to further filter results if non-empty If limit is -1, fetches all builds

func (*Client) ListTestMetadata

func (c *Client) ListTestMetadata(account, repo string, buildNum int) ([]*TestMetadata, error)

ListTestMetadata fetches the build metadata for the given build

func (*Client) Me

func (c *Client) Me() (*User, error)

Me returns information about the current user

func (*Client) ParameterizedBuild

func (c *Client) ParameterizedBuild(account, repo, branch string, buildParameters map[string]string) (*Build, error)

ParameterizedBuild triggers a new parameterized build for the given project on the given branch, Marshaling the struct into json and passing in the post body. Returns the new build information

func (*Client) RetryBuild

func (c *Client) RetryBuild(account, repo string, buildNum int) (*Build, error)

RetryBuild triggers a retry of the specified build Returns the new build information

type CommitDetails

type CommitDetails struct {
	AuthorDate     *time.Time `json:"author_date"`
	AuthorEmail    string     `json:"author_email"`
	AuthorLogin    string     `json:"author_login"`
	AuthorName     string     `json:"author_name"`
	Body           string     `json:"body"`
	Branch         string     `json:"branch"`
	Commit         string     `json:"commit"`
	CommitURL      string     `json:"commit_url"`
	CommitterDate  *time.Time `json:"committer_date"`
	CommitterEmail string     `json:"committer_email"`
	CommitterLogin string     `json:"committer_login"`
	CommitterName  string     `json:"committer_name"`
	Subject        string     `json:"subject"`
}

CommitDetails represents information about a commit returned with other structs

type EnvVar

type EnvVar struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

EnvVar represents an environment variable

type FeatureFlags

type FeatureFlags struct {
	TrustyBeta             bool    `json:"trusty-beta"`
	OSX                    bool    `json:"osx"`
	SetGithubStatus        bool    `json:"set-github-status"`
	BuildPRsOnly           bool    `json:"build-prs-only"`
	ForksReceiveSecretVars bool    `json:"forks-receive-secret-env-vars"`
	Fleet                  *string `json:"fleet"`
	BuildForkPRs           bool    `json:"build-fork-prs"`
	AutocancelBuilds       bool    `json:"autocancel-builds"`
	OSS                    bool    `json:"oss"`
	MemoryLimit            *string `json:"memory-limit"`
	// contains filtered or unexported fields
}

func (*FeatureFlags) Raw

func (f *FeatureFlags) Raw() map[string]interface{}

Raw returns the underlying map[string]interface{} representing the feature flags This is useful to access flags that have been added to the API, but not yet added to this library

func (*FeatureFlags) UnmarshalJSON

func (f *FeatureFlags) UnmarshalJSON(b []byte) error

type Logger

type Logger interface {
	Printf(fmt string, args ...interface{})
}

Logger is a minimal interface for injecting custom logging logic for debug logs

type Message

type Message struct {
	Message string `json:"message"`
	Type    string `json:"type"`
}

Message represents build messages

type Node

type Node struct {
	ImageID      string `json:"image_id"`
	Port         int    `json:"port"`
	PublicIPAddr string `json:"public_ip_addr"`
	SSHEnabled   *bool  `json:"ssh_enabled"`
	Username     string `json:"username"`
}

Node represents the node a build was run on

type Output

type Output struct {
	Type    string    `json:"type"`
	Time    time.Time `json:"time"`
	Message string    `json:"message"`
}

Output represents the output of a given action

type Picard

type Picard struct {
	BuildAgent    *BuildAgent    `json:"build_agent"`
	ResourceClass *ResourceClass `json:"resource_class"`
	Executor      string         `json:"executor"`
}

Picard represents metadata about an execution environment

type Project

type Project struct {
	AWSConfig           AWSConfig         `json:"aws"`
	Branches            map[string]Branch `json:"branches"`
	CampfireNotifyPrefs *string           `json:"campfire_notify_prefs"`
	CampfireRoom        *string           `json:"campfire_room"`
	CampfireSubdomain   *string           `json:"campfire_subdomain"`
	CampfireToken       *string           `json:"campfire_token"`
	Compile             string            `json:"compile"`
	DefaultBranch       string            `json:"default_branch"`
	Dependencies        string            `json:"dependencies"`
	Extra               string            `json:"extra"`
	FeatureFlags        FeatureFlags      `json:"feature_flags"`
	FlowdockAPIToken    *string           `json:"flowdock_api_token"`
	Followed            bool              `json:"followed"`
	HallNotifyPrefs     *string           `json:"hall_notify_prefs"`
	HallRoomAPIToken    *string           `json:"hall_room_api_token"`
	HasUsableKey        bool              `json:"has_usable_key"`
	HerokuDeployUser    *string           `json:"heroku_deploy_user"`
	HipchatAPIToken     *string           `json:"hipchat_api_token"`
	HipchatNotify       *bool             `json:"hipchat_notify"`
	HipchatNotifyPrefs  *string           `json:"hipchat_notify_prefs"`
	HipchatRoom         *string           `json:"hipchat_room"`
	IrcChannel          *string           `json:"irc_channel"`
	IrcKeyword          *string           `json:"irc_keyword"`
	IrcNotifyPrefs      *string           `json:"irc_notify_prefs"`
	IrcPassword         *string           `json:"irc_password"`
	IrcServer           *string           `json:"irc_server"`
	IrcUsername         *string           `json:"irc_username"`
	Parallel            int               `json:"parallel"`
	Reponame            string            `json:"reponame"`
	Setup               string            `json:"setup"`
	SlackAPIToken       *string           `json:"slack_api_token"`
	SlackChannel        *string           `json:"slack_channel"`
	SlackNotifyPrefs    *string           `json:"slack_notify_prefs"`
	SlackSubdomain      *string           `json:"slack_subdomain"`
	SlackWebhookURL     *string           `json:"slack_webhook_url"`
	SSHKeys             []*PublicSSHKey   `json:"ssh_keys"`
	Test                string            `json:"test"`
	Username            string            `json:"username"`
	VCSURL              string            `json:"vcs_url"`
}

Project represents information about a project

type PublicSSHKey

type PublicSSHKey struct {
	Hostname    string `json:"hostname"`
	PublicKey   string `json:"public_key"`
	Fingerprint string `json:"fingerprint"`
}

PublicSSHKey represents the public part of an SSH key associated with a project PrivateKey will be a masked value

type PullRequest

type PullRequest struct {
	HeadSha string `json:"head_sha"`
	URL     string `json:"url"`
}

PullRequest represents a pull request

type ResourceClass

type ResourceClass struct {
	CPU   float64 `json:"cpu"`
	RAM   int     `json:"ram"`
	Class string  `json:"class"`
}

ResourceClass represents usable resource information for a job

type SSHUser

type SSHUser struct {
	GithubID int    `json:"github_id"`
	Login    string `json:"login"`
}

SSHUser represents a user associated with an build with SSH enabled

type Step

type Step struct {
	Name    string    `json:"name"`
	Actions []*Action `json:"actions"`
}

Step represents an individual step in a build Will contain more than one action if the step was parallelized

type TestMetadata

type TestMetadata struct {
	Classname  string  `json:"classname"`
	File       string  `json:"file"`
	Message    *string `json:"message"`
	Name       string  `json:"name"`
	Result     string  `json:"result"`
	RunTime    float64 `json:"run_time"`
	Source     string  `json:"source"`
	SourceType string  `json:"source_type"`
}

TestMetadata represents metadata collected from the test run (e.g. JUnit output)

type User

type User struct {
	Admin               bool                    `json:"admin"`
	AllEmails           []string                `json:"all_emails"`
	AvatarURL           string                  `json:"avatar_url"`
	BasicEmailPrefs     string                  `json:"basic_email_prefs"`
	Containers          int                     `json:"containers"`
	CreatedAt           time.Time               `json:"created_at"`
	DaysLeftInTrial     int                     `json:"days_left_in_trial"`
	GithubID            int                     `json:"github_id"`
	GithubOauthScopes   []string                `json:"github_oauth_scopes"`
	GravatarID          *string                 `json:"gravatar_id"`
	HerokuAPIKey        *string                 `json:"heroku_api_key"`
	LastViewedChangelog time.Time               `json:"last_viewed_changelog"`
	Login               string                  `json:"login"`
	Name                *string                 `json:"name"`
	Parallelism         int                     `json:"parallelism"`
	Plan                *string                 `json:"plan"`
	Projects            map[string]*UserProject `json:"projects"`
	SelectedEmail       *string                 `json:"selected_email"`
	SignInCount         int                     `json:"sign_in_count"`
	TrialEnd            time.Time               `json:"trial_end"`
}

User represents a CircleCI user

type UserProject

type UserProject struct {
	Emails      string `json:"emails"`
	OnDashboard bool   `json:"on_dashboard"`
}

UserProject returns the selective project information included when querying for a User

type Workflow

type Workflow struct {
	JobName        string    `json:"job_name"`
	JobId          string    `json:"job_id"`
	UpstreamJobIds []*string `json:"upstream_job_ids"`
	WorkflowId     string    `json:"workflow_id"`
	WorkspaceId    string    `json:"workspace_id"`
	WorkflowName   string    `json:"workflow_name"`
}

Workflow represents the details of the workflow for a build

Source Files