circleci

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2020 License: MIT Imports: 12 Imported by: 0

README

go-circleci

License

This is a Go client of CircleCI API v2.

This API is implemented by following the public docs by CircleCI.

Install

$ go get github.com/ttyfky/go-circleci

Use

import "github.com/bold-commerce/go-shopify"
Authentication

CircleCI supports two types of authentication 1. api_key_header and 2. basic_auth.

This Client currently supports api_key_header authentication.

Get API token

Get API token by following instruction before using this client.

Create Client

Give API token to NewClient function.

token := "API_TOKEN"
client := circleci.NewClient(token)
API call

Use resource service in the client to call API of each resources in CircleCI.

client := circleci.NewClient(token)
workflowID := "ID"
workflow, _ := client.Workflow.Get(workflowID)

More examples are availablein example_test.go.

API availability

Not all of the APIs are implemented yet. It's more based on demand of the actions. The table below shows the API's availability as of Jan 2021.

Preview means it's preview phase in CircleCI side.

API Availability
Context (Preview) Available
Insights Not Implemented
User (Preview) Not Implemented
Pipeline Not Implemented
Job (Preview) Available
Workflow Available
Project Partially Available

Note: Environment variable handling is part of Project API, but extracted as ProjectEnvVar it for convenience.

Documentation

Index

Examples

Constants

View Source
const (
	UserAgent = "gocircleci/1.0.0"
)

Variables

This section is empty.

Functions

func ProjectSlug

func ProjectSlug(projectType, org, repo string) string

ProjectSlug assemle ProjectSlug of CircleCI. projectType: bitbucket, github(gh) org: organization name or user nme repo: repository name

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 Artifact

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

Artifact represents artifact of a Job.

type ArtifactList

type ArtifactList struct {
	Items         []Artifact `json:"items,omitempty"`
	NextPageToken string     `json:"next_page_token,omitempty"`
}

ArtifactList represents list of Artifact in a Job.

type Client

type Client struct {
	// CircleCI API endpoint (defaults to DefaultEndpoint)
	BaseURL *url.URL

	// HTTPClient to use for connecting to CircleCI (defaults to http.DefaultClient)
	HTTPClient *http.Client

	Project  ProjectService
	EnvVar   ProjectEnvVarService
	Workflow WorkflowService
	Job      JobService
	Context  ContextService
	// contains filtered or unexported fields
}

Client is a CircleCI client.

func NewClient

func NewClient(token string, opts ...Option) *Client

NewClient creates new CircleCI client with given API token. Optionally HTTP client or some other fields can be also given.

func (*Client) CreateAndDo

func (c *Client) CreateAndDo(method, relPath string, data, options, resource interface{}) error

CreateAndDo performs a web request to CircleCI with the given method (GET, POST, PUT, DELETE) and relative path. If the data argument is non-nil, it will be used as the body of the request for POST and PUT requests. The options argument is used for specifying request options. Any data returned from CircleCI will be marshalled into resource argument.

func (*Client) Delete

func (c *Client) Delete(path string) error

Delete performs a DELETE request for the given path

func (*Client) Get

func (c *Client) Get(path string, resource, options interface{}) error

Get performs a GET request for the given path and saves the result in the given resource.

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, body, opts interface{}) (req *http.Request, err error)

NewRequest creates a new http.Request with given parameters.

func (*Client) Post

func (c *Client) Post(path string, data, resource interface{}) error

Post performs a POST request for the given path and saves the result in the given resource.

func (*Client) Put

func (c *Client) Put(path string, data, resource interface{}) error

Put performs a PUT request for the given path and saves the result in the given resource.

type Context

type Context struct {
	ID        string    `json:"id,omitempty"`
	Name      string    `json:"name,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
}

Context represents information about a context in CircleCI.

type ContextCreate

type ContextCreate struct {
	Name   string `json:"name,omitempty"`
	*Owner `json:"owner,omitempty"`
}

ContextCreate represents payload to create Context.

type ContextEnvVar

type ContextEnvVar struct {
	Variable  string    `json:"variable,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	ContextID string    `json:"context_id,omitempty"`
}

ContextEnvVar represents information about an environment variable of Context.

type ContextEnvVarList

type ContextEnvVarList struct {
	NextPageToken string           `json:"next_page_token,omitempty"`
	Items         []*ContextEnvVar `json:"items,omitempty"`
}

ContextEnvVarList represents a list of ContextEnvVar.

type ContextList

type ContextList struct {
	NextPageToken string     `json:"next_page_token,omitempty"`
	Items         []*Context `json:"items,omitempty"`
}

ContextList represents a list of Context variables.

type ContextOp

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

ContextOp handles communication with the project related methods in the CircleCI API v2.

func (*ContextOp) Create

func (ps *ContextOp) Create(projectSlug, name string) (*Context, error)

Create adds a new environment variable or update existing variable on the specified project. Returns the added env var (the value will be masked).

Example
token := os.Getenv("CIRCLECI_TOKEN")
client := circleci.NewClient(token)

id := "context_id"

envVarName := "test_key"
envVar, err := client.Context.UpsertEnvVar(id, envVarName, "test_value")
println("Created env Var")
printPretty(envVar)
contextList, err := client.Context.ListEnvVar(id)
if err != nil {
	log.Fatal(err)
}
printPretty(contextList)
err = client.Context.RemoveEnvVar(id, envVarName)
if err != nil {
	log.Fatal(err)
}
println("Deleted env var")
contextList, err = client.Context.ListEnvVar(id)
if err != nil {
	log.Fatal(err)
}
printPretty(contextList)
Output:

func (*ContextOp) Delete

func (ps *ContextOp) Delete(id string) error

Delete deletes the specified environment variable from the project.

func (*ContextOp) Get

func (ps *ContextOp) Get(id string) (*Context, error)

Get gets environment variable. Returns the env vars (the value will be masked).

Example
token := os.Getenv("CIRCLECI_TOKEN")
client := circleci.NewClient(token)

id := "context_id"
contextList, err := client.Context.Get(id)
if err != nil {
	log.Fatal(err)
}
printPretty(contextList)
Output:

func (*ContextOp) List

func (ps *ContextOp) List(slug string) (*ContextList, error)

List list contexts for an owner. owner-slug is expected but not owner-id.

func (*ContextOp) ListEnvVar

func (ps *ContextOp) ListEnvVar(id string) (*ContextEnvVarList, error)

ListEnvVar list contexts for an owner. Returns the env vars (the value will be masked).

func (*ContextOp) RemoveEnvVar

func (ps *ContextOp) RemoveEnvVar(id, envVarName string) error

RemoveEnvVar list contexts for an owner. Returns the env vars (the value will be masked).

func (*ContextOp) UpsertEnvVar

func (ps *ContextOp) UpsertEnvVar(id, envVarName, envVarValue string) (*ContextEnvVar, error)

UpsertEnvVar list contexts for an owner. Returns the env vars (the value will be masked).

type ContextService

type ContextService interface {
	List(slug string) (*ContextList, error)
	Create(projectSlug, name string) (*Context, error)
	Delete(id string) error
	Get(id string) (*Context, error)
	ListEnvVar(id string) (*ContextEnvVarList, error)
	UpsertEnvVar(id, envVarName, envVarValue string) (*ContextEnvVar, error)
	RemoveEnvVar(id, envVarName string) error
}

ContextService is an interface for Context in Project API.

type Job

type Job struct {
	WebURL       string `json:"web_url,omitempty"`
	Project      `json:"project,omitempty"`
	ParallelRuns []struct {
		Index  int    `json:"index,omitempty"`
		Status string `json:"status,omitempty"`
	} `json:"parallel_runs,omitempty"`
	StartedAt      time.Time `json:"started_at,omitempty"`
	LatestWorkflow struct {
		ID   string `json:"id,omitempty"`
		Name string `json:"name,omitempty"`
	} `json:"latest_workflow,omitempty"`
	Name     string `json:"name,omitempty"`
	Executor struct {
		Type          string `json:"type,omitempty"`
		ResourceClass string `json:"resource_class,omitempty"`
	} `json:"executor,omitempty"`
	Parallelism  int         `json:"parallelism,omitempty"`
	Status       interface{} `json:"status,omitempty"`
	Number       int         `json:"number,omitempty"`
	Pipeline     Pipeline    `json:"pipeline,omitempty"`
	Duration     int         `json:"duration,omitempty"`
	CreatedAt    time.Time   `json:"created_at,omitempty"`
	Messages     []Message   `json:"messages,omitempty"`
	Contexts     []Context   `json:"contexts,omitempty"`
	Organization struct {
		Name string `json:"name,omitempty"`
	} `json:"organization,omitempty"`
	QueuedAt  time.Time `json:"queued_at,omitempty"`
	StoppedAt time.Time `json:"stopped_at,omitempty"`
}

Job represents information about job in CircleCI.

type JobOp

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

JobOp handles communication with the project related methods in the CircleCI API v2.

func (*JobOp) Cancel

func (ps *JobOp) Cancel(id, projectSlug string) (*Message, error)

Cancel cancels a given job.

func (*JobOp) Get

func (ps *JobOp) Get(id, projectSlug string) (*Job, error)

Get gets job detail.

func (*JobOp) GetArtifacts

func (ps *JobOp) GetArtifacts(id, projectSlug string) (*ArtifactList, error)

GetArtifacts get artifacts in a job.

func (*JobOp) GetTestMetadata

func (ps *JobOp) GetTestMetadata(id, projectSlug string) (*TestMetadataList, error)

GetTestMetadata gets metadata of test in a job.

type JobService

type JobService interface {
	Get(id, projectSlug string) (*Job, error)
	Cancel(id, projectSlug string) (*Message, error)
	GetArtifacts(id, projectSlug string) (*ArtifactList, error)
	GetTestMetadata(id, projectSlug string) (*TestMetadataList, error)
}

type Jobs

type Jobs struct {
	Items []struct {
		CanceledBy        string      `json:"canceled_by,omitempty"`
		Dependencies      []string    `json:"dependencies,omitempty"`
		JobNumber         int         `json:"job_number,omitempty"`
		ID                string      `json:"id,omitempty"`
		StartedAt         time.Time   `json:"started_at,omitempty"`
		Name              string      `json:"name,omitempty"`
		ApprovedBy        string      `json:"approved_by,omitempty"`
		ProjectSlug       string      `json:"project_slug,omitempty"`
		Status            interface{} `json:"status,omitempty"`
		Type              string      `json:"type,omitempty"`
		StoppedAt         time.Time   `json:"stopped_at,omitempty"`
		ApprovalRequestID string      `json:"approval_request_id,omitempty"`
	} `json:"items,omitempty"`
	NextPageToken string `json:"next_page_token,omitempty"`
}

Jobs represents information about a jobs having dependencies.

type Message

type Message struct {
	Type    string `json:"type,omitempty"`
	Message string `json:"message,omitempty"`
	Reason  string `json:"reason,omitempty"`
}

Message represents messages.

type Metadata

type Metadata struct {
	Message   string `json:"message,omitempty"`
	Source    string `json:"source,omitempty"`
	RunTime   string `json:"run_time,omitempty"`
	File      string `json:"file,omitempty"`
	Result    string `json:"result,omitempty"`
	Name      string `json:"name,omitempty"`
	Classname string `json:"classname,omitempty"`
}

Metadata represents information about a test metadata of a Job.

type Option

type Option func(c *Client)

Option is used to configure client with options

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient optionally sets the http.Client. This can be used when would like to customize HTTP option.

func WithPathPrefix

func WithPathPrefix(path string) Option

WithPathPrefix optionally sets the API Prefix. This can be used when would like to mock or use different prefix.

type Owner

type Owner struct {
	Slug string `json:"slug,omitempty"`
	Type string `json:"type,omitempty"`
}

Owner represents Owner used in ContextCreate.

type Pipeline

type Pipeline struct {
	ID     string `json:"id,omitempty"`
	Errors []struct {
		Type    string `json:"type,omitempty"`
		Message string `json:"message,omitempty"`
	} `json:"errors,omitempty"`
	ProjectSlug string    `json:"project_slug,omitempty"`
	UpdatedAt   time.Time `json:"updated_at,omitempty"`
	Number      int       `json:"number,omitempty"`
	State       string    `json:"state,omitempty"`
	CreatedAt   time.Time `json:"created_at,omitempty"`
	Trigger     struct {
		Type       string    `json:"type,omitempty"`
		ReceivedAt time.Time `json:"received_at,omitempty"`
		Actor      struct {
			Login     string `json:"login,omitempty"`
			AvatarURL string `json:"avatar_url,omitempty"`
		} `json:"actor,omitempty"`
	} `json:"trigger,omitempty"`
	Vcs struct {
		ProviderName        string `json:"provider_name,omitempty"`
		TargetRepositoryURL string `json:"target_repository_url,omitempty"`
		Branch              string `json:"branch,omitempty"`
		ReviewID            string `json:"review_id,omitempty"`
		ReviewURL           string `json:"review_url,omitempty"`
		Revision            string `json:"revision,omitempty"`
		Tag                 string `json:"tag,omitempty"`
		Commit              struct {
			Subject string `json:"subject,omitempty"`
			Body    string `json:"body"`
		} `json:"commit"`
		OriginRepositoryURL string `json:"origin_repository_url"`
	} `json:"vcs"`
}

Pipeline represents pipeline in CircleCI.

type Project

type Project struct {
	Slug             string `json:"slug,omitempty"`
	Name             string `json:"name,omitempty"`
	OrganizationName string `json:"organization_name,omitempty"`
	ExternalURL      string `json:"external_url,omitempty"`
	VcsInfo          struct {
		VcsURL        string `json:"vcs_url,omitempty"`
		Provider      string `json:"provider,omitempty"`
		DefaultBranch string `json:"default_branch,omitempty"`
	} `json:"vcs_info,omitempty"`
}

Project represents information about a project in CircleCI.

type ProjectEnvVar

type ProjectEnvVar struct {
	Name  string `json:"name,omitempty"`
	Value string `json:"value,omitempty"`
}

ProjectEnvVar represents an environment variable in a Project.

type ProjectEnvVarList

type ProjectEnvVarList struct {
	NextPageToken string           `json:"next_page_token,omitempty"`
	Items         []*ProjectEnvVar `json:"items,omitempty"`
}

ProjectEnvVar represents a list of ProjectEnvVar.

type ProjectEnvVarOp

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

ProjectEnvVarOp handles communication with the project related methods in the CircleCI API v2.

func (*ProjectEnvVarOp) Create

func (ps *ProjectEnvVarOp) Create(projectSlug, name, value string) (*ProjectEnvVar, error)

Create adds a new environment variable or update existing variable on the specified project. Returns the added env var (the value will be masked).

func (*ProjectEnvVarOp) Delete

func (ps *ProjectEnvVarOp) Delete(projectSlug, name string) error

Delete deletes the specified environment variable from the project.

func (*ProjectEnvVarOp) Get

func (ps *ProjectEnvVarOp) Get(projectSlug, name string) (*ProjectEnvVar, error)

Get gets environment variable. Returns the env vars (the value will be masked).

func (*ProjectEnvVarOp) List

func (ps *ProjectEnvVarOp) List(projectSlug string) (*ProjectEnvVarList, error)

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

Example
token := os.Getenv("CIRCLECI_TOKEN")
client := circleci.NewClient(token)

envVarList, err := client.EnvVar.List(projectSlug())
if err != nil {
	log.Fatal(err)
}
printPretty(envVarList)
Output:

type ProjectEnvVarService

type ProjectEnvVarService interface {
	Create(projectSlug, name, value string) (*ProjectEnvVar, error)
	Get(projectSlug, name string) (*ProjectEnvVar, error)
	List(projectSlug string) (*ProjectEnvVarList, error)
	Delete(projectSlug, name string) error
}

ProjectEnvVarService is an interface for ProjectEnvVar in Project API.

type ProjectService

type ProjectService interface {
	Get(projectSlug string) (*Project, error)
}

ProjectService is an interface for Project API.

type ProjectServiceOp

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

ProjectServiceOp handles communication with the project related methods in the CircleCI API v2.

func (*ProjectServiceOp) Get

func (ps *ProjectServiceOp) Get(projectSlug string) (*Project, error)

Get gets project information.

Example
token := os.Getenv("CIRCLECI_TOKEN")
client := circleci.NewClient(token)

project, err := client.Project.Get(projectSlug())
if err != nil {
	log.Fatal(err)
}
printPretty(project)
Output:

type RerunJob

type RerunJob struct {
	Jobs       []string `json:"jobs,omitempty"`
	FromFailed bool     `json:"from_failed,omitempty"`
}

RerunJob is a payload to send when rerunning jobs in Workflow. Multiple job ids can be given in Jobs.

type TestMetadataList

type TestMetadataList struct {
	Items         []Metadata `json:"items,omitempty"`
	NextPageToken string     `json:"next_page_token,omitempty"`
}

TestMetadataList contains list of Metadata of test.

type Workflow

type Workflow struct {
	PipelineID     string    `json:"pipeline_id,omitempty"`
	CanceledBy     string    `json:"canceled_by,omitempty"`
	ID             string    `json:"id,omitempty"`
	Name           string    `json:"name,omitempty"`
	ProjectSlug    string    `json:"project_slug,omitempty"`
	ErroredBy      string    `json:"errored_by,omitempty"`
	Tag            string    `json:"tag,omitempty"`
	Status         string    `json:"status,omitempty"`
	StartedBy      string    `json:"started_by,omitempty"`
	PipelineNumber int       `json:"pipeline_number,omitempty"`
	CreatedAt      time.Time `json:"created_at,omitempty"`
	StoppedAt      time.Time `json:"stopped_at,omitempty"`
}

Workflow represents information workflow.

type WorkflowJobs

type WorkflowJobs struct {
	Items []struct {
		CanceledBy        string      `json:"canceled_by,omitempty"`
		Dependencies      []string    `json:"dependencies,omitempty"`
		JobNumber         int         `json:"job_number,omitempty"`
		ID                string      `json:"id,omitempty"`
		StartedAt         time.Time   `json:"started_at,omitempty"`
		Name              string      `json:"name,omitempty"`
		ApprovedBy        string      `json:"approved_by,omitempty"`
		ProjectSlug       string      `json:"project_slug,omitempty"`
		Status            interface{} `json:"status,omitempty"`
		Type              string      `json:"type,omitempty"`
		StoppedAt         time.Time   `json:"stopped_at,omitempty"`
		ApprovalRequestID string      `json:"approval_request_id,omitempty"`
	} `json:"items,omitempty"`
	NextPageToken string `json:"next_page_token,omitempty"`
}

WorkflowJobs is jobs belongs to a Workflow.

type WorkflowOp

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

WorkflowOp handles communication with the project related methods in the CircleCI API v2.

func (*WorkflowOp) Approve

func (ps *WorkflowOp) Approve(id, approvalReqID string) (*Message, error)

Approve approves pending workflow job.

func (*WorkflowOp) Cancel

func (ps *WorkflowOp) Cancel(id string) (*Message, error)

Cancel cancels given workflow.

func (*WorkflowOp) Get

func (ps *WorkflowOp) Get(id string) (*Workflow, error)

Get gets detail of workflow.

Example
token := os.Getenv("CIRCLECI_TOKEN")
client := circleci.NewClient(token)

workflowID := "ID"
workflow, err := client.Workflow.Get(workflowID)
if err != nil {
	log.Fatal(err)
}
printPretty(workflow)
Output:

func (*WorkflowOp) GetJobs

func (ps *WorkflowOp) GetJobs(id string) (*WorkflowJobs, error)

GetJobs get jobs in the workflow.

func (*WorkflowOp) Rerun

func (ps *WorkflowOp) Rerun(id string, jobIDs []string, fromFailed bool) (*Message, error)

Rerun cancels given workflow

type WorkflowService

type WorkflowService interface {
	Get(id string) (*Workflow, error)
	Approve(id, approvalReqID string) (*Message, error)
	Cancel(id string) (*Message, error)
	GetJobs(id string) (*WorkflowJobs, error)
	Rerun(id string, jobIDs []string, fromFailed bool) (*Message, error)
}

WorkflowService is an interface for Workflow API.

Jump to

Keyboard shortcuts

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