github

package
v0.0.0-...-7f01c5f Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NegativeCacheTTL = 3 * time.Minute // Used for negative caching of missing/not-signed users
	ProjectCacheTTL  = 3 * time.Hour   // Used for per-project caching of signed users
	MaxCommentLength = 0xff00          // 65520 characters - leave some buffer under 64KB limit
)
View Source
const MissingCoAuthorsMessage = `` /* 1038-byte string literal not displayed */

Note: we use | and ||| as placeholders for inline and fenced code, then swap to backticks at render time.

View Source
const (
	// SessionStoreKey is the key used to lookup the session
	SessionStoreKey = "cla-github"
)

Variables

View Source
var (
	// ErrAccessDenied is returned whenever github return 403 or 401
	ErrAccessDenied = errors.New("access denied")
	// ErrRateLimited is returned when github detects rate limit abuse
	ErrRateLimited = errors.New("rate limit")
)
View Source
var (
	// ErrGitHubRepositoryNotFound is returned when github repository is not found
	ErrGitHubRepositoryNotFound = errors.New("github repository not found")
	NoreplyIDPattern            = regexp.MustCompile(`^(\d+)\+([a-zA-Z0-9-]+)@users\.noreply\.github\.com$`)
	NoreplyUserPattern          = regexp.MustCompile(`^([a-zA-Z0-9-]+)@users\.noreply\.github\.com$`)
	GithubUsernameRegex         = regexp.MustCompile(`^[A-Za-z0-9-]{3,39}$`)
)
View Source
var (
	ErrGithubOrganizationNotFound = errors.New("github organization name not found")
)

errors

View Source
var GithubUserCache = NewCache(12 * time.Hour)
View Source
var ModelProjectUserCache = NewProjectUserCache(3 * time.Hour)
View Source
var ModelUserCache = NewUserCache(12 * time.Hour)

Functions

func CheckAndWrapForKnownErrors

func CheckAndWrapForKnownErrors(resp *github.Response, err error) (bool, error)

CheckAndWrapForKnownErrors checks for some of the known error types

func ClearCaches

func ClearCaches()

ClearCaches clears all in-memory caches maintained by the GitHub module.

func Configure

func Configure(api *operations.ClaAPI, clientID, clientSecret, accessToken string, sessionStore *dynastore.Store)

Configure API call

func EditIssueCommentIfChanged

func EditIssueCommentIfChanged(ctx context.Context, client *github.Client, owner, repo string, prNum int, commentID int64, newBody string) (bool, error)

EditIssueCommentIfChanged fetches the existing comment and edits only if NormalizeComment(existing) != NormalizeComment(newBody). Returns true if edited.

func ExpandWithCoAuthors

func ExpandWithCoAuthors(
	ctx context.Context,
	client *github.Client,
	usersService users.Service,
	commit *github.RepositoryCommit,
	pr int,
	installationID int64,
	commitAuthors *[]*UserCommitSummary,
	mu *sync.Mutex,
) bool

ExpandWithCoAuthors appends UserCommitSummary objects for all co-authors to commitAuthors slice.

func GetCoAuthorsFromCommit

func GetCoAuthorsFromCommit(
	ctx context.Context,
	commit *github.RepositoryCommit,
) [][2]string

GetCoAuthorsFromCommit returns a slice of [2]string, each representing [name, email] of a co-author.

func GetCommitAuthorSignedStatus

func GetCommitAuthorSignedStatus(
	ctx context.Context,
	usersService users.Service,
	hasUserSigned func(context.Context, *models.User, string) (*bool, *bool, error),
	projectID string,
	userSummary *UserCommitSummary,
	signed *[]*UserCommitSummary,
	unsigned *[]*UserCommitSummary,
	mu *sync.Mutex,
)

GetCommitAuthorSignedStatus checks if the commit author has signed the CLA for the given project

func GetCommitAuthorsSignedStatuses

func GetCommitAuthorsSignedStatuses(
	ctx context.Context,
	usersService users.Service,
	hasUserSigned func(context.Context, *models.User, string) (*bool, *bool, error),
	projectID string,
	authors []*UserCommitSummary,
) ([]*UserCommitSummary, []*UserCommitSummary)

func GetGitHubRepository

func GetGitHubRepository(ctx context.Context, installationID, githubRepositoryID int64) (*github.Repository, error)

func GetGithubUserByID

func GetGithubUserByID(ctx context.Context, client *github.Client, githubID int64) (*github.User, error)

GetGitHubUserByID fetches a GitHub user by their GitHubID. Returns (*github.User, nil) if found, (nil, nil) if not found, or (nil, error) on error.

func GetGithubUserByLogin

func GetGithubUserByLogin(ctx context.Context, client *github.Client, login string) (*github.User, error)

GetGitHubUserByLogin fetches a GitHub user by their login (username). Returns (*github.User, nil) if found, (nil, nil) if not found, or (nil, error) on error.

func GetInstallationRepositories

func GetInstallationRepositories(ctx context.Context, installationID int64) ([]*github.Repository, error)

GetInstallationRepositories returns list of repositories for github app installation

func GetMembership

func GetMembership(ctx context.Context, user, organizationName string) (*github.Membership, error)

GetOrganization gets github organization

func GetOrganization

func GetOrganization(ctx context.Context, organizationName string) (*github.Organization, error)

GetOrganization gets github organization

func GetOrganizationMembers

func GetOrganizationMembers(ctx context.Context, orgName string, installationID int64) ([]string, error)

GetOrganizationMembers gets members in organization

func GetPRCommitSHA

func GetPRCommitSHA(ctx context.Context, gh *github.Client, owner, repo string, prNumber int) (string, error)

Commit SHA for a PR (authoritative "last commit")

func GetPullRequest

func GetPullRequest(ctx context.Context, pullRequestID int, owner, repo string, client *github.Client) (*github.PullRequest, error)

func GetRepositories

func GetRepositories(ctx context.Context, organizationName string) ([]*github.Repository, error)

GetRepositories gets github repositories by organization

func GetRepositoryByExternalID

func GetRepositoryByExternalID(ctx context.Context, installationID, id int64) (*github.Repository, error)

GetRepositoryByExternalID finds github repository by github repository id

func GetReturnURL

func GetReturnURL(ctx context.Context, installationID, repositoryID int64, pullRequestID int) (string, error)

func GetUserDetails

func GetUserDetails(user string) (*github.User, error)

GetUserDetails return github users details

func Init

func Init(ghAppID int, ghAppPrivateKey string, secAccessToken string)

Init initializes the required GitHub variables

func IsCoAuthorsEnabledForRepo

func IsCoAuthorsEnabledForRepo(enableCoAuthors map[string]bool, orgRepo string) bool

IsCoAuthorsEnabledForRepo returns whether co-authors are enabled for this repo

func IsValidGitHubUsername

func IsValidGitHubUsername(username string) bool

IsValidGitHubUsername checks if the provided username is a valid GitHub username.

func NewGithubAppClient

func NewGithubAppClient(installationID int64) (*github.Client, error)

NewGithubAppClient creates a new github client from the supplied installationID

func NewGithubOauthClient

func NewGithubOauthClient() *github.Client

NewGithubOauthClient creates github client from global accessToken

func NewGithubOauthClientWithAccessToken

func NewGithubOauthClientWithAccessToken(accessToken string) *github.Client

NewGithubOauthClientWithAccessToken creates github client from specified accessToken

func NewGithubV4AppClient

func NewGithubV4AppClient(installationID int64) (*githubv4.Client, error)

NewGithubV4AppClient creates a new github v4 client from the supplied installationID

func NormalizeComment

func NormalizeComment(s string) string

NormalizeComment mirrors Python normalize_comment

func ProjectUserKey

func ProjectUserKey(projectID, id, login, email string) [4]string

func SearchGithubUserByEmail

func SearchGithubUserByEmail(ctx context.Context, client *github.Client, email string) (*github.User, error)

SearchGithubUserByEmail searches for a GitHub user by email using the GitHub search API. Returns the first found *github.User, or nil if not found or on error.

func SkipAllowlistedBots

func SkipAllowlistedBots(ev events.Service, orgModel *models.GithubOrganization, orgRepo, projectID string, actorsMissingCLA []*UserCommitSummary) ([]*UserCommitSummary, []*UserCommitSummary)

SkipAllowlistedBots- check if the actors are allowlisted based on the skip_cla configuration. Returns two lists: - actors still missing cla: actors who still need to sign the CLA after checking skip_cla - allowlisted actors: actors who are skipped due to skip_cla configuration :param orgModel: The GitHub organization model instance. :param orgRepo: The repository name in the format 'org/repo'. :param actorsMissingCla: List of UserCommitSummary objects representing actors who are missing CLA. :return: two arrays (actors still missing CLA, allowlisted actors) : in cla-{stage}-github-orgs table there can be a skip_cla field which is a dict with the following structure:

{
    "repo-name": "<login_pattern>;<email_pattern>;<name_pattern>",
    "re:repo-regexp": "[<login_pattern>;<email_pattern>;<name_pattern>||...]",
    "*": "<login_pattern>"
}

where:

  • repo-name is the exact repository name under given org (e.g., "my-repo" not "my-org/my-repo")
  • re:repo-regexp is a regex pattern to match repository names
  • * is a wildcard that applies to all repositories
  • <login_pattern> is a GitHub login pattern (exact match or regex prefixed by re: or match all '*') if not specified defaults to ""
  • <email_pattern> is a GitHub email pattern (exact match or regex prefixed by re: or match all '*') if not specified defaults to ""
  • <name_pattern> is a GitHub name pattern (exact match or regex prefixed by re: or match all '*') if not specified defaults to "" "" matches empty value, null value or missing property The login, email and name patterns are separated by a semicolon (;). Email and name parts are optional. There can be an array of patterns for a single repository, separated by ||. It must start with a '[' and end with a ']': "[...||...||...]" If the skip_cla is not set, it will skip the allowlisted bots check.

func TrimComment

func TrimComment(html string, maxItems, head, tail int, ellipsis string) string

TrimComment collapses any "(sha1, sha2, ...)" group where all tokens look like SHAs (7–40 hex). If a group has > maxItems, it keeps the first `head`, then an ellipsis, then the last `tail`.

func UpdateCacheAfterSignature

func UpdateCacheAfterSignature(ctx context.Context, user *models.User, projectID string) error

UpdateCacheAfterSignature marks the user as authorized for the given project

func UpdatePullRequest

func UpdatePullRequest(ctx context.Context, installationID int64, pullRequestID int, owner, repo string, repoID *int64, signed []*UserCommitSummary, missing []*UserCommitSummary, anyMissing bool, CLABaseAPIURL, CLALandingPage, CLALogoURL string) error

func UserKey

func UserKey(id, login, email string) [3]string

Types

type Cache

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

func NewCache

func NewCache(ttl time.Duration) *Cache

func (*Cache) Cleanup

func (c *Cache) Cleanup()

func (*Cache) Clear

func (c *Cache) Clear()

func (*Cache) Delete

func (c *Cache) Delete(key [2]string)

func (*Cache) Get

func (c *Cache) Get(key [2]string) (*github.User, bool)

func (*Cache) Set

func (c *Cache) Set(key [2]string, value *github.User)

func (*Cache) SetWithTTL

func (c *Cache) SetWithTTL(key [2]string, value *github.User, tl time.Duration)

type GraphQLError

type GraphQLError struct {
	Errs []gqlError
}

func (*GraphQLError) Error

func (e *GraphQLError) Error() string

type ProjectUserCache

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

func NewProjectUserCache

func NewProjectUserCache(ttl time.Duration) *ProjectUserCache

func (*ProjectUserCache) Cleanup

func (c *ProjectUserCache) Cleanup()

func (*ProjectUserCache) Clear

func (c *ProjectUserCache) Clear()

func (*ProjectUserCache) Delete

func (c *ProjectUserCache) Delete(key [4]string)

func (*ProjectUserCache) Get

func (c *ProjectUserCache) Get(key [4]string) (*models.User, bool, bool, bool)

func (*ProjectUserCache) Set

func (c *ProjectUserCache) Set(key [4]string, value *models.User, signed, affiliated bool)

func (*ProjectUserCache) SetWithTTL

func (c *ProjectUserCache) SetWithTTL(key [4]string, value *models.User, signed, affiliated bool, tl time.Duration)

type Status

type Status struct {
	State       *string `json:"state,omitempty"`
	TargetURL   *string `json:"target_url,omitempty"`
	Description *string `json:"description,omitempty"`
	Context     *string `json:"context,omitempty"`
}

func CreateStatus

func CreateStatus(ctx context.Context, client *github.Client, owner, repo, sha string, status *Status) (*Status, *github.Response, error)

CreateStatus creates a new status on the specified commit.

GitHub API docs:https://docs.github.com/en/rest/commits/statuses

type UserCache

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

func NewUserCache

func NewUserCache(ttl time.Duration) *UserCache

func (*UserCache) Cleanup

func (c *UserCache) Cleanup()

func (*UserCache) Clear

func (c *UserCache) Clear()

func (*UserCache) Delete

func (c *UserCache) Delete(key [3]string)

func (*UserCache) Get

func (c *UserCache) Get(key [3]string) (*models.User, bool)

func (*UserCache) Set

func (c *UserCache) Set(key [3]string, value *models.User)

func (*UserCache) SetWithTTL

func (c *UserCache) SetWithTTL(key [3]string, value *models.User, tl time.Duration)

type UserCommitSummary

type UserCommitSummary struct {
	SHA          string
	CommitAuthor *github.User
	Affiliated   bool
	Authorized   bool
}

UserCommitSummary data model

func DedupAndSortCommitSummaries

func DedupAndSortCommitSummaries(items []*UserCommitSummary) []*UserCommitSummary

DedupAndSortCommitSummaries mirrors Python dedup_and_sort Dedupe key: (author_id, login, email, sha) Sort key: login, name, email, sha (all case-insensitive)

func GetCoAuthorCommits

func GetCoAuthorCommits(
	ctx context.Context,
	client *github.Client,
	usersService users.Service,
	coAuthor [2]string,
	commit *github.RepositoryCommit,
	pr int,
	installationID int64,
) (*UserCommitSummary, bool)

func GetPullRequestCommitAuthors

func GetPullRequestCommitAuthors(
	ctx context.Context,
	usersService users.Service,
	installationID int64,
	pullRequestID int,
	owner, repo string,
	withCoAuthors bool,
) ([]*UserCommitSummary, bool, error)

func GetPullRequestCommitAuthorsREST

func GetPullRequestCommitAuthorsREST(ctx context.Context, usersService users.Service, installationID int64, pullRequestID int, owner, repo string, withCoAuthors bool) ([]*UserCommitSummary, bool, error)

func (UserCommitSummary) GetCommitAuthorEmail

func (u UserCommitSummary) GetCommitAuthorEmail() string

GetCommitAuthorEmail returns commit author email if available, otherwise returns empty string

func (UserCommitSummary) GetCommitAuthorID

func (u UserCommitSummary) GetCommitAuthorID() string

GetCommitAuthorID commit author username ID (numeric value as a string) if available, otherwise returns empty string

func (UserCommitSummary) GetCommitAuthorUsername

func (u UserCommitSummary) GetCommitAuthorUsername() string

GetCommitAuthorUsername returns commit author username if available, otherwise returns empty string

func (UserCommitSummary) GetDisplayText

func (u UserCommitSummary) GetDisplayText(tagUser bool) string

GetDisplayText returns the display text for the user commit summary

func (UserCommitSummary) IsValid

func (u UserCommitSummary) IsValid() bool

IsValid returns true if the commit author information is available

Directories

Path Synopsis
Package branch_protection is a generated GoMock package.
Package branch_protection is a generated GoMock package.

Jump to

Keyboard shortcuts

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