thirdparty

package
v0.0.0-...-6be7acf Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 43 Imported by: 74

Documentation

Overview

Package thirdparty defines interactions with third-party services but not cloud providers, which are in cloud.

Index

Constants

View Source
const (
	Github502Error = "502 Server Error"

	GithubInvestigation        = "Github API Limit Investigation"
	PRDiffTooLargeErrorMessage = "the diff exceeded the maximum"
	GithubStatusDefaultContext = "evergreen"
)
View Source
const (
	GithubPermissionRead  = "read"
	GithubPermissionWrite = "write"
	GithubPermissionAdmin = "admin"
)
View Source
const (
	// GitHub merge queue removal reasons
	MergeQueueReasonInvalidated = "invalidated" // Status checks failed
	MergeQueueReasonMerged      = "merged"      // Successfully merged

	// Merge queue status values for metrics
	MergeQueueStatusSuccess = "success" // Successfully completed/merged
	MergeQueueStatusFailed  = "failed"  // Failed status checks
	MergeQueueStatusRemoved = "removed" // Other removal reasons
)
View Source
const (
	APITypeOS         = "OS"
	APITypePackages   = "Packages"
	APITypeToolchains = "Toolchains"
	APITypeFiles      = "Files"
)
View Source
const GitOperationTimeout = 15 * time.Second

GitOperationTimeout is the maximum time to wait for a git operation to complete.

View Source
const MaxGitHubPRFilesListLength = 3000

MaxGitHubPRFilesListLength is the maximum number of files that can be returned by the GitHub API for a pull request. This is a hard limit imposed by the GitHub API. If the PR changes more than 3000 files, Evergreen will only see at most 3000 of them.

View Source
const TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token"

TokenTypeAccessToken is the RFC 8693 URN for an OAuth access token used as subject_token_type.

Variables

View Source
var (
	// BSON fields for GithubPatch
	GithubPatchPRNumberKey    = bsonutil.MustHaveTag(GithubPatch{}, "PRNumber")
	GithubPatchBaseOwnerKey   = bsonutil.MustHaveTag(GithubPatch{}, "BaseOwner")
	GithubPatchBaseRepoKey    = bsonutil.MustHaveTag(GithubPatch{}, "BaseRepo")
	RepeatPatchIdNextPatchKey = bsonutil.MustHaveTag(GithubPatch{}, "RepeatPatchIdNextPatch")
	GithubPatchLabelsKey      = bsonutil.MustHaveTag(GithubPatch{}, "Labels")
	GithubPatchHeadHashKey    = bsonutil.MustHaveTag(GithubPatch{}, "HeadHash")
)

Functions

func AppAuthorizedForOrg

func AppAuthorizedForOrg(ctx context.Context, requiredOrganization string, userID int) (bool, error)

AppAuthorizedForOrg returns true if the given GitHub account ID belongs to an app in the org's installation list with permission to write to pull requests. Returns an error if the app is installed but lacks permission.

func BuildGithubHeadPRURL

func BuildGithubHeadPRURL(org, repo, headRef string) string

BuildGithubHeadPRURL constructs the GitHub PR URL for the HEAD PR from a merge queue head ref. For merge queue entries, this returns the HEAD PR URL, not all PRs in the merge group. Returns empty string if the PR number cannot be extracted from headRef.

func CheckGithubAPILimit

func CheckGithubAPILimit(ctx context.Context, owner, repo string, ghAppAuth *githubapp.GithubAppAuth) (*github.RateLimits, error)

CheckGithubAPILimit queries Github for all the API rate limits for the given app. If no app/owner/repo is specified, it queries the Evergreen internal app's rate limit.

func CheckGithubResource

func CheckGithubResource(ctx context.Context) (int64, error)

CheckGithubResource queries Github for the number of API requests remaining

func CreateCheckRun

func CreateCheckRun(ctx context.Context, owner, repo, headSHA, uiBase string, task *task.Task, output *github.CheckRunOutput, ghAppAuth *githubapp.GithubAppAuth) (*github.CheckRun, error)

CreateCheckRun creates a checkRun and returns a Github CheckRun object. If ghAppAuth is provided, it will use the project's GitHub app credentials. If the external app fails, the error is returned without falling back to the internal app.

func ExchangeAuthCodeForToken

func ExchangeAuthCodeForToken(ctx context.Context, opts AuthCodeExchangeOptions) (string, error)

ExchangeAuthCodeForToken exchanges an OAuth 2.0 authorization code for an access token using the Authorization Code + PKCE flow. It returns just the access token string.

func ExchangeOktaToken

func ExchangeOktaToken(ctx context.Context, opts OktaTokenExchangeOptions) (*oauth2.Token, error)

ExchangeOktaToken performs an OAuth 2.0 Token Exchange (RFC 8693) against Okta. It resolves the token endpoint from the process-wide cache or via OAuth Authorization Server Metadata discovery (RFC 8414), then exchanges the provided subject token for a new token using client credentials.

func FormGitURL

func FormGitURL(owner, repo, token string) string

func FormGitURLForApp

func FormGitURLForApp(owner, repo, token string) string

func GetBranchProtectionRules

func GetBranchProtectionRules(ctx context.Context, owner, repo, branch string) ([]string, error)

GetBranchProtectionRules gets all branch protection checks as a list of strings.

func GetCheckRun

func GetCheckRun(ctx context.Context, owner, repo string, checkRunID int64) (*github.CheckRun, error)

GetCheckRun gets a check run by ID

func GetCommitComparisonStatus

func GetCommitComparisonStatus(ctx context.Context, owner, repo, baseRevision, headRevision string) (string, error)

GetCommitComparisonStatus returns how headRevision compares to baseRevision in a GitHub repo, which is one of "ahead", "behind", "identical", or "diverged".

func GetCommitEvent

func GetCommitEvent(ctx context.Context, owner, repo, githash string) (*github.RepositoryCommit, error)

func GetEvergreenBranchProtectionRules

func GetEvergreenBranchProtectionRules(ctx context.Context, owner, repo, branch string) ([]string, error)

GetEvergreenBranchProtectionRules gets all Evergreen branch protection checks as a list of strings.

func GetEvergreenRulesetRules

func GetEvergreenRulesetRules(ctx context.Context, owner, repo, branch string) ([]string, error)

GetEvergreenRulesetRules gets all Evergreen rules from rulesets as a list of strings. This may return duplicate rules.

func GetGitHubFileContent

func GetGitHubFileContent(ctx context.Context, owner, repo, ref, path, worktree string, ghAppAuth *githubapp.GithubAppAuth, useGit bool) ([]byte, error)

GetGitHubFileContent returns the contents of a file within a GitHub repository. If useGit is specified, it will attempt to retrieve the file using git first. If that fails, it will fall back to retrieving it from the GitHub API.

Caller should prefer to call this instead of GetGithubFile because if the file can be retrieved with git, it reduces the amount of GitHub API calls.

func GetGitHubFileFromGit

func GetGitHubFileFromGit(ctx context.Context, owner, repo, ref, file, worktree string) ([]byte, error)

GetGitHubFileFromGit retrieves a single file's contents from GitHub using git. If a worktree is specified, it will retrieve the file using that preloaded git worktree. Ref must be a commit hash or branch.

func GetGitHubUserByID

func GetGitHubUserByID(ctx context.Context, userID int) (*github.User, error)

GetGitHubUserByID fetches the GitHub user with the given immutable account ID.

func GetGithubCommits

func GetGithubCommits(ctx context.Context, owner, repo string, opts *github.CommitsListOptions) ([]*github.RepositoryCommit, int, error)

GetGithubCommits returns a slice of GithubCommit objects from the given commitsURL when provided a valid oauth token

func GetGithubFile

func GetGithubFile(ctx context.Context, owner, repo, path, ref string, ghAppAuth *githubapp.GithubAppAuth) (*github.RepositoryContent, error)

GetGithubFile returns a struct that contains the contents of files within a repository as Base64 encoded content. Ref should be the commit hash or branch (defaults to master).

Callers should generally prefer GetGitHubFileContent when possible because it reduces the number of GitHub API calls made.

func GetGithubMergeBaseRevision

func GetGithubMergeBaseRevision(ctx context.Context, owner, repo, baseRevision, currentCommitHash string) (string, error)

GetGithubMergeBaseRevision compares baseRevision and currentCommitHash in a GitHub repo and returns the merge base commit's SHA.

func GetGithubPullRequest

func GetGithubPullRequest(ctx context.Context, baseOwner, baseRepo string, prNumber int) (*github.PullRequest, error)

func GetGithubUser

func GetGithubUser(ctx context.Context, loginName string) (*github.User, error)

GetGithubUser fetches the github user with the given login name

func GetMergeQueueFrontEntry

func GetMergeQueueFrontEntry(ctx context.Context, owner, repo, baseBranch string) (headRef, headSHA string, ok bool, err error)

GetMergeQueueFrontEntry returns the head ref and head commit SHA of the merge group at the front of the GitHub merge queue (queue position 1) for the given branch. It returns ok=false if the queue is currently empty. There is no REST API with a notion of queue position, so this queries the GraphQL API's mergeQueue.entries field instead, which is position-ordered.

func GetMergeQueueStatusFromReason

func GetMergeQueueStatusFromReason(reason string) string

GetMergeQueueStatusFromReason maps a GitHub merge queue removal reason to a status value for metrics.

func GetPullRequestMergeBase

func GetPullRequestMergeBase(ctx context.Context, pr *github.PullRequest) (string, error)

GetPullRequestMergeBase returns the merge base hash for the given PR.

func GetRulesetRules

func GetRulesetRules(ctx context.Context, owner, repo, branch string) ([]string, error)

GetRulesetRules returns all active rules from rulesets that apply to a branch as a list of strings. This may return duplicate rules.

func GetTaggedCommitFromGithub

func GetTaggedCommitFromGithub(ctx context.Context, owner, repo, tag string) (string, error)

GetTaggedCommitFromGithub gets the commit SHA for the given tag name.

func GitApplyNumstat

func GitApplyNumstat(patch string) (*bytes.Buffer, error)

GitApplyNumstat attempts to apply a given patch; it returns the patch's bytes if it is successful

func GitCloneMinimal

func GitCloneMinimal(ctx context.Context, owner, repo, revision string) (string, error)

GitCloneMinimal performs a minimal git clone of a repository using the GitHub app. The minimal clone contains only git metadata for the one revision and has no file content. Callers are expected to clean up the returned git directory when it is no longer needed.

func GitCreateWorktree

func GitCreateWorktree(ctx context.Context, gitDir, worktreeDir string) error

GitCreateWorktree creates a new git worktree in worktreeDir based on gitDir. It does not perform a checkout. Callers are assumed to have already cloned the repo into gitDir and HEAD is assumed to be already pointing to the desired revision.

func GitHubUserHasReadPermission

func GitHubUserHasReadPermission(ctx context.Context, owner, repo, username string) (bool, error)

GitHubUserHasReadPermission returns true if the given user can read the repo. Returns an error if the user isn't found or the token isn't authed for this repo.

func GitHubUserHasWritePermission

func GitHubUserHasWritePermission(ctx context.Context, owner, repo, username string) (bool, error)

GitHubUserHasWritePermission returns true if the given user has write permission for the repo. Returns an error if the user isn't found or the token isn't authed for this repo.

func GitRestoreFile

func GitRestoreFile(ctx context.Context, owner, repo, revision, gitDir string, fileName string) ([]byte, error)

GitRestoreFile restores a git file within the given git directory and returns its contents. Callers are assumed to have already cloned the repo into dir and HEAD is assumed to be already pointing to the desired revision.

func GithubUserInOrganization

func GithubUserInOrganization(ctx context.Context, requiredOrganization, username string) (bool, error)

GithubUserInOrganization returns true if the given github user is in the given organization. The user with the attached token must have visibility into organization membership, including private members

func IsFileNotFound

func IsFileNotFound(err error) bool

func IsGitHubRepoPublic

func IsGitHubRepoPublic(ctx context.Context, owner, repo string) (bool, error)

IsGitHubRepoPublic returns true if the repo is visible to anyone on GitHub.

func IsMergeBaseAllowed

func IsMergeBaseAllowed(ctx context.Context, owner, repo, oldestAllowedMergeBase, mergeBase string) (bool, error)

IsMergeBaseAllowed will return true if the input merge base is newer than the oldest allowed merge base configured in the project settings.

func IsUserInGithubTeam

func IsUserInGithubTeam(ctx context.Context, teams []string, org, user, owner, repo string) bool

func IsValidJiraTicketKey

func IsValidJiraTicketKey(key string) bool

IsValidJiraTicketKey returns whether the key is a normalized Jira ticket key.

func ListCheckRunCheckSuite

func ListCheckRunCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64) ([]int64, error)

ListCheckRunCheckSuite returns a list of check run IDs for a given check suite

func MergeQueueRefExists

func MergeQueueRefExists(ctx context.Context, owner, repo, ref string, token string) (bool, error)

MergeQueueRefExists checks if a GitHub ref exists. The ref should be "heads/branch-name" (e.g. "heads/gh-readonly-queue/main/pr-515-abc123"). If token is non-empty, it will be used for authentication. Otherwise, an installation token is created from Evergreen config (requires server environment).

func MostRestrictiveGitHubPermission

func MostRestrictiveGitHubPermission(perm1, perm2 string) string

MostRestrictiveGitHubPermission returns the permission from the two given permissions that is the most restrictive. This function assumes that the given permissions are valid GitHub permissions or empty strings (which is no permissions).

func NormalizeJiraTicketKey

func NormalizeJiraTicketKey(key string) string

NormalizeJiraTicketKey trims surrounding whitespace and uppercases the key.

func NormalizeJiraTicketKeys

func NormalizeJiraTicketKeys(keys []string) []string

NormalizeJiraTicketKeys returns a copy of the keys with each one normalized.

func ParseGitUrl

func ParseGitUrl(url string) (string, string, error)

func ParseGitVersion

func ParseGitVersion(version string) (string, error)

ParseGitVersion parses the git version number from the version string and returns a boolean indicating if it's an Apple Git version.

func PostCommentToPullRequest

func PostCommentToPullRequest(ctx context.Context, owner, repo string, prNum int, comment string) error

PostCommentToPullRequest posts the given comment to the associated PR.

func RevokeInstallationToken

func RevokeInstallationToken(ctx context.Context, token string) error

RevokeInstallationToken revokes an installation token. Take care to make sure that the token being revoked is not cached - Evergreen sometimes caches tokens for reuse (e.g. for making GitHub API calls), and revoking a cached token could cause running GitHub operations to fail.

func SendPendingStatusToGithub

func SendPendingStatusToGithub(ctx context.Context, input SendGithubStatusInput, urlBase string) error

SendPendingStatusToGithub sends a pending status to a Github PR patch associated with a given version.

func UpdateCheckRun

func UpdateCheckRun(ctx context.Context, owner, repo, uiBase string, checkRunID int64, task *task.Task, output *github.CheckRunOutput, ghAppAuth *githubapp.GithubAppAuth) (*github.CheckRun, error)

UpdateCheckRun updates a checkRun and returns a Github CheckRun object. UpdateCheckRunOptions must specify a name for the check run. If ghAppAuth is provided, it will use the project's GitHub app credentials. If the external app fails, the error is returned without falling back to the internal app.

func ValidateCheckRunOutput

func ValidateCheckRunOutput(output *github.CheckRunOutput) error

func ValidateGitHubPermission

func ValidateGitHubPermission(permission string) error

ValidateGitHubPermission checks if the given permission is a valid GitHub permission.

func ValidatePathWithinDirectory

func ValidatePathWithinDirectory(dir, path string) error

ValidatePathWithinDirectory ensures that the given relative path resolves to a location contained within the specified directory.

Types

type APIDiffResponse

type APIDiffResponse struct {
	Data          []ImageDiffChange `json:"data"`
	FilteredCount int               `json:"filtered_count"`
	TotalCount    int               `json:"total_count"`
}

APIDiffResponse represents a response from the /rest/api/v1/ami/diff route.

type APIFileResponse

type APIFileResponse struct {
	Data          []File `json:"data"`
	FilteredCount int    `json:"filtered_count"`
	TotalCount    int    `json:"total_count"`
}

APIFileResponse represents a response from the /rest/api/v1/ami/files route.

type APIHistoryResponse

type APIHistoryResponse struct {
	Data       []ImageHistoryInfo `json:"data"`
	TotalCount int                `json:"total_count"`
}

APIHistoryResponse represents a response from the /rest/api/v1/ami/history route.

type APIPackageResponse

type APIPackageResponse struct {
	Data          []Package `json:"data"`
	FilteredCount int       `json:"filtered_count"`
	TotalCount    int       `json:"total_count"`
}

APIPackageResponse represents a response from the /rest/api/v1/ami/packages route.

type APIRequestError

type APIRequestError struct {
	StatusCode       int
	Message          string `json:"message"`
	DocumentationUrl string `json:"documentation_url"`
}

When attempting to access the some API using authentication, requests may return 404 Not Found, instead of 403 Forbidden, under certain circumstances. For example, see https://developer.github.com/v3/#authentication. This struct should be used for errors in fetching a requested remote config.

func (APIRequestError) Error

func (are APIRequestError) Error() string

type APIResponseError

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

func (APIResponseError) Error

func (are APIResponseError) Error() string

type APIToolchainResponse

type APIToolchainResponse struct {
	Data          []Toolchain `json:"data"`
	FilteredCount int         `json:"filtered_count"`
	TotalCount    int         `json:"total_count"`
}

APIToolchainResponse represents a response from the /rest/api/v1/ami/toolchains route.

type APIUnmarshalError

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

func (APIUnmarshalError) Error

func (ue APIUnmarshalError) Error() string

type AuthCodeExchangeOptions

type AuthCodeExchangeOptions struct {
	// TokenURL is the authorization server's issuer base URL; the token
	// endpoint is taken from RFC 8414 metadata at this issuer.
	TokenURL     string
	ClientID     string
	ClientSecret string
	Code         string
	RedirectURI  string
	CodeVerifier string
}

AuthCodeExchangeOptions configures the parameters for exchanging an OAuth 2.0 authorization code for an access token.

type Commit

type Commit struct {
	Summaries []Summary `bson:"summaries"`
	Message   string    `bson:"message"`
	Patch     string    `bson:"patch"`
}

type DistroImage

type DistroImage struct {
	ID           string
	AMI          string
	LastDeployed time.Time
}

DistroImage stores information about an image including its AMI, ID, and last deployed time. An example of an image ID would be "ubuntu2204", which would correspond to the distros "ubuntu2204-small" and "ubuntu2204-large".

type EventHistoryOptions

type EventHistoryOptions struct {
	Image string `json:"-"`
	Page  int    `json:"-"`
	Limit int    `json:"-"`
}

EventHistoryOptions represents the filtering arguments for GetEvents. Image and Limit are required arguments.

type File

type File struct {
	Name string `json:"name"`
	// File SHA-256.
	Version string `json:"version"`
	// Path to the file.
	Manager string `json:"manager"`
}

File represents a file's information.

type FileFilterOptions

type FileFilterOptions struct {
	AMI   string `json:"-"`
	Page  int    `json:"-"`
	Limit int    `json:"-"`
	Name  string `json:"-"` // Filter by the name of the file (ex. something.pem).
}

FileFilterOptions represents the filtering arguments, each of which is optional except for the AMI.

type FileNotFoundError

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

This error should be returned when the requested remote configuration file can not be found.

func (FileNotFoundError) Error

func (nfe FileNotFoundError) Error() string

type GithubAuthParameters

type GithubAuthParameters struct {
	ClientId     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	Code         string `json:"code"`
	RedirectUri  string `json:"redirect_uri"`
	State        string `json:"state"`
}

type GithubAuthResponse

type GithubAuthResponse struct {
	AccessToken string `json:"access_token"`
	Scope       string `json:"scope"`
	TokenType   string `json:"token_type"`
}

func GithubAuthenticate

func GithubAuthenticate(ctx context.Context, code, clientId, clientSecret string) (githubResponse *GithubAuthResponse, err error)

GithubAuthenticate does a POST to github with the code that it received, the ClientId, ClientSecret And returns the response which contains the accessToken associated with the user.

type GithubLoginUser

type GithubLoginUser struct {
	Login            string
	Id               int
	Company          string
	EmailAddress     string `json:"email"`
	Name             string
	OrganizationsURL string
}

func GetGithubTokenUser

func GetGithubTokenUser(ctx context.Context, token string, requiredOrg string) (*GithubLoginUser, bool, error)

GetGithubTokenUser fetches a github user associated with an oauth token, and if requiredOrg is specified, checks that it belongs to that org. Returns user object, if it was a member of the specified org (or false if not specified), and error

func (*GithubLoginUser) DisplayName

func (u *GithubLoginUser) DisplayName() string

func (*GithubLoginUser) Email

func (u *GithubLoginUser) Email() string

func (*GithubLoginUser) GetAPIKey

func (u *GithubLoginUser) GetAPIKey() string

func (*GithubLoginUser) GetAccessToken

func (u *GithubLoginUser) GetAccessToken() string

func (*GithubLoginUser) GetRefreshToken

func (u *GithubLoginUser) GetRefreshToken() string

func (*GithubLoginUser) HasPermission

func (u *GithubLoginUser) HasPermission(ctx context.Context, _ gimlet.PermissionOpts) bool

func (*GithubLoginUser) IsAPIOnly

func (u *GithubLoginUser) IsAPIOnly() bool

func (*GithubLoginUser) IsNil

func (u *GithubLoginUser) IsNil() bool

func (*GithubLoginUser) OktaID

func (u *GithubLoginUser) OktaID() string

func (*GithubLoginUser) Roles

func (u *GithubLoginUser) Roles() []string

func (*GithubLoginUser) Username

func (u *GithubLoginUser) Username() string

type GithubMergeGroup

type GithubMergeGroup struct {
	Org        string `bson:"org"`
	Repo       string `bson:"repo"`
	BaseBranch string `bson:"base_branch"` // BaseBranch is what GitHub merges to
	HeadBranch string `bson:"head_branch"` // HeadBranch is the merge group's gh-readonly-queue branch

	// HeadSHA is the SHA of the commit at the head of the merge group. For each
	// PR in the merge group, GitHub merges the commits from that PR together,
	// so there are as many commits as there are PRs in the merge group. This is
	// only the SHA of the first commit in the merge group.
	HeadSHA string `bson:"head_sha"`
	// BaseSHA is the merge base commit SHA for the merge group (GitHub's base_sha).
	// It identifies which point on the base branch this merge group was built from,
	// which helps distinguish merge groups that contain different sets of PRs.
	BaseSHA string `bson:"base_sha,omitempty"`
	// HeadCommit is the title of the commit at the head of the merge group. For
	// each PR in the merge group, GitHub merges the commits from that PR
	// together, so there are as many commits as there are PRs in the merge
	// group. This is only the title of the first commit in the merge group.
	HeadCommit string `bson:"head_commit"`
	// HeadCommitDate is the timestamp of the head commit. GitHub creates the
	// merge group commit when adding a PR to the queue, so this approximates
	// when the PR entered the merge queue.
	HeadCommitDate time.Time `bson:"head_commit_date,omitempty"`

	// RemovedFromQueueAt is set when GitHub sends a "destroyed" MergeGroupEvent,
	// indicating the patch is no longer in the merge queue. This is independent
	// of the patch's test status - a patch may still be running tests but has
	// already been removed from the queue.
	RemovedFromQueueAt time.Time `bson:"removed_from_queue_at,omitempty"`
	// RemovalReason indicates why the patch was removed from the queue.
	// Possible values: "merged" (successfully merged), "invalidated" (tests failed),
	// or "dequeued" (manually removed by user).
	RemovalReason string `bson:"removal_reason,omitempty"`

	// GitRefNotFound indicates that a git operation failed because the merge queue
	// ref was deleted. This can happen for any removal reason (invalidated, dequeued,
	// or merged) when GitHub deletes the ref before tasks complete.
	GitRefNotFound bool `bson:"git_ref_not_found,omitempty"`

	// InvalidatedByUpstream indicates this patch was removed from the queue because
	// an item ahead of it in the merge queue failed, not because its own tests failed.
	// This is set when GitHub's removal reason is "invalidated" AND one of the following
	// is true: no version was created yet, the version is still running, it was removed
	// before the finish time, the version succeeded or GitRefNotFound is set (to account
	// for races where the webhook arrives after we've tried to clone and failed because
	// the ref was already invalidated and deleted because the failure in this case is
	// not the task's fault).
	InvalidatedByUpstream bool `bson:"invalidated_by_upstream,omitempty"`
}

GithubMergeGroup stores patch data for patches created from GitHub merge groups

func (*GithubMergeGroup) GetPullRequest

func (g *GithubMergeGroup) GetPullRequest(ctx context.Context) (*github.PullRequest, error)

GetPullRequest fetches the GitHub PR associated with this merge group.

type GithubPatch

type GithubPatch struct {
	PRNumber      int    `bson:"pr_number"`
	BaseOwner     string `bson:"base_owner"`
	BaseRepo      string `bson:"base_repo"`
	BaseBranch    string `bson:"base_branch"`
	HeadOwner     string `bson:"head_owner"`
	HeadRepo      string `bson:"head_repo"`
	HeadBranch    string `bson:"head_branch"`
	HeadHash      string `bson:"head_hash"`
	BaseHash      string `bson:"base_hash"`
	Author        string `bson:"author"`
	AuthorUID     int    `bson:"author_uid"`
	CommitTitle   string `bson:"commit_title"`
	CommitMessage string `bson:"commit_message"`
	MergeBase     string `bson:"merge_base"`
	// the patchId to copy the definitions for for the next patch the pr creates
	RepeatPatchIdNextPatch string   `bson:"repeat_patch_id_next_patch"`
	Labels                 []string `bson:"labels,omitempty"`
}

GithubPatch stores patch data for patches create from GitHub pull requests

type ImageDiffChange

type ImageDiffChange struct {
	AfterVersion  string `json:"after_version"`
	BeforeVersion string `json:"before_version"`
	Name          string `json:"name"`
	Manager       string `json:"manager"`
	Type          string `json:"type"`
}

ImageDiffChange represents a change between two AMIs.

type ImageEvent

type ImageEvent struct {
	Entries   []ImageEventEntry
	Timestamp time.Time
	AMIBefore string
	AMIAfter  string
}

ImageEvent contains information about changes to an image when the AMI changes.

type ImageEventEntry

type ImageEventEntry struct {
	Name   string
	Before string
	After  string
	Type   ImageEventType
	Action ImageEventEntryAction
}

ImageEventEntry represents a change to the image.

type ImageEventEntryAction

type ImageEventEntryAction string
const (
	ImageEventEntryActionAdded   ImageEventEntryAction = "ADDED"
	ImageEventEntryActionUpdated ImageEventEntryAction = "UPDATED"
	ImageEventEntryActionDeleted ImageEventEntryAction = "DELETED"
)

type ImageEventType

type ImageEventType string
const (
	ImageEventTypeOperatingSystem ImageEventType = "OPERATING_SYSTEM"
	ImageEventTypePackage         ImageEventType = "PACKAGE"
	ImageEventTypeToolchain       ImageEventType = "TOOLCHAIN"
	ImageEventTypeFile            ImageEventType = "FILE"
)

type ImageHistoryInfo

type ImageHistoryInfo struct {
	AMI          string `json:"ami_id"`
	CreationDate int    `json:"created_date"`
}

ImageHistoryInfo represents information about an image with its AMI and creation date.

type JiraCustomField

type JiraCustomField struct {
	Value string `json:"value"`
}

type JiraHandler

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

func NewJiraHandler

func NewJiraHandler(opts send.JiraOptions) (JiraHandler, error)

func (*JiraHandler) GetIssue

func (jiraHandler *JiraHandler) GetIssue(ctx context.Context, key string) (*JiraTicket, error)

GetIssue returns the ticket with the given key using the go-jira client.

func (*JiraHandler) JQLSearch

func (jiraHandler *JiraHandler) JQLSearch(ctx context.Context, query string, startAt, maxResults int) (*JiraSearchResults, error)

JQLSearch runs the given JQL query against the given jira instance and returns the results in a JiraSearchResults.

type JiraResolution

type JiraResolution struct {
	Name string `json:"name"`
}

type JiraSearchResults

type JiraSearchResults struct {
	StartAt    int          `json:"startAt"`
	MaxResults int          `json:"maxResults"`
	Total      int          `json:"total"`
	Issues     []JiraTicket `json:"issues"`
}

JiraSearchResults marshal to and unmarshal from the json search results returned by the rest api at /rest/api/2/search?jql={jql}

type JiraStatus

type JiraStatus struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

type JiraTicket

type JiraTicket struct {
	Key    string        `json:"key"`
	Fields *TicketFields `json:"fields"`
}

JiraTicket marshals to and unmarshals from the json issue returned by the rest api at /rest/api/latest/issue/{ticket_id}

type OSInfo

type OSInfo struct {
	Name string `json:"name"`
	// Value associated with the OS field.
	Version string `json:"version"`
}

OSInfo stores operating system information.

type OSInfoFilterOptions

type OSInfoFilterOptions struct {
	AMI   string `json:"-"`
	Name  string `json:"-"`
	Page  int    `json:"-"`
	Limit int    `json:"-"`
}

OSInfoFilterOptions represents the filtering options for GetOSInfo. Each argument is optional except for the AMI field.

type OSInfoResponse

type OSInfoResponse struct {
	Data          []OSInfo `json:"data"`
	FilteredCount int      `json:"filtered_count"`
	TotalCount    int      `json:"total_count"`
}

OSInfoResponse represents a response from the /rest/api/v1/ami/os route.

type OktaAuthorizeOptions

type OktaAuthorizeOptions struct {
	Issuer      string
	ClientID    string
	RedirectURI string
	Scopes      []string
}

OktaAuthorizeOptions configures the parameters for building an OAuth 2.0 Authorization Code + PKCE authorization URL.

type OktaAuthorizeResult

type OktaAuthorizeResult struct {
	AuthorizeURL string
	State        string
	CodeVerifier string
}

OktaAuthorizeResult contains the authorization URL to redirect the user to, along with the state and PKCE code verifier generated for this request.

func BuildAuthorizeURL

func BuildAuthorizeURL(ctx context.Context, opts OktaAuthorizeOptions) (*OktaAuthorizeResult, error)

BuildAuthorizeURL discovers the Okta authorization endpoint, generates PKCE and state parameters, and returns the full authorize URL along with the state and code verifier that the caller should persist for the callback.

type OktaTokenExchangeOptions

type OktaTokenExchangeOptions struct {
	// Issuer is the OAuth 2.0 Authorization Server issuer URL. Used to
	// discover the token endpoint via RFC 8414 metadata when the process-wide
	// token URL cache is empty.
	Issuer string
	// ClientID is the OAuth2 client identifier.
	ClientID string
	// ClientSecret is the OAuth2 client secret.
	ClientSecret string
	// SubjectToken is the existing token to exchange.
	SubjectToken string
	// SubjectTokenType identifies the type of SubjectToken (RFC 8693), e.g. TokenTypeAccessToken.
	SubjectTokenType string
	// Audience is the target audience for the requested token. Optional.
	Audience string
	// Scopes is the set of scopes to request on the new token. Optional.
	Scopes []string
}

OktaTokenExchangeOptions configures the parameters for an OAuth 2.0 Token Exchange (RFC 8693) against an Okta authorization server.

type Package

type Package struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	// Manager of the package (e.g. pip).
	Manager string `json:"manager"`
}

Package represents a package's information.

type PackageFilterOptions

type PackageFilterOptions struct {
	AMI     string `json:"-"`
	Page    int    `json:"-"`
	Limit   int    `json:"-"`
	Name    string `json:"-"` // Filter by the name of the package.
	Manager string `json:"-"` // Filter by the package manager (ex. pip).
}

PackageFilterOptions represents the filtering arguments, each of which is optional except the AMI.

type PapertrailClient

type PapertrailClient struct {
	*http.Client
	Address   string
	KeyID     string
	SecretKey string
}

PapertrailClient is used to interact with the Papertrail service over HTTP. It is recommended to use NewPapertrailClient to initialize this struct.

func NewPapertrailClient

func NewPapertrailClient(keyID, secretKey, address string) *PapertrailClient

NewPapertrailClient returns an initialized PapertrailClient. If address is empty, the default production address is used

func (*PapertrailClient) GetProductVersion

func (c *PapertrailClient) GetProductVersion(ctx context.Context, product, version string) (*PapertrailProductVersion, error)

GetProductVersion calls the Papertrail /product-version endpoint, returning a PapertrailProductVersion with the collection of all spans associated with the product and version passed in.

func (*PapertrailClient) Trace

func (c *PapertrailClient) Trace(ctx context.Context, args TraceArgs) error

Trace calls the Papertrail /trace endpoint, associating a file and its metadata with a product version.

type PapertrailProductVersion

type PapertrailProductVersion struct {
	Product string           `json:"product"`
	Version string           `json:"version"`
	Spans   []PapertrailSpan `json:"spans"`
}

PapertrailProductVersion contains a particular product-version's complete list of spans from Papertrail's /product-versions endpoint

type PapertrailSpan

type PapertrailSpan struct {
	ID        string `json:"id"`
	SHA256sum string `json:"sha256sum"`
	Filename  string `json:"filename"`
	Build     string `json:"build"`
	Platform  string `json:"platform"`
	Product   string `json:"product"`
	Version   string `json:"version"`
	Submitter string `json:"submitter"`
	KeyID     string `json:"key_id"`
	Time      uint64 `json:"time"`
}

PapertrailSpan represents a span in json form from Papertrail.

type ResponseReadError

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

func (ResponseReadError) Error

func (re ResponseReadError) Error() string

type RuntimeEnvironmentsClient

type RuntimeEnvironmentsClient struct {
	Client  *http.Client
	BaseURL string
	APIKey  string
}

RuntimeEnvironmentsClient is a client that can communicate with the Runtime Environments API. Interacting with the API requires an API key.

func NewRuntimeEnvironmentsClient

func NewRuntimeEnvironmentsClient(baseURL string, apiKey string) *RuntimeEnvironmentsClient

NewRuntimeEnvironmentsClient returns a client that can interact with the Runtime Environments API.

func (*RuntimeEnvironmentsClient) DoRequest

func (c *RuntimeEnvironmentsClient) DoRequest(ctx context.Context, route string, encodedParams string) ([]byte, error)

DoRequest makes a request to the Runtime Environments API.

func (*RuntimeEnvironmentsClient) GetEvents

GetEvents returns information about the changes between AMIs that occurred on the image.

func (*RuntimeEnvironmentsClient) GetFiles

GetFiles returns a list of files from the AMI and filters in the FileFilterOptions.

func (*RuntimeEnvironmentsClient) GetImageInfo

func (c *RuntimeEnvironmentsClient) GetImageInfo(ctx context.Context, imageID string) (*DistroImage, error)

GetImageInfo returns basic information about an image.

func (*RuntimeEnvironmentsClient) GetImageNames

func (c *RuntimeEnvironmentsClient) GetImageNames(ctx context.Context) ([]string, error)

GetImageNames returns a list of strings containing the names of all images from the Runtime Environments API.

func (*RuntimeEnvironmentsClient) GetOSInfo

GetOSInfo returns a list of operating system information for an AMI.

func (*RuntimeEnvironmentsClient) GetPackages

GetPackages returns a list of packages from the corresponding AMI and filters in opts.

func (*RuntimeEnvironmentsClient) GetToolchains

GetToolchains returns a list of toolchains from the AMI and filters in the ToolchainFilterOptions.

type SageClient

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

SageClient is a client for communicating with the Sage API service.

func NewSageClient

func NewSageClient(baseURL string) (*SageClient, error)

NewSageClient creates a new Sage API client.

func (*SageClient) Close

func (c *SageClient) Close()

Close releases resources used by the client.

type SearchReturnInfo

type SearchReturnInfo struct {
	Issues []JiraTicket `json:"issues"`
	Search string       `json:"search"`
	Source string       `json:"source"`
}

type SendGithubStatusInput

type SendGithubStatusInput struct {
	VersionId string
	Owner     string
	Repo      string
	Ref       string
	Desc      string
	Caller    string
	Context   string
}

SendGithubStatusInput is the input to the SendPendingStatusToGithub function and contains all the information associated with a version necessary to send a status to GitHub.

type Summary

type Summary struct {
	Name        string `bson:"filename"`
	Additions   int    `bson:"additions"`
	Deletions   int    `bson:"deletions"`
	Description string `bson:"description,omitempty"`
}

Summary stores summary patch information

func GetChangedFilesBetweenCommits

func GetChangedFilesBetweenCommits(ctx context.Context, owner, repo, base, head string) ([]Summary, error)

GetChangedFilesBetweenCommits gets the summary list of the changed files between the given commits

func GetGitHubPullRequestFiles

func GetGitHubPullRequestFiles(ctx context.Context, gh GithubPatch) ([]Summary, error)

GetGitHubPullRequestFiles gets the summary list of the changed files for the given pull request. Due to GitHub limitations, this can get at most 3000 changed files. If it hits the 3000 file retrieval limit, it'll return the first 3000 files and no error; callers are expected to handle that limit appropriately.

func GetGithubPullRequestDiff

func GetGithubPullRequestDiff(ctx context.Context, gh GithubPatch) (string, []Summary, error)

GetGithubPullRequestDiff downloads a raw diff from a Github Pull Request. This can fail if the PR is too large (e.g. greater than 300 files). See GetGitHubPullRequestFiles.

func GetPatchSummaries

func GetPatchSummaries(ctx context.Context, patchContent string) ([]Summary, error)

func ParseGitSummary

func ParseGitSummary(ctx context.Context, gitOutput fmt.Stringer) (summaries []Summary, err error)

ParseGitSummary takes in a buffer of data and parses it into a slice of git summaries. It returns an error if it is unable to parse the data

type TicketFields

type TicketFields struct {
	Summary      string             `json:"summary"`
	Assignee     *User              `json:"assignee"`
	Resolution   *JiraResolution    `json:"resolution"`
	Created      string             `json:"created"`
	Updated      string             `json:"updated"`
	Status       *JiraStatus        `json:"status"`
	AssignedTeam []*JiraCustomField `json:"customfield_12751"`
	FailingTasks []string           `json:"customfield_12950"`
}

type Toolchain

type Toolchain struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	// Path to the toolchain.
	Manager string `json:"manager"`
}

Toolchain represents a toolchain's information.

type ToolchainFilterOptions

type ToolchainFilterOptions struct {
	AMI     string `json:"-"`
	Page    int    `json:"-"`
	Limit   int    `json:"-"`
	Name    string `json:"-"` // Filter by the name of the toolchain (ex. golang).
	Version string `json:"-"` // Filter by the version (ex. go1.8.7).
}

ToolchainFilterOptions represents the filtering arguments, each of which is optional except for the AMI.

type TraceArgs

type TraceArgs struct {

	// Build is the unique identifier for a particular job run in a CI system.
	// For evergreen jobs, this is in the form "{task_id}_{execution}"
	Build string

	// Platform is the Papertrail-internal name for this CI service. It should
	// always be set to Evergreen unless doing testing
	Platform string

	// Filename is the basename of the file that is being traced
	Filename string

	// Sha256 is the hex-encoded checksum of the file that is being traced
	Sha256 string

	// Product is the product name to associate this file with (e.g. compass)
	Product string

	// Version is the version name to associate this file with (e.g. 1.0.0)
	Version string

	// Submitter is the username in the CI system to associate this trace with.
	Submitter string
}

TraceArgs contain the list of items necessary to pass to Papertrail

type User

type User struct {
	DisplayName string `json:"displayName"`
}

type YAMLFormatError

type YAMLFormatError struct {
	Message string
}

func (YAMLFormatError) Error

func (y YAMLFormatError) Error() string

Directories

Path Synopsis
clients
fws

Jump to

Keyboard shortcuts

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