github

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MergeStateStatusBehind and other
	// values correspond to enum values for the field pr.MergeStateStatus
	// https://docs.github.com/en/graphql/reference/enums#mergestatestatus
	MergeStateStatusBehind   = "BEHIND"
	MergeStateStatusBlocked  = "BLOCKED"
	MergeStateStatusClosed   = "CLOSED"
	MergeStateStatusClean    = "CLEAN"
	MergeStateStatusDirty    = "DIRTY"
	MergeStateStatusHasHooks = "HAS_HOOKS"
	MergeStateStatusMerged   = "MERGED"
	MergeStateStatusUnstable = "UNSTABLE"

	MergedState   PRMergeState = "MERGED"
	EnqueuedState PRMergeState = "ENQUEUED"
	ClosedState   PRMergeState = "CLOSED"
	UnknownState  PRMergeState = "UNKNOWN"
	BlockedState  PRMergeState = "BLOCKED"
)
View Source
const (
	// GitHubAppUsername is the username used by GitHub App's for basic auth.
	GitHubAppUsername = "x-access-token"
)

Variables

View Source
var ErrAlreadyInMergeQueue = errors.New("already in merge queue")

ErrAlreadyInMergeQueue indicates that the pull request is already in a merge queue

Functions

func GetInstallID

func GetInstallID(appID int64, privateKey []byte, owner string, repo string) (int64, error)

GetInstallID returns the installation id for the specified GitHubApp. privateKey should be the contents of the private key.

func GitHubRepoToURI added in v0.0.5

func GitHubRepoToURI(repo v1alpha1.GitHubRepo) url.URL

GitHubRepoToURI converts a GitHubRepo to a URI in the gogetter form. It assumes the protocol is https.

Types

type AppAuth

type AppAuth struct {
	Tr *ghinstallation.Transport
}

AppAuth implements BasicAuth for GitHub Apps for use with GoGit. When authenticating as a GitHub App, we need to use basic auth with the username "x-access-token"

Reference: https://github.com/go-git/go-git/blob/c798d4a42004b1c8976a6a4f42f131f16d08b6fa/plumbing/transport/http/common.go#L191

We also need to generate an appropriate token to use as the password. Since the token can expire we can't use the existing BasicAuth.

It is similar to go-git's BasicAuth. https://github.com/go-git/go-git/blob/c798d4a42004b1c8976a6a4f42f131f16d08b6fa/plumbing/transport/http/common.go#L191

func (*AppAuth) Name

func (a *AppAuth) Name() string

Name is name of the auth method.

func (*AppAuth) SetAuth

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

SetAuth adds the appropriate authentication headers to the request.

func (*AppAuth) String

func (a *AppAuth) String() string

String returns a sanitized string suitable for log messages.

type EnablePullRequestAutoMergeInput

type EnablePullRequestAutoMergeInput struct {
	githubv4.MergePullRequestInput
}

TODO: drop after githubv4 gets updated

type MergeOptions

type MergeOptions struct {
	HttpClient *http.Client
	// The number for the PR
	PRNumber int
	Repo     ghrepo.Interface
}

MergeOptions are the options used to construct a context.

type PRMergeState

type PRMergeState string

PRMergeState is different states the PR can be in. It aggregates information from multiple fields in the GitHub API (e.g. pr.State and pr.MergeStateStatus and pr.IsInMergeQueue)

func MergePR

func MergePR(client *http.Client, repo ghrepo.Interface, number int) (PRMergeState, error)

MergePR merges a PR. client - http client to use to talk to github repo - the repo that owns the PR number - the PR number to merge

type Proxy

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

Proxy is a proxy server for GitHub. It proxies http requests using a GitHub app's credentials. This makes it easy to fetch documents from private repositories.

N.B jeremy@ tried using the gin framework but couldn't figure out how to properly handle path prefixes. I tried using NoRoute and overriding the not found handler but the response code was always 404.

func NewProxy

func NewProxy(m *TransportManager, log logr.Logger, port string) (*Proxy, error)

NewProxy constructs a new server.

func (*Proxy) Address

func (f *Proxy) Address() string

Address returns the address the server is listening on.

func (*Proxy) HealthCheck

func (f *Proxy) HealthCheck(w http.ResponseWriter, r *http.Request)

HealthCheck handles a health check

func (*Proxy) NotFoundHandler

func (f *Proxy) NotFoundHandler(w http.ResponseWriter, r *http.Request)

NotFoundHandler is a custom not found handler A custom not found handler is useful for determining whether a 404 is coming because of an issue with ISTIO not hitting the server or the request is hitting the server but the path is wrong.

func (*Proxy) Serve

func (f *Proxy) Serve() error

Serve starts the server this is blocking.

type PullRequest

type PullRequest struct {
	ID          string
	Number      int
	Title       string
	State       string
	Closed      bool
	URL         string
	BaseRefName string
	HeadRefName string
	Body        string
	Mergeable   string

	Author struct {
		Login string
	}
	HeadRepositoryOwner struct {
		Login string
	}
	HeadRepository struct {
		Name             string
		DefaultBranchRef struct {
			Name string
		}
	}
	IsCrossRepository   bool
	IsDraft             bool
	MaintainerCanModify bool

	ReviewDecision string

	Commits struct {
		TotalCount int
		Nodes      []struct {
			Commit struct {
				StatusCheckRollup struct {
					Contexts struct {
						Nodes []struct {
							State      string
							Status     string
							Conclusion string
						}
					}
				}
			}
		}
	}
	ReviewRequests struct {
		Nodes []struct {
			RequestedReviewer struct {
				TypeName string `json:"__typename"`
				Login    string
				Name     string
			}
		}
		TotalCount int
	}
	Reviews struct {
		Nodes []struct {
			Author struct {
				Login string
			}
			State string
		}
	}
	Assignees struct {
		Nodes []struct {
			Login string
		}
		TotalCount int
	}
	Labels struct {
		Nodes []struct {
			Name string
		}
		TotalCount int
	}
	ProjectCards struct {
		Nodes []struct {
			Project struct {
				Name string
			}
			Column struct {
				Name string
			}
		}
		TotalCount int
	}
	Milestone struct {
		Title string
	}
}

PullRequest is a struct for representing PRs. This was largely copied from GitHub's CLI.

func (PullRequest) HeadLabel

func (pr PullRequest) HeadLabel() string

HeadLabel returns the label for the head reference.

type RepoHelper

type RepoHelper struct {
	BranchName string
	BaseBranch string
	// contains filtered or unexported fields
}

RepoHelper manages the local and remote operations involved in creating a PR. RepoHelper is used to create a local working version of a repository where files can be modified. Once those files have been modified they can be pushed to the remote repository and a PR can be created

TODO(jeremy): the code currently assumes the PR is created from a branch in the repository as opposed to creating the PR from a fork. We should update the code to support using a fork.

TODO(https://github.com/jlewi/hydros/issues/2): Migrage to github.com/shurcooL/githubv4 The functions CreatePR and PullRequestForBranch are inspired by the higher level API in GitHub's GoLang CLI. A lot of the code is modified from that.

We don't use the CLI. The CLI authors suggested (https://github.com/cli/cli/issues/1327) that it would be better to use the API client libraries directly; github.com/shurcooL/githubv4. The CLI API is providing higher level functions ontop of the underlying GraphQL API; originally it seemed silly to redo that rather than just import it and reuse it. https://github.com/cli/cli/blob/4d28c791921621550f19a4c6bcc13778a7525025/api/queries_pr.go. However, I think the CLI pulls in some dependencies (BlueMonday?) that we'd like to avoid pulling in if we can so that's a good reason to try to migrate of the CLI package.

func NewGithubRepoHelper

func NewGithubRepoHelper(args *RepoHelperArgs) (*RepoHelper, error)

NewGithubRepoHelper creates a helper for a specific repository. transport - must be a transport configured with permission to access the referenced repository. baseRepo - the repository to access.

func (*RepoHelper) BranchRef

func (h *RepoHelper) BranchRef() plumbing.ReferenceName

BranchRef returns reference to the branch we created

func (*RepoHelper) CommitAndPush

func (h *RepoHelper) CommitAndPush(message string, force bool) error

CommitAndPush and push commits and pushes all the working changes

NullOp if nothing to commit.

force means the remote branch will be overwritten if it isn't in sync.

func (*RepoHelper) CreatePr

func (h *RepoHelper) CreatePr(prMessage string, labels []string) (*api.PullRequest, error)

CreatePr creates a pull request baseBranch the branch into which your code should be merged. forkRef the reference to the fork from which to create the PR

Forkref will either be OWNER:BRANCH when a different repository is used as the fork.
or it will be just BRANCH when merging from a branch in the same Repo as Repo

func (*RepoHelper) Dir

func (h *RepoHelper) Dir() string

Dir returns the directory of the repository.

func (*RepoHelper) Email

func (h *RepoHelper) Email() string

Email returns the value of email used by this repohelper.

func (*RepoHelper) FetchPR

func (h *RepoHelper) FetchPR(prNumber int) (*api.PullRequest, error)

func (*RepoHelper) HasChanges

func (h *RepoHelper) HasChanges() (bool, error)

HasChanges returns true if there are changes to be committed.

func (*RepoHelper) Head

func (h *RepoHelper) Head() (*plumbing.Reference, error)

Head returns the reference of the head commit of the branch.

func (*RepoHelper) MergeAndWait

func (h *RepoHelper) MergeAndWait(prNumber int, timeout time.Duration) (PRMergeState, error)

MergeAndWait merges the PR and waits for it to be merged.

func (*RepoHelper) MergePR

func (h *RepoHelper) MergePR(prNumber int) (PRMergeState, error)

MergePR tries to merge the PR. This means either 1. enabling auto merge if a merge queue is required 2. merging right away if able

func (*RepoHelper) PrepareBranch

func (h *RepoHelper) PrepareBranch(dropChanges bool) error

PrepareBranch prepares a branch. This will do the following 1. Clone the repository if it hasn't already been cloned 2. Create a branch if one doesn't already exist.

If dropChanges is true if the working tree is dirty the changes will be ignored.

if the tree is dirty and dropChanges is false then an error is returned because we can't check out the local
branch.

Typically PrepareBranch should be called with dropChanges=true.

If a local branch already exists it will be deleted and the local branch will be recreated from the latest baseBranch. This is to ensure the branch is created from the latest code on the base branch.

N.B the semantics are based on how hydros and similar automation is expected to work. Each time hydros runs hydrate it should run on the head commit of the baseBranch. So if a local/remote branch already exists it represents a previous sync and we want to completely override it. When a hydros sync successfully runs it should result in a PR. The existence of the PR should be used to block hydros from recreating or otherwise modifying the branch until the PR is merged or closed. These semantics are designed to allow humans to interact with the PR and potentially edit it before merging.

func (*RepoHelper) PullRequestForBranch

func (h *RepoHelper) PullRequestForBranch() (*PullRequest, error)

PullRequestForBranch returns the PR for the given branch if it exists and nil if no PR exists. TODO(jeremy): Can we change this to api.PullRequest?

func (*RepoHelper) RemoteBaseRef

func (h *RepoHelper) RemoteBaseRef() plumbing.ReferenceName

RemoteBaseRef returns the remote base reference. Per https://git-scm.com/book/en/v2/Git-Internals-The-Refspec This is the local copy of the remote branch.

type RepoHelperArgs

type RepoHelperArgs struct {
	// BaseRepo is the repository from which the branch is created. This is also the repository used to create the PR.
	BaseRepo ghrepo.Interface
	// GhTr is the GitHub transport used to authenticate as a GitHub App. If nil a transport will not be used.
	GhTr    *ghinstallation.Transport
	FullDir string
	// Name is the name attached to commits.
	Name string
	// Email is the email attached to commits
	Email string
	// Remote is the name to use for the remote repository.
	// Defaults to origin
	Remote string

	// BranchName is the name for the branch to be created
	BranchName string

	// BaseBranch is the name of the branch to use as the base.
	// This is all the branch to which the PR will be merged
	BaseBranch string
}

RepoHelperArgs is the arguments used to instantiate the object.

type ReposCloner

type ReposCloner struct {
	// List of repositories to clone
	URIs    []string
	Manager *TransportManager
	BaseDir string
}

ReposCloner clones a set of repositories

TODO(jeremy): This is currently GitHub specific we should change that TODO(jeremy): How do we support public repositories? right now it always uses the app auth.

func (*ReposCloner) GetRepoDir added in v0.0.3

func (r *ReposCloner) GetRepoDir(uri string) (string, error)

GetRepoDir the directory where the repository will be cloned

func (*ReposCloner) Run

func (r *ReposCloner) Run(ctx context.Context) error

Run clones the repository. If the repository has already been cloned then it will fetch the latest changes and checkout the specified branch. Any changes are dropped.

type TransportManager

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

TransportManager manages transport managers for a GitHub App. The manager is instantiated with the app ID and private key for a GitHub App. The Get function can then be used to obtain a transport with credentials to talk to a particular repository that the app has access to

TODO(jeremy): Can/should we wrap this in the OAuth flow. TODO(jeremy): Should we reuse some of palantir built? https://github.com/palantir/go-githubapp/blob/develop/githubapp/client_creator.go

func NewTransportManager

func NewTransportManager(appID int64, privateKey []byte, log logr.Logger) (*TransportManager, error)

NewTransportManager creates a new transport manager.

func (*TransportManager) Get

Get returns a transport to talk to the specified Org and Repo.

Directories

Path Synopsis
package ghrepo is a copy of https://github.com/cli/cli/tree/trunk/internal/ghrepo
package ghrepo is a copy of https://github.com/cli/cli/tree/trunk/internal/ghrepo

Jump to

Keyboard shortcuts

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