Giter Site home page Giter Site logo

codeship / codeship-go Goto Github PK

View Code? Open in Web Editor NEW
18.0 18.0 9.0 302 KB

Go library for accessing the Codeship API v2

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

License: MIT License

Go 97.74% Makefile 1.21% Shell 0.57% Dockerfile 0.47%
codeship codeship-api golang golang-library api-client

codeship-go's Introduction

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

codeship-go's People

Contributors

brettbuddin avatar fillup avatar garethjevans avatar joesiewert avatar krames avatar markphelps avatar rheinwein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codeship-go's Issues

Support GZIP compression

Codeship now supports GZIP compression on responses if requested with the Accept-Encoding: gzip header.

We should allow our client to request gzipped responses in order to reduce latency. This should perhaps be on by default but configurable by the end user of the client.

Handle errors

We return an errors JSON response { errors: ['foo', 'bar'] } along with the appropriate HTTP status code. We should probably create an errors type or handle errors in a better way?

The Marshall function in projects.go does not work as expected.

CreateProject() does not properly marshal a project for which 'pro' is set.

Using the const codeship.ProjectTypePro results in a response error: "expecting 'basic' or 'pro'"
Using the word "pro" just results in Go throwing up a type error during compilation

I expected the marshaling to work correctly.

To reproduce, attempt to create a new project of type 'pro'.

The marshal definition is incorrect. When I changed

// MarshalJSON marshals a ProjectType to JSON
func (t *ProjectType) MarshalJSON() ([]byte, error) {
	return json.Marshal(t.String())
}

To

// MarshalJSON marshals a ProjectType to JSON
func (t ProjectType) MarshalJSON() ([]byte, error) {
	return json.Marshal(t.String())
}

... it worked fine. Note the function args for the working version is pass-by-value. ProjectType is a numeric primitive of type iota, and I think it should be passed around by value, not by reference.

Unable to create a new project with the project type 'basic'

Description

Unable to create a new project with the project type 'basic'

possibly related to #45

Actual outcome

When trying to create a build with:

createProjectRequest := codeship.ProjectCreateRequest{
	Type:          codeship.ProjectTypeBasic,
	RepositoryURL: fmt.Sprintf("[email protected]:%s/%s", githubUser, githubProject),
}

I always get the error unable to create project: Type must be either 'pro' or 'basic'

Looking at the code, i think that

ProjectTypeBasic ProjectType = iota
and
Type ProjectType `json:"type,omitempty"`
are conflicting against each other. The docs for omitempty seem to suggest that integer values of 0 are considered empty and will be omitted from the request.

Running in verbose mode does seem to confirm this:

POST /v2/organizations/<org>/projects HTTP/1.1
Host: api.codeship.com
Accept: application/json
Authorization: Bearer REMOVED
Content-Type: application/json

{"repository_url":"[email protected]:garethjevans/myrepo"}

HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Date: Mon, 16 Jul 2018 11:39:54 GMT
Server: Cowboy
Strict-Transport-Security: max-age=31536000; includeSubDomains
Vary: Accept-Encoding
Via: 1.1 vegur
X-Frame-Options: SAMEORIGIN
X-Request-Id: afea08dc-306a-425a-a269-dad3f6d9ad62
X-Runtime: 0.008124

33
{"errors":["Type must be either 'pro' or 'basic'"]}
0

Expected outcome

I was expecting the project to be successfully created

Steps to reproduce the issue

Use the golang api to create a project of type basic.

Additional information

Support pagination

Support pagination for all list responses and requests

Make use of the total, per_page, and page query params as well as the Link headers in the responses.

Delete Project in the API

Description

I need to delete projects via API and as far as I can see the API doesn't let me do it.

Are you planning on implement it?

Handle 2FA Error

Description

When trying to authenticate with my account that has 2FA enabled, I get the following error:

organization 'codeship' not authorized. Authorized organizations: []

When in reality I am authorized, but I have 2FA enabled. Making the same request via Postman returns this more helpful error:

{
    "error": "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"
}

Expected outcome

Return the more helpful error message like:

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

Instead of:

organization 'codeship' not authorized. Authorized organizations: []

Example in README.md is outdated

Description

The following example in the README.md file is outdated

Actual wording

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

projects, err := org.ListProjects(ctx)

Expected wording

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

projects, response, err := org.ListProjects(ctx)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.