octo

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2020 License: MIT Imports: 40 Imported by: 0

README

octo-go

godoc ci

octo-go is an experimental client for GitHub's v3 API. It is generated from the openapi schema published at https://github.com/github/rest-api-description

Project status: Experimental

Overview

For every API endpoint, octo-cli provides a request struct and a response struct. The request struct is used to build the http request, and the response struct is used to handle the api's response. You can use these structs as-is and handle all the http details yourself, or you can let octo-go do the request for you as well. Each endpoint also has a function that accepts the endpoints request struct and returns the response struct.

Let's use the issues/create endpoint as an example. You would use issues.CreateReq to build your request.

You can build a request like this:

req := issues.CreateReq{
    Owner: "myorg",
    Repo:  "myrepo",
    RequestBody: issues.CreateReqBody{
        Title: octo.String("hello world"),
        Body:  octo.String("greetings from octo-cli"),
        Labels: []string{"test", "hello-world"},
    },
}

Then you can perform the request with:

resp, err := issues.Create(ctx, &req)

And finally get the id of the newly created issue with:

issueID := resp.Data.Id

User Agent

GitHub requires all requests have a User-Agent header set. Octo-go sets it to octo-go by default, but please set it to the name of your program instead. Do that with the option octo.WithUserAgent("my wonderful computer program").

Authentication

In most situations, octo-go can handle the authentication, but you can also provide your own transport to set the Authentication header if you want.

Personal Access Token

This is the simplest and most common way to authenticate.

myToken := os.Getenv("GITHUB_TOKEN") // or however you want to provide your token

client := octo.NewClient(octo.WithPATAuth(myToken))
GitHub App

If you want to authenticate as a GitHub App, octo can do that for you too. You need to provide the app's private key in PEM format along with your app's ID.

appID := int64(1)
key, err := ioutil.ReadFile("appsecretkey.pem")
if err != nil {
    log.Fatal(err)
}
client := octo.NewClient(octo.WithAppAuth(appID, key))
GitHub App Installation

To authenticate as a GitHub App Installation, you need the installation's ID along with the app's ID and private key.

appID := int64(1)
installationID := int64(99)
key, err := ioutil.ReadFile("appsecretkey.pem")
if err != nil {
    log.Fatal(err)
}

instTokenClient := octo.NewClient(octo.WithAppAuth(appID, key))

auth := octo.WithAppInstallationAuth(installationID, instTokenClient, nil)
client := octo.NewClient(auth)

When authenticating as an App Installation, you can also limit the token's authorization to specific repositories and scopes by setting the request body used to create the token.

appID := int64(1)
installationID := int64(99)
repoID := int64(12)
key, err := ioutil.ReadFile("appsecretkey.pem")
if err != nil {
    log.Fatal(err)
}

instTokenClient := octo.NewClient(octo.WithAppAuth(appID, key))

auth := octo.WithAppInstallationAuth(installationID, instTokenClient, &apps.CreateInstallationAccessTokenReqBody{
    Permissions: map[string]string{
        "deployments": "write",
        "content":     "read",
    },
    RepositoryIds: []int64{repoID},
})
client := octo.NewClient(auth)

Pagination

The GitHub API supports paging through result sets using relative links in the Link header. Octo-go makes use of these headers to enable paging. Every response has the methods RelLink(lnk string) and HasRelLink(lnk string) to get relative links. You can call this with RelNext for the next page of results, RelPrev for the previous page. RelFirst and RelLast point the first and last page of results.

Every request has a Rel(lnk string, resp *ResponseType) method that will update the request to point to a response's relative link.

Let me demonstrate with an example. getReleaseBlockers will page through all open golang/go issues that are labeled "release-blocker" and return their titles.

func getReleaseBlockers(ctx context.Context, client octo.Client) ([]string, error) {
	var result []string

	// Build the initial request.
	req := &issues.ListForRepoReq{
		Owner:  "golang",
		Repo:   "go",
		Labels: octo.String("release-blocker"),
	}

	// ok will be true as long as there is a next page.
	for ok := true; ok; {
		// Get a page of issues.
		resp, err := client.Issues().ListForRepo(ctx, req)
		if err != nil {
			return nil, err
		}

		// Add issue titles to the result.
		for _, issue := range resp.Data {
			result = append(result, issue.Title)
		}

		// Update req to point to the next page of results.
		// If there is no next page, req.Rel will return false and break the loop
		ok = req.Rel(octo.RelNext, resp)
	}
	return result, nil
}

Rate Limits

The GitHub API has a general rate limit of 5,000 requests per hour for most authenticated requests and 60 per hour per ip address for unauthenticated requests. More details are in the API documentation.

The API includes rate limit information in response headers, and octo-go provides three helper functions:

octo.RateLimitRemaining() - returns the number of requests remaining (or -1 if the header is missing)

octo.RateLimitReset() - returns the time when the rate limit will reset (or zero value if the header is missing)

octo.RateLimit() - returns the rate limit (or -1 if the header is missing)

You can also explicitly get your rate limit status with ratelimit.Get()

Documentation

Index

Constants

View Source
const (
	RelNext  = "next"
	RelPrev  = "prev"
	RelFirst = "first"
	RelLast  = "last"
)

Common values for rel links

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to b

func ISOTimeString

func ISOTimeString(tm time.Time) *string

ISOTimeString returns a pointer to tm formated as an iso8601/rfc3339 string

func Int64

func Int64(i int64) *int64

Int64 returns a pointer to i

func RateLimit added in v0.8.0

func RateLimit(r *http.Response) int

RateLimit - The maximum number of requests you're permitted to make per hour.

returns -1 if no X-RateLimit-Limit value exists in the response header

func RateLimitRemaining added in v0.8.0

func RateLimitRemaining(r *http.Response) int

RateLimitRemaining - The number of requests remaining in the current rate limit window.

returns -1 if no X-RateLimit-Remaining value exists in the response header

func RateLimitReset added in v0.8.0

func RateLimitReset(r *http.Response) time.Time

RateLimitReset - X-RateLimit-Reset

returns time.Zero if no X-RateLimit-Reset value exists in the response header
func RelLink(r *http.Response, lnk string) string

RelLink returns the content of lnk from the response's Link header or "" if it does not exist

func String

func String(s string) *string

String returns a pointer to s

func WithAllPreviews

func WithAllPreviews() requests.Option

WithAllPreviews enables all previews that are available for your request

func WithAppAuth

func WithAppAuth(appID int64, privateKey []byte) requests.Option

WithAppAuth provides authentication for a GitHub App. See also WithAppInstallationAuth

appID is the GitHub App's id privateKey is the app's private key. It should be the content of a PEM file

func WithAppInstallationAuth

func WithAppInstallationAuth(installationID int64, client Client, requestBody *apps.CreateInstallationAccessTokenReqBody) requests.Option

WithAppInstallationAuth provides authentication for a GitHub App installation

client is the client to use when fetching the installation token. It should use WithAppAuth.
requestBody is used to restrict access to the installation token. Leave it nil if you don't want to restrict access.

func WithAuthProvider

func WithAuthProvider(authProvider requests.AuthProvider) requests.Option

WithAuthProvider sets a provider to use in setting the Authentication header

This is for custom providers. You will typically want to use WithPATAuth, WithAppAuth or WithAppInstallationAuth instead.

func WithBaseURL

func WithBaseURL(baseURL url.URL) requests.Option

WithBaseURL set the baseURL to use. Default is https://api.github.com

func WithHTTPClient

func WithHTTPClient(client *http.Client) requests.Option

WithHTTPClient sets an http client to use for requests. If unset, http.DefaultClient is used

func WithPATAuth

func WithPATAuth(token string) requests.Option

WithPATAuth authenticates requests with a Personal Access Token

func WithRequiredPreviews

func WithRequiredPreviews() requests.Option

WithRequiredPreviews enables any previews that are required for your request

func WithUserAgent

func WithUserAgent(userAgent string) requests.Option

WithUserAgent sets the User-Agent header in requests

Types

type Client

type Client []requests.Option

Client is a set of options to apply to requests

func NewClient

func NewClient(opt ...requests.Option) Client

NewClient returns a new Client

func (Client) Actions added in v0.8.0

func (c Client) Actions() actions.Client

Actions returns a actions.Client

func (Client) Activity added in v0.8.0

func (c Client) Activity() activity.Client

Activity returns a activity.Client

func (Client) Apps added in v0.8.0

func (c Client) Apps() apps.Client

Apps returns a apps.Client

func (Client) Billing added in v0.8.0

func (c Client) Billing() billing.Client

Billing returns a billing.Client

func (Client) Checks added in v0.8.0

func (c Client) Checks() checks.Client

Checks returns a checks.Client

func (Client) CodeScanning added in v0.8.0

func (c Client) CodeScanning() codescanning.Client

CodeScanning returns a codescanning.Client

func (Client) CodesOfConduct added in v0.8.0

func (c Client) CodesOfConduct() codesofconduct.Client

CodesOfConduct returns a codesofconduct.Client

func (Client) Emojis added in v0.8.0

func (c Client) Emojis() emojis.Client

Emojis returns a emojis.Client

func (Client) Gists added in v0.8.0

func (c Client) Gists() gists.Client

Gists returns a gists.Client

func (Client) Git added in v0.8.0

func (c Client) Git() git.Client

Git returns a git.Client

func (Client) Gitignore added in v0.8.0

func (c Client) Gitignore() gitignore.Client

Gitignore returns a gitignore.Client

func (Client) Interactions added in v0.8.0

func (c Client) Interactions() interactions.Client

Interactions returns a interactions.Client

func (Client) Issues added in v0.8.0

func (c Client) Issues() issues.Client

Issues returns a issues.Client

func (Client) Licenses added in v0.8.0

func (c Client) Licenses() licenses.Client

Licenses returns a licenses.Client

func (Client) Markdown added in v0.8.0

func (c Client) Markdown() markdown.Client

Markdown returns a markdown.Client

func (Client) Meta added in v0.8.0

func (c Client) Meta() meta.Client

Meta returns a meta.Client

func (Client) Migrations added in v0.8.0

func (c Client) Migrations() migrations.Client

Migrations returns a migrations.Client

func (Client) OauthAuthorizations added in v0.8.0

func (c Client) OauthAuthorizations() oauthauthorizations.Client

OauthAuthorizations returns a oauthauthorizations.Client

func (Client) Orgs added in v0.8.0

func (c Client) Orgs() orgs.Client

Orgs returns a orgs.Client

func (Client) Projects added in v0.8.0

func (c Client) Projects() projects.Client

Projects returns a projects.Client

func (Client) Pulls added in v0.8.0

func (c Client) Pulls() pulls.Client

Pulls returns a pulls.Client

func (Client) RateLimit added in v0.8.0

func (c Client) RateLimit() ratelimit.Client

RateLimit returns a ratelimit.Client

func (Client) Reactions added in v0.8.0

func (c Client) Reactions() reactions.Client

Reactions returns a reactions.Client

func (Client) Repos added in v0.8.0

func (c Client) Repos() repos.Client

Repos returns a repos.Client

func (Client) Scim added in v0.8.0

func (c Client) Scim() scim.Client

Scim returns a scim.Client

func (Client) Search added in v0.8.0

func (c Client) Search() search.Client

Search returns a search.Client

func (Client) Teams added in v0.8.0

func (c Client) Teams() teams.Client

Teams returns a teams.Client

func (Client) Users added in v0.8.0

func (c Client) Users() users.Client

Users returns a users.Client

type ResponseError added in v0.8.0

type ResponseError interface {
	HttpResponse() *http.Response
	Error() string
	Data() *components.ResponseErrorData // data from the error body if it can be unmarshalled
	IsClientError() bool                 // true if the http status is in the 4xx range
	IsServerError() bool                 // true if the http status is in the 5xx range
}

ResponseError is an error from an *http.Response.

Jump to

Keyboard shortcuts

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