codeship

package module
v0.0.0-...-8205949 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2020 License: MIT Imports: 17 Imported by: 11

README

Codeship API v2 Client for Go

Codeship Status Coverage Status Go Doc Go Report Card GitHub Release

Codeship

Codeship API v2 client for Go.

Documentation

https://godoc.org/github.com/codeship/codeship-go

Usage

go get -u github.com/codeship/codeship-go

Package codeship provides a client for using the Codeship API v2.

import codeship "github.com/codeship/codeship-go"

Create a new API Client:

auth := codeship.NewBasicAuth("username", "password")
client, err := codeship.New(auth)

You must then scope the client to a single Organization that you have access to:

org, err := client.Organization(ctx, "codeship")

You can then perform calls to the API on behalf of an Organization:

projects, err := org.ListProjects(ctx)

Authentication

Authentication is handled automatically via the API Client using the provided authentication mechanism.

If you would like to manually re-authenticate, you may do this by calling the Authenticate method on the client:

err := client.Authenticate(ctx)
Two-Factor Authentication

Codeship now supports Two-Factor Authentication (2FA).

However, it is currently not possible to use 2FA with the API. If you try to authenticate via this client with a user that has 2FA enabled you will get the following error:

authentication failed: your account has two-factor authentication enabled, which is not possible to support with the API. Disable two factor authentication or create a dedicated API user without it enabled.

You must disable 2FA for the user you wish to authenticate with using this client. We hope to support Personal Access Tokens in a future version of the API to mitigate this issue.

Response

All API methods also return a codeship.Response type that contains the actual *http.Response embedded as well as a Links type that contains information to be used for pagination.

Pagination

Pagination is provided for all requests that can return multiple results. The methods that are able to be paginated all take a variable argument of type PaginationOption such as: ListProjects(opts ...PaginationOption).

We have defined two helper functions, Page and PerPage, to make pagination easier.

Usage is as follows:

// defaults to first page with page_size of 30
projects, resp, err := org.ListProjects(ctx)

// paging forwards with 50 results per page
for {
    if resp.IsLastPage() || resp.Next == "" {
        break
    }

    next, _ := resp.NextPage()

    projects, resp, _ = org.ListProjects(ctx, codeship.Page(next), codeship.PerPage(50))
}

// paging backwards with 50 results per page
for {
    if current, _ := resp.CurrentPage(); current == 1 || resp.Previous == "" {
        break
    }

    prev, _ := resp.PreviousPage()

    projects, resp, _ = org.ListProjects(ctx, codeship.Page(prev), codeship.PerPage(50))
}

Logging

You can enable verbose logging of all HTTP requests/responses by configuring the client via the functional option Verbose(verbose bool) when instantiating the client:

auth := codeship.NewBasicAuth("username", "password")
client, err := codeship.New(auth, codeship.Verbose(true))
Bring your own Logger

The default logger logs to STDOUT but can be replaced by any type that fulfills the StdLogger interface:

// StdLogger allows you to bring your own log implementation for logging
type StdLogger interface {
	Println(...interface{})
}

Example:

import "github.com/sirupsen/logrus"

var (
    logger = logrus.New()
    auth   = codeship.NewBasicAuth("username", "password")
)

client, err := codeship.New(auth, codeship.Verbose(true), codeship.Logger(logger))

Contributing

This project follows Codeship's Go best practices. Please review them and make sure your PR follows the guidelines laid out before submitting.

Everyone interacting in the project and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Code of Conduct.

Setup

To install all dependencies and external tools, run:

make setup tools
Testing
make test

We aim for > 80% test coverage. You can view the current coverage info by running:

make cover
Linting
make lint
Other
$ make help

setup                          Install all dependencies
tools                          Install external tools
test                           Run all the tests
integration                    Run integration tests
cover                          Run all the tests and opens the coverage report
fmt                            goimports all go files
lint                           Run all the linters

Documentation

Overview

Package codeship provides a client for using the Codeship API v2.

The Codeship API v2 documentation exists at: https://apidocs.codeship.com/v2

Usage:

import codeship "github.com/codeship/codeship-go"

Create a new API Client:

auth := codeship.NewBasicAuth("username", "password")
client, err := codeship.New(auth)

You must then scope the client to a single Organization that you have access to:

org, err := client.Organization(ctx, "codeship")

You can then perform calls to the API on behalf of an Organization:

projects, err := org.ListProjects(ctx)

Index

Constants

This section is empty.

Variables

View Source
var ErrRateLimitExceeded = errors.New("rate limit exceeded")

ErrRateLimitExceeded occurs when Codeship returns 403 Forbidden response

Functions

This section is empty.

Types

type Authentication

type Authentication struct {
	AccessToken   string `json:"access_token,omitempty"`
	Organizations []struct {
		Name   string   `json:"name,omitempty"`
		UUID   string   `json:"uuid,omitempty"`
		Scopes []string `json:"scopes,omitempty"`
	} `json:"organizations,omitempty"`
	ExpiresAt int64 `json:"expires_at,omitempty"`
}

Authentication object holds access token and scope information

type Authenticator

type Authenticator interface {
	SetAuth(*http.Request)
}

Authenticator is a strategy for authenticating with the API

type BasicAuth

type BasicAuth struct {
	Username, Password string
}

BasicAuth is an Authenticator that implements basic auth

func NewBasicAuth

func NewBasicAuth(username, password string) *BasicAuth

NewBasicAuth returns a new BasicAuth Authenticator

func (*BasicAuth) SetAuth

func (a *BasicAuth) SetAuth(r *http.Request)

SetAuth implements Authenticator

type Build

type Build struct {
	AllocatedAt      time.Time  `json:"allocated_at,omitempty"`
	Branch           string     `json:"branch,omitempty"`
	CommitMessage    string     `json:"commit_message,omitempty"`
	CommitSha        string     `json:"commit_sha,omitempty"`
	FinishedAt       time.Time  `json:"finished_at,omitempty"`
	Links            BuildLinks `json:"links,omitempty"`
	OrganizationUUID string     `json:"organization_uuid,omitempty"`
	ProjectID        uint       `json:"project_id,omitempty"`
	ProjectUUID      string     `json:"project_uuid,omitempty"`
	QueuedAt         time.Time  `json:"queued_at,omitempty"`
	Ref              string     `json:"ref,omitempty"`
	Status           string     `json:"status,omitempty"`
	Username         string     `json:"username,omitempty"`
	UUID             string     `json:"uuid,omitempty"`
}

Build structure of Build object

type BuildLinks struct {
	Pipelines string `json:"pipelines,omitempty"`
	Services  string `json:"services,omitempty"`
	Steps     string `json:"steps,omitempty"`
}

BuildLinks structure of BuildLinks object for a Build

type BuildList

type BuildList struct {
	Builds []Build `json:"builds"`
	// contains filtered or unexported fields
}

BuildList holds a list of Build objects

type BuildPipeline

type BuildPipeline struct {
	UUID       string               `json:"uuid,omitempty"`
	BuildUUID  string               `json:"build_uuid,omitempty"`
	Type       string               `json:"type,omitempty"`
	Status     string               `json:"status,omitempty"`
	CreatedAt  time.Time            `json:"created_at,omitempty"`
	UpdatedAt  time.Time            `json:"updated_at,omitempty"`
	FinishedAt time.Time            `json:"finished_at,omitempty"`
	Metrics    BuildPipelineMetrics `json:"metrics,omitempty"`
}

BuildPipeline structure of BuildPipeline object for a Basic Project

type BuildPipelineMetrics

type BuildPipelineMetrics struct {
	AmiID                 string `json:"ami_id,omitempty"`
	Queries               string `json:"queries,omitempty"`
	CPUUser               string `json:"cpu_user,omitempty"`
	Duration              string `json:"duration,omitempty"`
	CPUSystem             string `json:"cpu_system,omitempty"`
	InstanceID            string `json:"instance_id,omitempty"`
	Architecture          string `json:"architecture,omitempty"`
	InstanceType          string `json:"instance_type,omitempty"`
	CPUPerSecond          string `json:"cpu_per_second,omitempty"`
	DiskFreeBytes         string `json:"disk_free_bytes,omitempty"`
	DiskUsedBytes         string `json:"disk_used_bytes,omitempty"`
	NetworkRxBytes        string `json:"network_rx_bytes,omitempty"`
	NetworkTxBytes        string `json:"network_tx_bytes,omitempty"`
	MaxUsedConnections    string `json:"max_used_connections,omitempty"`
	MemoryMaxUsageInBytes string `json:"memory_max_usage_in_bytes,omitempty"`
}

BuildPipelineMetrics structure of BuildPipelineMetrics object for a BuildPipeline

type BuildPipelines

type BuildPipelines struct {
	Pipelines []BuildPipeline `json:"pipelines"`
	// contains filtered or unexported fields
}

BuildPipelines holds a list of BuildPipeline objects for a Basic Project

type BuildService

type BuildService struct {
	BuildUUID  string    `json:"build_uuid,omitempty"`
	BuildingAt time.Time `json:"building_at,omitempty"`
	CreatedAt  time.Time `json:"created_at,omitempty"`
	FinishedAt time.Time `json:"finished_at,omitempty"`
	Name       string    `json:"name,omitempty"`
	PullingAt  time.Time `json:"pulling_at,omitempty"`
	UpdatedAt  time.Time `json:"updated_at,omitempty"`
	UUID       string    `json:"uuid,omitempty"`
	Status     string    `json:"status,omitempty"`
}

BuildService structure of BuildService object for a Pro Project

type BuildServices

type BuildServices struct {
	Services []BuildService `json:"services"`
	// contains filtered or unexported fields
}

BuildServices holds a list of BuildService objects for a Pro Project

type BuildStep

type BuildStep struct {
	BuildUUID   string      `json:"build_uuid,omitempty"`
	BuildingAt  time.Time   `json:"building_at,omitempty"`
	Command     string      `json:"command,omitempty"`
	FinishedAt  time.Time   `json:"finished_at,omitempty"`
	ImageName   string      `json:"image_name,omitempty"`
	Name        string      `json:"name,omitempty"`
	Registry    string      `json:"registry,omitempty"`
	ServiceUUID string      `json:"service_uuid,omitempty"`
	StartedAt   time.Time   `json:"started_at,omitempty"`
	Status      string      `json:"status,omitempty"`
	Steps       []BuildStep `json:"steps,omitempty"`
	Tag         string      `json:"tag,omitempty"`
	Type        string      `json:"type,omitempty"`
	UpdatedAt   time.Time   `json:"updated_at,omitempty"`
	UUID        string      `json:"uuid,omitempty"`
}

BuildStep structure of BuildStep object for a Pro Project

type BuildSteps

type BuildSteps struct {
	Steps []BuildStep `json:"steps"`
	// contains filtered or unexported fields
}

BuildSteps holds a list of BuildStep objects for a Pro Project

type Client

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

Client holds information necessary to make a request to the Codeship API

func New

func New(auth Authenticator, opts ...Option) (*Client, error)

New creates a new Codeship API client

func (*Client) Authenticate

func (c *Client) Authenticate(ctx context.Context) (Response, error)

Authenticate swaps username/password for an authentication token

Codeship API docs: https://apidocs.codeship.com/v2/authentication/authentication-endpoint

func (*Client) Authentication

func (c *Client) Authentication() Authentication

Authentication returns the client's current Authentication object

func (*Client) AuthenticationRequired

func (c *Client) AuthenticationRequired() bool

AuthenticationRequired determines if a client must authenticate before making a request

func (*Client) Organization

func (c *Client) Organization(ctx context.Context, name string) (*Organization, error)

Organization scopes a client to a single Organization, allowing the user to make calls to the API

type DeploymentBranch

type DeploymentBranch struct {
	BranchName string `json:"branch_name,omitempty"`
	MatchMode  string `json:"match_mode,omitempty"`
}

DeploymentBranch structure for DeploymentBranch object for a Basic Project

type DeploymentPipeline

type DeploymentPipeline struct {
	ID       int                    `json:"id,omitempty"`
	Branch   DeploymentBranch       `json:"branch,omitempty"`
	Config   map[string]interface{} `json:"config,omitempty"`
	Position int                    `json:"position,omitempty"`
}

DeploymentPipeline structure for DeploymentPipeline object for a Basic Project

type EnvironmentVariable

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

EnvironmentVariable structure for EnvironmentVariable object for a Basic Project

type ErrBadRequest

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

ErrBadRequest occurs when Codeship returns a 400 Bad Request response

func (ErrBadRequest) Error

func (e ErrBadRequest) Error() string

type ErrNotFound

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

ErrNotFound occurs when Codeship returns a 404 Not Found response

func (ErrNotFound) Error

func (e ErrNotFound) Error() string

type ErrUnauthorized

type ErrUnauthorized string

ErrUnauthorized occurs when Codeship returns a 401 Unauthorized response

func (ErrUnauthorized) Error

func (e ErrUnauthorized) Error() string
type Links struct {
	Next     string
	Previous string
	Last     string
	First    string
}

Links contain links for pagination purposes

Codeship API docs: https://apidocs.codeship.com/v2/introduction/pagination

func (Links) CurrentPage

func (l Links) CurrentPage() (int, error)

CurrentPage returns the page number of the current page

func (Links) IsLastPage

func (l Links) IsLastPage() bool

IsLastPage returns true if the current page is the last

func (Links) LastPage

func (l Links) LastPage() (int, error)

LastPage returns the page number of the last page

func (Links) NextPage

func (l Links) NextPage() (int, error)

NextPage returns the page number of the next page

func (Links) PreviousPage

func (l Links) PreviousPage() (int, error)

PreviousPage returns the page number of the previous page

type NotificationOptions

type NotificationOptions struct {
	Key  string `json:"key,omitempty"`
	URL  string `json:"url,omitempty"`
	Room string `json:"room,omitempty"`
}

NotificationOptions structure for NotificationOptions object for a Project

type NotificationRule

type NotificationRule struct {
	Branch        string              `json:"branch,omitempty"`
	BranchMatch   string              `json:"branch_match,omitempty"`
	Notifier      string              `json:"notifier,omitempty"`
	Options       NotificationOptions `json:"options,omitempty"`
	BuildStatuses []string            `json:"build_statuses,omitempty"`
	Target        string              `json:"target,omitempty"`
}

NotificationRule structure for NotificationRule object for a Project

type Option

type Option func(*Client) error

Option is a functional option for configuring the API client

func BaseURL

func BaseURL(baseURL string) Option

BaseURL allows overriding of API client baseURL for testing

func HTTPClient

func HTTPClient(client *http.Client) Option

HTTPClient accepts a custom *http.Client for making API calls

func Headers

func Headers(headers http.Header) Option

Headers allows you to set custom HTTP headers when making API calls (e.g. for satisfying HTTP proxies, or for debugging)

func Logger

func Logger(logger StdLogger) Option

Logger allows overriding the default STDOUT logger

func Verbose

func Verbose(verbose bool) Option

Verbose allows enabling/disabling internal logging

type Organization

type Organization struct {
	UUID   string
	Name   string
	Scopes []string
	// contains filtered or unexported fields
}

Organization holds the configuration for the current API client scoped to the Organization. Should not be modified concurrently

func (*Organization) CreateBuild

func (o *Organization) CreateBuild(ctx context.Context, projectUUID, ref, commitSha string) (bool, Response, error)

CreateBuild creates a new build

Codeship API docs: https://apidocs.codeship.com/v2/builds/create-build

func (*Organization) CreateProject

func (o *Organization) CreateProject(ctx context.Context, p ProjectCreateRequest) (Project, Response, error)

CreateProject creates a new project

Codeship API docs: https://apidocs.codeship.com/v2/projects/create-project

func (*Organization) GetBuild

func (o *Organization) GetBuild(ctx context.Context, projectUUID, buildUUID string) (Build, Response, error)

GetBuild fetches a build by UUID

Codeship API docs: https://apidocs.codeship.com/v2/builds/get-build

func (*Organization) GetProject

func (o *Organization) GetProject(ctx context.Context, projectUUID string) (Project, Response, error)

GetProject fetches a project by UUID

Codeship API docs: https://apidocs.codeship.com/v2/projects/get-project

func (*Organization) ListBuildPipelines

func (o *Organization) ListBuildPipelines(ctx context.Context, projectUUID, buildUUID string, opts ...PaginationOption) (BuildPipelines, Response, error)

ListBuildPipelines lists Basic build pipelines

Codeship API docs: https://apidocs.codeship.com/v2/builds/get-build-pipelines

func (*Organization) ListBuildServices

func (o *Organization) ListBuildServices(ctx context.Context, projectUUID, buildUUID string, opts ...PaginationOption) (BuildServices, Response, error)

ListBuildServices lists Pro build services

Codeship API docs: https://apidocs.codeship.com/v2/builds/get-build-services

func (*Organization) ListBuildSteps

func (o *Organization) ListBuildSteps(ctx context.Context, projectUUID, buildUUID string, opts ...PaginationOption) (BuildSteps, Response, error)

ListBuildSteps lists Pro build steps

Codeship API docs: https://apidocs.codeship.com/v2/builds/get-build-steps

func (*Organization) ListBuilds

func (o *Organization) ListBuilds(ctx context.Context, projectUUID string, opts ...PaginationOption) (BuildList, Response, error)

ListBuilds fetches a list of builds

Codeship API docs: https://apidocs.codeship.com/v2/builds/list-builds

func (*Organization) ListProjects

func (o *Organization) ListProjects(ctx context.Context, opts ...PaginationOption) (ProjectList, Response, error)

ListProjects fetches a list of projects

Codeship API docs: https://apidocs.codeship.com/v2/projects/list-projects

func (*Organization) ResetProjectAESKey

func (o *Organization) ResetProjectAESKey(ctx context.Context, projectUUID string) (Project, Response, error)

ResetProjectAESKey resets the AES key for a project

Codeship API docs: https://apidocs.codeship.com/v2/projects/reset-aes-key

func (*Organization) RestartBuild

func (o *Organization) RestartBuild(ctx context.Context, projectUUID, buildUUID string) (bool, Response, error)

RestartBuild restarts a previous build

Codeship API docs: https://apidocs.codeship.com/v2/builds/restart-build

func (*Organization) StopBuild

func (o *Organization) StopBuild(ctx context.Context, projectUUID, buildUUID string) (bool, Response, error)

StopBuild stops a running build

Codeship API docs: https://apidocs.codeship.com/v2/builds/stop-build

func (*Organization) UpdateProject

func (o *Organization) UpdateProject(ctx context.Context, projectUUID string, p ProjectUpdateRequest) (Project, Response, error)

UpdateProject updates an existing project

Codeship API docs: https://apidocs.codeship.com/v2/projects/update-project

type PaginationOption

type PaginationOption func(o *paginationOption)

PaginationOption is a functional option for providing pagination options

func Page

func Page(page int) PaginationOption

Page sets the page of results to be returned in the response

func PerPage

func PerPage(perPage int) PaginationOption

PerPage sets the number of results to be returned per page in the response

type Project

type Project struct {
	AesKey               string                `json:"aes_key,omitempty"`
	AuthenticationUser   string                `json:"authentication_user,omitempty"`
	CreatedAt            time.Time             `json:"created_at,omitempty"`
	DeploymentPipelines  []DeploymentPipeline  `json:"deployment_pipelines,omitempty"`
	EnvironmentVariables []EnvironmentVariable `json:"environment_variables,omitempty"`
	ID                   uint                  `json:"id,omitempty"`
	Name                 string                `json:"name,omitempty"`
	NotificationRules    []NotificationRule    `json:"notification_rules,omitempty"`
	OrganizationUUID     string                `json:"organization_uuid,omitempty"`
	RepositoryProvider   string                `json:"repository_provider,omitempty"`
	RepositoryURL        string                `json:"repository_url,omitempty"`
	SetupCommands        []string              `json:"setup_commands,omitempty"`
	SSHKey               string                `json:"ssh_key,omitempty"`
	TeamIDs              []int                 `json:"team_ids,omitempty"`
	TestPipelines        []TestPipeline        `json:"test_pipelines,omitempty"`
	Type                 ProjectType           `json:"type"`
	UpdatedAt            time.Time             `json:"updated_at,omitempty"`
	UUID                 string                `json:"uuid,omitempty"`
}

Project structure for Project object

type ProjectCreateRequest

type ProjectCreateRequest struct {
	DeploymentPipelines  []DeploymentPipeline  `json:"deployment_pipelines,omitempty"`
	EnvironmentVariables []EnvironmentVariable `json:"environment_variables,omitempty"`
	NotificationRules    []NotificationRule    `json:"notification_rules,omitempty"`
	RepositoryURL        string                `json:"repository_url,omitempty"`
	SetupCommands        []string              `json:"setup_commands,omitempty"`
	TeamIDs              []int                 `json:"team_ids,omitempty"`
	TestPipelines        []TestPipeline        `json:"test_pipelines,omitempty"`
	Type                 ProjectType           `json:"type"`
}

ProjectCreateRequest structure for creating a Project

type ProjectList

type ProjectList struct {
	Projects []Project `json:"projects"`
	// contains filtered or unexported fields
}

ProjectList holds a list of Project objects

type ProjectType

type ProjectType int

ProjectType represents Codeship project types (Basic and Pro)

const (
	// ProjectTypeBasic represents a Codeship Basic project type
	ProjectTypeBasic ProjectType = iota
	// ProjectTypePro represents a Codeship Pro project type
	ProjectTypePro
)

func (ProjectType) MarshalJSON

func (t ProjectType) MarshalJSON() ([]byte, error)

MarshalJSON marshals a ProjectType to JSON

func (ProjectType) String

func (t ProjectType) String() string

func (*ProjectType) UnmarshalJSON

func (t *ProjectType) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals JSON to a ProjectType

type ProjectUpdateRequest

type ProjectUpdateRequest struct {
	EnvironmentVariables []EnvironmentVariable `json:"environment_variables,omitempty"`
	NotificationRules    []NotificationRule    `json:"notification_rules,omitempty"`
	SetupCommands        []string              `json:"setup_commands,omitempty"`
	TeamIDs              []int                 `json:"team_ids,omitempty"`
	Type                 ProjectType           `json:"type"`
}

ProjectUpdateRequest structure for updating a Project

type Response

type Response struct {
	*http.Response
	// Links that were returned with the response. These are parsed from the Link header.
	Links
}

Response is a Codeship response. This wraps the standard http.Response returned from Codeship.

type StdLogger

type StdLogger interface {
	Println(...interface{})
}

StdLogger allows you to bring your own log implementation for logging

type TestPipeline

type TestPipeline struct {
	ID       int      `json:"id,omitempty"`
	Commands []string `json:"commands,omitempty"`
	Name     string   `json:"name,omitempty"`
}

TestPipeline structure for Project object

Directories

Path Synopsis
Package integration contains integration tests.
Package integration contains integration tests.

Jump to

Keyboard shortcuts

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