scm

package
v0.0.0-...-e99cc0b Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2020 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const EmptyCommit = "0000000000000000000000000000000000000000"

EmptyCommit is an empty commit sha.

Variables

View Source
var (
	// ErrNotFound indicates a resource is not found.
	ErrNotFound = errors.New("Not Found")

	// ErrNotSupported indicates a resource endpoint is not
	// supported or implemented.
	ErrNotSupported = errors.New("Not Supported")

	// ErrNotAuthorized indicates the request is not
	// authorized or the user does not have access to the
	// resource.
	ErrNotAuthorized = errors.New("Not Authorized")
)
View Source
var (
	// ErrSignatureInvalid is returned when the webhook
	// signature is invalid or cannot be calculated.
	ErrSignatureInvalid = errors.New("Invalid webhook signature")

	// ErrUnknownEvent is returned when the webhook event
	// is not recognized by the system.
	ErrUnknownEvent = errors.New("Unknown webhook event")
)

Functions

func ExpandRef

func ExpandRef(name, prefix string) string

ExpandRef returns name expanded to the fully qualified reference path (e.g refs/heads/master).

func ExtractPullRequest

func ExtractPullRequest(ref string) int

ExtractPullRequest returns name extraced pull request number from the reference path.

func IsBranch

func IsBranch(ref string) bool

IsBranch returns true if the reference path points to a branch.

func IsPullRequest

func IsPullRequest(ref string) bool

IsPullRequest returns true if the reference path points to a pull request object.

func IsTag

func IsTag(ref string) bool

IsTag returns true if the reference path points to a tag object.

func Join

func Join(owner, name string) string

Join joins the repository owner and name segments to create a fully qualified repository name.

func Split

func Split(s string) (owner, name string)

Split splits the full repository name into segments.

func TrimRef

func TrimRef(ref string) string

TrimRef returns ref without the path prefix.

func WithContext

func WithContext(parent context.Context, token *Token) context.Context

WithContext returns a copy of parent in which the token value is set

Types

type Action

type Action int

Action identifies webhook actions.

const (
	ActionCreate Action = iota + 1
	ActionUpdate
	ActionDelete
	// issues
	ActionOpen
	ActionReopen
	ActionClose
	ActionLabel
	ActionUnlabel
	// pull requests
	ActionSync
	ActionMerge
)

Action values.

func (Action) MarshalJSON

func (a Action) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON-encoded Action.

func (Action) String

func (a Action) String() (s string)

String returns the string representation of Action.

func (*Action) UnmarshalJSON

func (a *Action) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshales the JSON-encoded Action.

type BranchHook

type BranchHook struct {
	Ref    Reference
	Repo   Repository
	Action Action
	Sender User
}

BranchHook represents a branch or tag event, eg create and delete github event types.

func (*BranchHook) Repository

func (h *BranchHook) Repository() Repository

type Change

type Change struct {
	Path    string
	Added   bool
	Renamed bool
	Deleted bool
}

Change represents a changed file.

type Client

type Client struct {

	// HTTP client used to communicate with the API.
	Client *http.Client

	// Base URL for API requests.
	BaseURL *url.URL

	// Services used for communicating with the API.
	Driver        Driver
	Linker        Linker
	Contents      ContentService
	Git           GitService
	Organizations OrganizationService
	Issues        IssueService
	PullRequests  PullRequestService
	Repositories  RepositoryService
	Reviews       ReviewService
	Users         UserService
	Webhooks      WebhookService

	// DumpResponse optionally specifies a function to
	// dump the the response body for debugging purposes.
	// This can be set to httputil.DumpResponse.
	DumpResponse func(*http.Response, bool) ([]byte, error)
	// contains filtered or unexported fields
}

Client manages communication with a version control system API.

Example
package main

import (
	"log"
	"net/http"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	// Sets a custom http.Client. This can be used with
	// github.com/golang/oauth2 for authorization.
	client.Client = &http.Client{}
}
Output:

func (*Client) Do

func (c *Client) Do(ctx context.Context, in *Request) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response will be written to v, without attempting to decode it.

func (*Client) Rate

func (c *Client) Rate() Rate

Rate returns a snapshot of the request rate limit for the current client.

func (*Client) SetRate

func (c *Client) SetRate(rate Rate)

SetRate set the last recorded request rate limit for the current client.

type Comment

type Comment struct {
	ID      int
	Body    string
	Author  User
	Created time.Time
	Updated time.Time
}

Comment represents a comment.

Example (Create)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	in := &scm.CommentInput{
		Body: "Found a bug",
	}

	comment, _, err := client.Issues.CreateComment(ctx, "octocat/Hello-World", 1, in)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(comment.ID)
}
Output:

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	comment, _, err := client.Issues.FindComment(ctx, "octocat/Hello-World", 1, 1)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(comment.Body)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	comments, _, err := client.Issues.ListComments(ctx, "octocat/Hello-World", 1, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, comment := range comments {
		log.Println(comment.Body)
	}
}
Output:

type CommentInput

type CommentInput struct {
	Body string
}

CommentInput provides the input fields required for creating an issue comment.

type Commit

type Commit struct {
	Sha       string
	Message   string
	Author    Signature
	Committer Signature
	Link      string
}

Commit represents a repository commit.

Example (Changes)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	changes, _, err := client.Git.ListChanges(ctx, "octocat/Hello-World", "6dcb09b5b57875f334f61aebed695e2e4193db5e", opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, change := range changes {
		log.Println(change.Path, change.Added, change.Deleted, change.Renamed)
	}
}
Output:

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	commit, _, err := client.Git.FindCommit(ctx, "octocat/Hello-World", "6dcb09b5b57875f334f61aebed695e2e4193db5e")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(commit.Sha, commit.Message, commit.Author.Login)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.CommitListOptions{
		Ref:  "master",
		Page: 1,
		Size: 30,
	}

	commits, _, err := client.Git.ListCommits(ctx, "octocat/Hello-World", opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, commit := range commits {
		log.Println(commit.Sha, commit.Message, commit.Author.Login)
	}
}
Output:

type CommitListOptions

type CommitListOptions struct {
	Ref  string
	Page int
	Size int
}

CommitListOptions provides options for querying a list of repository commits.

type Content

type Content struct {
	Path string
	Data []byte
}

Content stores the contents of a repository file.

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	content, _, err := client.Contents.Find(ctx, "octocat/Hello-World", "README", "6dcb09b5b57875f334f61aebed695e2e4193db5e")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(content.Path, content.Data)
}
Output:

type ContentInfo

type ContentInfo struct {
	Path string
	Kind ContentKind
}

ContentInfo stores the kind of any content in a repository.

type ContentKind

type ContentKind int

ContentKind defines the kind of a content in a directory.

const (
	ContentKindUnsupported ContentKind = iota
	ContentKindFile
	ContentKindDirectory
	ContentKindSymlink
	ContentKindGitlink
)

ContentKind values.

func (ContentKind) String

func (k ContentKind) String() string

String returns the string representation of ContentKind.

func (*ContentKind) UnmarshalJSON

func (k *ContentKind) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshales the JSON-encoded ContentKind.

type ContentParams

type ContentParams struct {
	Ref       string
	Branch    string
	Message   string
	Data      []byte
	Sha       string
	Signature Signature
}

ContentParams provide parameters for creating and updating repository content.

type ContentService

type ContentService interface {
	// Find returns the repository file content by path.
	Find(ctx context.Context, repo, path, ref string) (*Content, *Response, error)

	// Create creates a new repositroy file.
	Create(ctx context.Context, repo, path string, params *ContentParams) (*Response, error)

	// Update updates a repository file.
	Update(ctx context.Context, repo, path string, params *ContentParams) (*Response, error)

	// Delete deletes a reository file.
	Delete(ctx context.Context, repo, path, ref string) (*Response, error)

	// List returns a list of contents in a repository directory by path. It is
	// up to the driver to list the directory recursively or non-recursively,
	// but a robust driver should return a non-recursive list if possible.
	List(ctx context.Context, repo, path, ref string, opts ListOptions) ([]*ContentInfo, *Response, error)
}

ContentService provides access to repositroy content.

type DeployHook

type DeployHook struct {
	Data      interface{}
	Desc      string
	Number    int64
	Ref       Reference
	Repo      Repository
	Sender    User
	Target    string
	TargetURL string
	Task      string
}

DeployHook represents a deployment event. This is currently a GitHub-specific event type.

func (*DeployHook) Repository

func (h *DeployHook) Repository() Repository

type DeployStatus

type DeployStatus struct {
	Number         int64
	State          State
	Desc           string
	Target         string
	Environment    string
	EnvironmentURL string
}

DeployStatus represents a deployment status.

type Driver

type Driver int

Driver identifies source code management driver.

const (
	DriverUnknown Driver = iota
	DriverGithub
	DriverGitlab
	DriverGogs
	DriverGitea
	DriverBitbucket
	DriverStash
	DriverCoding
)

Driver values.

func (Driver) String

func (d Driver) String() (s string)

String returns the string representation of Driver.

type GitService

type GitService interface {
	// FindBranch finds a git branch by name.
	FindBranch(ctx context.Context, repo, name string) (*Reference, *Response, error)

	// FindCommit finds a git commit by ref.
	FindCommit(ctx context.Context, repo, ref string) (*Commit, *Response, error)

	// FindTag finds a git tag by name.
	FindTag(ctx context.Context, repo, name string) (*Reference, *Response, error)

	// ListBranches returns a list of git branches.
	ListBranches(ctx context.Context, repo string, opts ListOptions) ([]*Reference, *Response, error)

	// ListCommits returns a list of git commits.
	ListCommits(ctx context.Context, repo string, opts CommitListOptions) ([]*Commit, *Response, error)

	// ListChanges returns the changeset of a commit.
	ListChanges(ctx context.Context, repo, ref string, opts ListOptions) ([]*Change, *Response, error)

	// ListTags returns a list of git tags.
	ListTags(ctx context.Context, repo string, opts ListOptions) ([]*Reference, *Response, error)

	// CompareChanges returns the changeset between two
	// commits. If the source commit is not an ancestor
	// of the target commit, it is up to the driver to
	// return a 2-way or 3-way diff changeset.
	CompareChanges(ctx context.Context, repo, source, target string, opts ListOptions) ([]*Change, *Response, error)
}

GitService provides access to git resources.

type Hook

type Hook struct {
	ID         string
	Name       string
	Target     string
	Events     []string
	Active     bool
	SkipVerify bool
}

Hook represents a repository hook.

Example (Create)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	input := &scm.HookInput{
		Name:       "CI",
		Target:     "https://ci.example.com",
		Secret:     "topsecret",
		SkipVerify: false,
		Events: scm.HookEvents{
			Branch:             true,
			Issue:              false,
			IssueComment:       false,
			PullRequest:        true,
			PullRequestComment: false,
			Push:               true,
			ReviewComment:      false,
			Tag:                true,
		},
	}

	_, _, err = client.Repositories.CreateHook(ctx, "octocat/Hello-World", input)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	hook, _, err := client.Repositories.FindHook(ctx, "octocat/Hello-World", "1")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(hook.ID, hook.Target, hook.Events)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	hooks, _, err := client.Repositories.ListHooks(ctx, "octocat/Hello-World", opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, hook := range hooks {
		log.Println(hook.ID, hook.Target, hook.Events)
	}
}
Output:

type HookEvents

type HookEvents struct {
	Branch             bool
	Deployment         bool
	Issue              bool
	IssueComment       bool
	PullRequest        bool
	PullRequestComment bool
	Push               bool
	ReviewComment      bool
	Tag                bool
}

HookEvents represents supported hook events.

type HookInput

type HookInput struct {
	Name       string
	Target     string
	Secret     string
	Events     HookEvents
	SkipVerify bool

	// NativeEvents are used to create hooks with
	// provider-specific event types that cannot be
	// abstracted or represented in HookEvents.
	NativeEvents []string
}

HookInput provides the input fields required for creating or updating repository webhooks.

type Issue

type Issue struct {
	Number  int
	Title   string
	Body    string
	Link    string
	Labels  []string
	Closed  bool
	Locked  bool
	Author  User
	Created time.Time
	Updated time.Time
}

Issue represents an issue.

Example (Close)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.Issues.Close(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	issue, _, err := client.Issues.Find(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(issue.Number, issue.Title)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.IssueListOptions{
		Page:   1,
		Size:   30,
		Open:   true,
		Closed: false,
	}

	issues, _, err := client.Issues.List(ctx, "octocat/Hello-World", opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, issue := range issues {
		log.Println(issue.Number, issue.Title)
	}
}
Output:

Example (Lock)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.Issues.Lock(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (Unlock)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.Issues.Lock(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

type IssueCommentHook

type IssueCommentHook struct {
	Action  Action
	Repo    Repository
	Issue   Issue
	Comment Comment
	Sender  User
}

IssueCommentHook represents an issue comment event, eg issue_comment.

func (*IssueCommentHook) Repository

func (h *IssueCommentHook) Repository() Repository

type IssueHook

type IssueHook struct {
	Action Action
	Repo   Repository
	Issue  Issue
	Sender User
}

IssueHook represents an issue event, eg issues.

func (*IssueHook) Repository

func (h *IssueHook) Repository() Repository

type IssueInput

type IssueInput struct {
	Title string
	Body  string
}

IssueInput provides the input fields required for creating or updating an issue.

type IssueListOptions

type IssueListOptions struct {
	Page   int
	Size   int
	Open   bool
	Closed bool
}

IssueListOptions provides options for querying a list of repository issues.

type IssueService

type IssueService interface {
	// Find returns the issue by number.
	Find(context.Context, string, int) (*Issue, *Response, error)

	// FindComment returns the issue comment.
	FindComment(context.Context, string, int, int) (*Comment, *Response, error)

	// List returns the repository issue list.
	List(context.Context, string, IssueListOptions) ([]*Issue, *Response, error)

	// ListComments returns the issue comment list.
	ListComments(context.Context, string, int, ListOptions) ([]*Comment, *Response, error)

	// Create creates a new issue.
	Create(context.Context, string, *IssueInput) (*Issue, *Response, error)

	// CreateComment creates a new issue comment.
	CreateComment(context.Context, string, int, *CommentInput) (*Comment, *Response, error)

	// DeleteComment deletes an issue comment.
	DeleteComment(context.Context, string, int, int) (*Response, error)

	// Close closes an issue.
	Close(context.Context, string, int) (*Response, error)

	// Lock locks an issue discussion.
	Lock(context.Context, string, int) (*Response, error)

	// Unlock unlocks an issue discussion.
	Unlock(context.Context, string, int) (*Response, error)
}

IssueService provides access to issue resources.

type Label

type Label struct {
	Name  string
	Color string
}

type Linker

type Linker interface {
	// Resource returns a link to the resource.
	Resource(ctx context.Context, repo string, ref Reference) (string, error)

	// Diff returns a link to the diff.
	Diff(ctx context.Context, repo string, source, target Reference) (string, error)
}

Linker provides deep links to resources.

type ListOptions

type ListOptions struct {
	URL  string
	Page int
	Size int
}

ListOptions specifies optional pagination parameters.

type Membership

type Membership struct {
	Active bool
	Role   Role
}

Membership represents an organization membership.

type Organization

type Organization struct {
	Name   string
	Avatar string
}

Organization represents an organization account.

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	org, _, err := client.Organizations.Find(ctx, "github")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(org.Name)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	orgs, _, err := client.Organizations.List(ctx, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, org := range orgs {
		log.Println(org.Name)
	}
}
Output:

type OrganizationService

type OrganizationService interface {
	// Find returns the organization by name.
	Find(ctx context.Context, name string) (*Organization, *Response, error)

	// FindMembership returns the organization membership
	// by a given user account.
	FindMembership(ctx context.Context, name, username string) (*Membership, *Response, error)

	// List returns the user organization list.
	List(ctx context.Context, opts ListOptions) ([]*Organization, *Response, error)
}

OrganizationService provides access to organization resources.

type Page

type Page struct {
	Next    int
	NextURL string
	Last    int
	First   int
	Prev    int
}

Page represents parsed link rel values for pagination.

type Perm

type Perm struct {
	Pull  bool
	Push  bool
	Admin bool
}

Perm represents a user's repository permissions.

type PullRequest

type PullRequest struct {
	Number  int
	Title   string
	Body    string
	Sha     string
	Ref     string
	Source  string
	Target  string
	Fork    string
	Link    string
	Diff    string
	Closed  bool
	Merged  bool
	Base    Reference
	Head    Reference
	Author  User
	Created time.Time
	Updated time.Time
	Labels  []Label
}

PullRequest represents a repository pull request.

Example (Changes)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	changes, _, err := client.PullRequests.ListChanges(ctx, "octocat/Hello-World", 1, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, change := range changes {
		log.Println(change.Path, change.Added, change.Deleted, change.Renamed)
	}
}
Output:

Example (Close)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.PullRequests.Close(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	pr, _, err := client.PullRequests.Find(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(pr.Number, pr.Title)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.PullRequestListOptions{
		Page:   1,
		Size:   30,
		Open:   true,
		Closed: false,
	}

	prs, _, err := client.PullRequests.List(ctx, "octocat/Hello-World", opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, pr := range prs {
		log.Println(pr.Number, pr.Title)
	}
}
Output:

Example (Merge)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.PullRequests.Merge(ctx, "octocat/Hello-World", 1)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

type PullRequestCommentHook

type PullRequestCommentHook struct {
	Action      Action
	Repo        Repository
	PullRequest PullRequest
	Comment     Comment
	Sender      User
}

PullRequestCommentHook represents an pull request comment event, eg pull_request_comment.

func (*PullRequestCommentHook) Repository

func (h *PullRequestCommentHook) Repository() Repository

type PullRequestHook

type PullRequestHook struct {
	Action      Action
	Repo        Repository
	PullRequest PullRequest
	Sender      User
}

PullRequestHook represents an pull request event, eg pull_request.

func (*PullRequestHook) Repository

func (h *PullRequestHook) Repository() Repository

type PullRequestInput

type PullRequestInput struct {
	Title  string
	Body   string
	Source string
	Target string
}

PullRequestInput provides the input fields required for creating a pull request.

type PullRequestListOptions

type PullRequestListOptions struct {
	Page   int
	Size   int
	Open   bool
	Closed bool
}

PullRequestListOptions provides options for querying a list of repository merge requests.

type PullRequestService

type PullRequestService interface {
	// Find returns the repository pull request by number.
	Find(context.Context, string, int) (*PullRequest, *Response, error)

	// FindComment returns the pull request comment by id.
	FindComment(context.Context, string, int, int) (*Comment, *Response, error)

	// Find returns the repository pull request list.
	List(context.Context, string, PullRequestListOptions) ([]*PullRequest, *Response, error)

	// ListChanges returns the pull request changeset.
	ListChanges(context.Context, string, int, ListOptions) ([]*Change, *Response, error)

	// ListComments returns the pull request comment list.
	ListComments(context.Context, string, int, ListOptions) ([]*Comment, *Response, error)

	// Merge merges the repository pull request.
	Merge(context.Context, string, int) (*Response, error)

	// Close closes the repository pull request.
	Close(context.Context, string, int) (*Response, error)

	// Create creates a new pull request.
	Create(context.Context, string, *PullRequestInput) (*PullRequest, *Response, error)

	// CreateComment creates a new pull request comment.
	CreateComment(context.Context, string, int, *CommentInput) (*Comment, *Response, error)

	// DeleteComment deletes an pull request comment.
	DeleteComment(context.Context, string, int, int) (*Response, error)
}

PullRequestService provides access to pull request resources.

type PushHook

type PushHook struct {
	Ref     string
	BaseRef string
	Repo    Repository
	Before  string
	After   string
	Commit  Commit
	Sender  User
	Commits []Commit
}

PushHook represents a push hook, eg push events.

func (*PushHook) Repository

func (h *PushHook) Repository() Repository

type Rate

type Rate struct {
	Limit     int
	Remaining int
	Reset     int64
}

Rate represents the rate limit for the current client.

type Reference

type Reference struct {
	Name string
	Path string
	Sha  string
}

Reference represents a git reference.

type Repository

type Repository struct {
	ID        string
	Namespace string
	Name      string
	Perm      *Perm
	Branch    string
	Private   bool
	Clone     string
	CloneSSH  string
	Link      string
	Created   time.Time
	Updated   time.Time
}

Repository represents a git repository.

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	repo, _, err := client.Repositories.Find(ctx, "octocat/Hello-World")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(repo.Namespace, repo.Name)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	repos, _, err := client.Repositories.List(ctx, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, repo := range repos {
		log.Println(repo.Namespace, repo.Name)
	}
}
Output:

type RepositoryService

type RepositoryService interface {
	// Find returns a repository by name.
	Find(context.Context, string) (*Repository, *Response, error)

	// FindHook returns a repository hook.
	FindHook(context.Context, string, string) (*Hook, *Response, error)

	// FindPerms returns repository permissions.
	FindPerms(context.Context, string) (*Perm, *Response, error)

	// List returns a list of repositories.
	List(context.Context, ListOptions) ([]*Repository, *Response, error)

	// ListHooks returns a list or repository hooks.
	ListHooks(context.Context, string, ListOptions) ([]*Hook, *Response, error)

	// ListStatus returns a list of commit statuses.
	ListStatus(context.Context, string, string, ListOptions) ([]*Status, *Response, error)

	// CreateHook creates a new repository hook.
	CreateHook(context.Context, string, *HookInput) (*Hook, *Response, error)

	// CreateStatus creates a new commit status.
	CreateStatus(context.Context, string, string, *StatusInput) (*Status, *Response, error)

	// UpdateHook updates an existing repository hook.
	UpdateHook(context.Context, string, string, *HookInput) (*Hook, *Response, error)

	// DeleteHook deletes a repository hook.
	DeleteHook(context.Context, string, string) (*Response, error)
}

RepositoryService provides access to repository resources.

type Request

type Request struct {
	Method string
	Path   string
	Header http.Header
	Body   io.Reader
}

Request represents an HTTP request.

type Response

type Response struct {
	ID     string
	Status int
	Header http.Header
	Body   io.ReadCloser

	Page Page // Page values
	Rate Rate // Rate limit snapshot
}

Response represents an HTTP response.

type Review

type Review struct {
	ID      int
	Body    string
	Path    string
	Sha     string
	Line    int
	Link    string
	Author  User
	Created time.Time
	Updated time.Time
}

Review represents a review comment.

Example (Create)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	in := &scm.ReviewInput{
		Line: 38,
		Path: "main.go",
		Body: "Run gofmt please",
	}

	review, _, err := client.Reviews.Create(ctx, "octocat/Hello-World", 1, in)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(review.ID)
}
Output:

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	review, _, err := client.Reviews.Find(ctx, "octocat/Hello-World", 1, 1)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(
		review.Path,
		review.Line,
		review.Body,
	)
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	reviews, _, err := client.Reviews.List(ctx, "octocat/Hello-World", 1, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, review := range reviews {
		log.Println(
			review.Path,
			review.Line,
			review.Body,
		)
	}
}
Output:

type ReviewCommentHook

type ReviewCommentHook struct {
	Action      Action
	Repo        Repository
	PullRequest PullRequest
	Review      Review
}

ReviewCommentHook represents a pull request review comment, eg pull_request_review_comment.

func (*ReviewCommentHook) Repository

func (h *ReviewCommentHook) Repository() Repository

type ReviewInput

type ReviewInput struct {
	Body string
	Sha  string
	Path string
	Line int
}

ReviewInput provides the input fields required for creating a review comment.

type ReviewService

type ReviewService interface {
	// Find returns the review comment by id.
	Find(context.Context, string, int, int) (*Review, *Response, error)

	// List returns the review comment list.
	List(context.Context, string, int, ListOptions) ([]*Review, *Response, error)

	// Create creates a review comment.
	Create(context.Context, string, int, *ReviewInput) (*Review, *Response, error)

	// Delete deletes a review comment.
	Delete(context.Context, string, int, int) (*Response, error)
}

ReviewService provides access to review resources.

type Role

type Role int

Role defines membership roles.

const (
	RoleUndefined Role = iota
	RoleMember
	RoleAdmin
)

Role values.

func (Role) String

func (r Role) String() (s string)

String returns the string representation of Role.

type SecretFunc

type SecretFunc func(webhook Webhook) (string, error)

SecretFunc provides the Webhook parser with the secret key used to validate webhook authenticity.

type Signature

type Signature struct {
	Name  string
	Email string
	Date  time.Time

	// Fields are optional. The provider may choose to
	// include account information in the response.
	Login  string
	Avatar string
}

Signature identifies a git commit creator.

type State

type State int

State represents the commit state.

const (
	StateUnknown State = iota
	StatePending
	StateRunning
	StateSuccess
	StateFailure
	StateCanceled
	StateError
)

State values.

type Status

type Status struct {
	State  State
	Label  string
	Desc   string
	Target string

	// TODO(bradrydzewski) this field is only used
	// by Bitbucket which requires a user-defined
	// key (label), title and description. We need
	// to cleanup this abstraction.
	Title string
}

Status represents a commit status.

Example (Create)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	input := &scm.StatusInput{
		State:  scm.StateSuccess,
		Label:  "continuous-integation",
		Desc:   "Build has completed successfully",
		Target: "https://ci.example.com/octocat/hello-world/1",
	}

	_, _, err = client.Repositories.CreateStatus(ctx, "octocat/Hello-World", "6dcb09b5b57875f334f61aebed695e2e4193db5e", input)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (List)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	opts := scm.ListOptions{
		Page: 1,
		Size: 30,
	}

	statuses, _, err := client.Repositories.ListStatus(ctx, "octocat/Hello-World", "6dcb09b5b57875f334f61aebed695e2e4193db5e", opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, status := range statuses {
		log.Println(status.State, status.Target)
	}
}
Output:

type StatusInput

type StatusInput struct {
	State  State
	Label  string
	Title  string
	Desc   string
	Target string
}

StatusInput provides the input fields required for creating or updating commit statuses.

type TagHook

type TagHook struct {
	Ref    Reference
	Repo   Repository
	Action Action
	Sender User
}

TagHook represents a tag event, eg create and delete github event types.

func (*TagHook) Repository

func (h *TagHook) Repository() Repository

type Token

type Token struct {
	Token   string
	Refresh string
	Expires time.Time
}

Token represents the credentials used to authorize the requests to access protected resources.

type TokenKey

type TokenKey struct{}

TokenKey is the key to use with the context.WithValue function to associate an Token value with a context.

type TokenSource

type TokenSource interface {
	Token(context.Context) (*Token, error)
}

TokenSource returns a token.

type User

type User struct {
	Login   string
	Name    string
	Email   string
	Avatar  string
	Created time.Time
	Updated time.Time
}

User represents a user account.

Example (Find)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	user, _, err := client.Users.Find(ctx)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(user.Login)
}
Output:

Example (FindLogin)
package main

import (
	"context"
	"log"

	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var ctx context.Context

func main() {
	client, err := github.New("https://api.github.com")
	if err != nil {
		log.Fatal(err)
	}

	user, _, err := client.Users.FindLogin(ctx, "octocat")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(user.Login)
}
Output:

type UserService

type UserService interface {
	// Find returns the authenticated user.
	Find(context.Context) (*User, *Response, error)

	// FindEmail returns the authenticated user email.
	FindEmail(context.Context) (string, *Response, error)

	// FindLogin returns the user account by username.
	FindLogin(context.Context, string) (*User, *Response, error)
}

UserService provides access to user account resources.

type Webhook

type Webhook interface {
	Repository() Repository
}

Webhook defines a webhook for repository events.

Example
package main

import (
	"log"
	"net/http"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

func main() {
	client := github.NewDefault()

	secret := func(webhook scm.Webhook) (string, error) {
		return "topsecret", nil
	}

	handler := func(w http.ResponseWriter, r *http.Request) {
		webhook, err := client.Webhooks.Parse(r, secret)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		switch event := webhook.(type) {
		case *scm.PushHook:
			log.Println(
				event.Ref,
				event.Commit.Sha,
				event.Commit.Message,
				event.Repo.Namespace,
				event.Repo.Name,
				event.Sender.Login,
			)
		case *scm.BranchHook:
		case *scm.TagHook:
		case *scm.IssueHook:
		case *scm.IssueCommentHook:
		case *scm.PullRequestHook:
		case *scm.PullRequestCommentHook:
		case *scm.ReviewCommentHook:
		}
	}

	http.HandleFunc("/hook", handler)
	http.ListenAndServe(":8000", nil)
}
Output:

Example (LookupSecret)
package main

import (
	"database/sql"
	"log"
	"net/http"

	"github.com/ozonep/drone/pkg/scm"
	"github.com/ozonep/drone/pkg/scm/driver/github"
)

var db *sql.DB

func main() {
	client := github.NewDefault()

	secret := func(webhook scm.Webhook) (secret string, err error) {
		stmt := "SELECT secret FROM repos WHERE id = ?"
		repo := webhook.Repository()
		err = db.QueryRow(stmt, repo.ID).Scan(&secret)
		return
	}

	handler := func(w http.ResponseWriter, r *http.Request) {
		webhook, err := client.Webhooks.Parse(r, secret)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		switch event := webhook.(type) {
		case *scm.PushHook:
			log.Println(
				event.Ref,
				event.Commit.Sha,
				event.Commit.Message,
				event.Repo.Namespace,
				event.Repo.Name,
				event.Sender.Login,
			)
		}
	}

	http.HandleFunc("/hook", handler)
	http.ListenAndServe(":8000", nil)
}
Output:

type WebhookService

type WebhookService interface {
	// Parse returns the parsed the repository webhook payload.
	Parse(req *http.Request, fn SecretFunc) (Webhook, error)
}

WebhookService provides abstract functions for parsing and validating webhooks requests.

Directories

Path Synopsis
driver
bitbucket
Package bitbucket implements a Bitbucket Cloud client.
Package bitbucket implements a Bitbucket Cloud client.
bitbucket/integration
Package integration implements a Bitbucket Cloud integration tests.
Package integration implements a Bitbucket Cloud integration tests.
gitea
Package gitea implements a Gitea client.
Package gitea implements a Gitea client.
github
Package github implements a GitHub client.
Package github implements a GitHub client.
gitlab
Package gitlab implements a GitLab client.
Package gitlab implements a GitLab client.
gogs
Package gogs implements a Gogs client.
Package gogs implements a Gogs client.
stash
Package stash implements a Bitbucket Server client.
Package stash implements a Bitbucket Server client.
Package transport provides facilities for setting up authenticated http.RoundTripper given credentials and base RoundTripper.
Package transport provides facilities for setting up authenticated http.RoundTripper given credentials and base RoundTripper.

Jump to

Keyboard shortcuts

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