Documentation
¶
Overview ¶
Package gitoperationslib wraps git forge operations behind a common set of interfaces. Forgejo is the primary backend; GitHub and Bitbucket Cloud are supported where their APIs overlap. Operations a backend cannot perform return an error matching ErrNotSupported.
Create a client with forgejo.New, github.New or bitbucket.New; the webhook sub-package receives and verifies deliveries. See __docs/USAGE.md in the repository for the full guide.
Index ¶
- Constants
- Variables
- func All[T any](ctx context.Context, opts ListOptions, ...) iter.Seq2[T, error]
- func IsForbidden(err error) bool
- func IsNotFound(err error) bool
- func IsUnauthorized(err error) bool
- func NotSupported(backend Backend, operation, reason string) error
- func Ptr[T any](v T) *T
- func StatusCode(err error) int
- type APIError
- type AccessToken
- type Account
- type AddSSHKeyOptions
- type Admin
- type Allowlist
- type Asset
- type Backend
- type Branch
- type BranchProtection
- type BranchProtections
- type Branches
- type CI
- type CIScope
- type Capability
- type ChangedFile
- type Client
- type Collaborator
- type CollaboratorInvitation
- type CollaboratorInvitations
- type CollaboratorPermission
- type Collaborators
- type Comment
- type Commit
- type CommitAuthor
- type CommitDiffs
- type CommitStats
- type CommitSummary
- type Commits
- type Comparison
- type CreateBranchOptions
- type CreateIssueOptions
- type CreateMilestoneOptions
- type CreateOrgOptions
- type CreatePROptions
- type CreatePushMirrorOptions
- type CreateReleaseOptions
- type CreateRepoOptions
- type CreateReviewCommentOptions
- type CreateReviewOptions
- type CreateTagOptions
- type CreateTeamOptions
- type CreateTokenOptions
- type CreateUserOptions
- type CreateWebhookOptions
- type CurrentUser
- type DefaultWebhooks
- type DeleteUserOptions
- type DiffFormat
- type Directory
- type EditAssetOptions
- type EditIssueOptions
- type EditLabelOptions
- type EditMilestoneOptions
- type EditOrgOptions
- type EditPROptions
- type EditProfileOptions
- type EditReleaseOptions
- type EditRepoOptions
- type EditSettings
- type EditTeamOptions
- type EditUserOptions
- type EditWebhookOptions
- type Email
- type Emails
- type ExternalAssets
- type FileStatus
- type GPGKey
- type GPGKeyEmail
- type GPGKeys
- type GitHook
- type GitHooks
- type History
- type HookContentType
- type HookDeliveries
- type HookDelivery
- type HookDeliveryPage
- type HookEvent
- type HookScope
- type Issue
- type IssueState
- type Issues
- type Label
- type Labels
- type ListCommitsOptions
- type ListHookDeliveriesOptions
- type ListIssuesOptions
- type ListOptions
- type ListPROptions
- type MergeMethod
- type MergeOptions
- type Milestone
- type MilestoneState
- type Milestones
- type Mirrors
- type NotSupportedError
- type Org
- type OrgAvatars
- type OrgInfo
- type OrgSecrets
- type Orgs
- type OwnerVisibility
- type PRBranch
- type PRContents
- type PRState
- type Page
- type PartError
- type Profile
- type PullRequest
- type PullRequests
- type PushMirror
- type Release
- type Releases
- type Repo
- type Repos
- type RetryPolicy
- type Review
- type ReviewComment
- type ReviewComments
- type ReviewEvent
- type ReviewState
- type SSHKey
- type SSHKeys
- type Secret
- type SecretAccess
- type SecretVisibility
- type Secrets
- type SiteHooks
- type SystemWebhooks
- type Tag
- type TagProtection
- type TagProtections
- type Tags
- type Team
- type TeamAccess
- type TeamInfo
- type TeamPermission
- type TeamUnit
- type Teams
- type Tokens
- type UnsupportedVersionError
- type User
- type UserHooks
- type UserInfo
- type UserSettings
- type UserWebhooks
- type Users
- type Variable
- type Variables
- type Visibility
- type Webhook
- type Webhooks
Constants ¶
const MaxAvatarSize = 10 << 20
MaxAvatarSize is the largest image SetAvatar and SetOrgAvatar send; larger ones are refused before any request.
Variables ¶
var ( // ErrOwnsRepos: deleting an organisation (Forgejo: HTTP 500) or a user // without Purge (HTTP 422) that still owns repositories. ErrOwnsRepos = errors.New("the account still owns repositories") // ErrOrgMember: deleting a user without Purge who still belongs to // organisations (Forgejo). ErrOrgMember = errors.New("the user still belongs to organisations") // ErrLastOwner: removing the last member of an organisation's owner team, // from the organisation or from the team (Forgejo: HTTP 500). ErrLastOwner = errors.New("cannot remove the last owner of an organisation") // ErrBranchProtected: deleting a branch a protection rule covers // (Forgejo 403, GitHub 422, Bitbucket 500). ErrBranchProtected = errors.New("the branch is protected") // ErrInvalidOTP: basic authentication of an account with two-factor // authentication, without a valid code (Forgejo: HTTP 401 on every // request, forgejo.New included). Retry with forgejo.BasicAuthOTP. ErrInvalidOTP = errors.New("two-factor authentication code missing or invalid") // ErrGPGSignature: a GPG key needs a valid signature of the verification // token (GPGKeys.VerificationToken). Forgejo answers HTTP 404 when none of // the key's e-mail addresses belongs to the account, and 422 when the // signature does not match. ErrGPGSignature = errors.New("the GPG key needs a valid signature of the verification token") // ErrPasswordRequired: the operation needs username and password // authentication, not a token (Forgejo: HTTP 401 "auth method not // allowed" when creating or deleting access tokens). ErrPasswordRequired = errors.New("the operation needs username and password authentication") )
Refusals recognised in a server's error response. The *APIError keeps the server's status and message, and matches the sentinel through errors.Is:
if errors.Is(err, gitoperationslib.ErrOwnsRepos) { … }
Recognition relies on the server's wording; an unrecognised refusal is reported as a plain *APIError, as before.
var AllTeamUnits = []TeamUnit{ TeamUnitCode, TeamUnitIssues, TeamUnitExternalIssues, TeamUnitWiki, TeamUnitExternalWiki, TeamUnitPulls, TeamUnitReleases, TeamUnitProjects, TeamUnitPackages, TeamUnitActions, }
AllTeamUnits lists every TeamUnit.
var DefaultRetryPolicy = RetryPolicy{MaxAttempts: 3, MaxWait: 30 * time.Second}
DefaultRetryPolicy is used when no WithRetry option is given: three attempts, with waits of about 1 s and 2 s, and server-requested waits of up to 30 s.
var ErrNotSupported = errors.New("operation not supported")
ErrNotSupported is matched (via errors.Is) by every error returned when a backend cannot perform an operation, instead of silently degrading.
var ErrOwnerTeam = errors.New("refusing to delete, rename or change the permissions of an owner team")
ErrOwnerTeam is returned when an operation would delete an organisation's owner team, rename it, or change its permissions. Forgejo allows deleting it, which leaves the organisation without owners.
var NoRetry = RetryPolicy{MaxAttempts: 1}
NoRetry disables retries.
Functions ¶
func All ¶
func All[T any](ctx context.Context, opts ListOptions, fetch func(context.Context, ListOptions) (Page[T], error)) iter.Seq2[T, error]
All iterates over every item of a paginated list, starting at opts.Page. Iteration stops at the first error, which is yielded with a zero item.
for repo, err := range gitoperationslib.All(ctx, opts, func(ctx context.Context, o gitoperationslib.ListOptions) (gitoperationslib.Page[gitoperationslib.Repo], error) {
return client.Repos().List(ctx, "owner", o)
}) { ... }
func IsForbidden ¶
func IsNotFound ¶
func IsUnauthorized ¶
func NotSupported ¶
NotSupported returns a *NotSupportedError.
func StatusCode ¶
StatusCode returns the HTTP status of the first *APIError in err's chain, or 0 if there is none.
Types ¶
type APIError ¶
type APIError struct {
Backend Backend `json:"backend"`
StatusCode int `json:"statusCode"`
Message string `json:"message"`
// DocumentationURL is GitHub's documentation_url or Forgejo's url field.
DocumentationURL string `json:"documentationUrl,omitzero"`
// Details holds GitHub's errors[] entries, flattened to strings.
Details []string `json:"details,omitzero"`
// RetryAt is when the server allows the request again: from Retry-After,
// or from a rate limit's reset time. Zero when the server did not say.
RetryAt time.Time `json:"retryAt,omitzero"`
// Err is the recognised refusal (ErrOwnsRepos, ErrBranchProtected…), or
// nil. It is what errors.Is and errors.As see through Unwrap.
Err error `json:"-"`
}
APIError is the normalised form of an error response from either backend.
type AccessToken ¶ added in v1.1.0
type AccessToken struct {
ID int64 `json:"id"`
Name string `json:"name"`
Scopes []string `json:"scopes"` // e.g. "write:repository", "all"
// Repositories limits the token to these repositories ("owner/name");
// empty means all of them.
Repositories []string `json:"repositories,omitzero"`
LastEight string `json:"lastEight"` // the secret's last eight characters
// Secret is the token itself, set by Create only. It is never
// serialised: print or store it explicitly.
Secret string `json:"-"`
}
AccessToken is a personal access token.
type Account ¶ added in v1.1.0
type Account interface {
Emails() Emails
SSHKeys() SSHKeys
GPGKeys() GPGKeys
Profile() Profile
// Tokens manages access tokens; Forgejo only (CapTokens).
Tokens() Tokens
}
Account manages the authenticated user's own account. The Forgejo, GitHub and Bitbucket clients implement it (CapAccount); find it with a type assertion:
acct, ok := client.(gitoperationslib.Account)
Parts a forge lacks return ErrNotSupported. Directory().Me() reads the same e-mail addresses and keys in one call, along with the rest of the account.
type AddSSHKeyOptions ¶ added in v1.1.0
type AddSSHKeyOptions struct {
Title string `json:"title"` // required
Key string `json:"key"` // required: "ssh-ed25519 AAAA… comment"
// ReadOnly asks for a key limited to reading. No backend can store one, so
// all of them refuse it with ErrNotSupported. Forgejo's API has the option
// but ignores it, and the key would be read-write.
ReadOnly bool `json:"readOnly,omitzero"`
}
AddSSHKeyOptions describes an SSH key to add.
type Admin ¶
Admin manages accounts. Only the Forgejo backend implements it; detect it with a type assertion (client.(gitoperationslib.Admin)) or CapAdmin.
type Allowlist ¶
type Allowlist struct {
Users []string `json:"users"` // logins
Teams []string `json:"teams"` // team names (GitHub: team slugs; organisations only)
}
Allowlist names users and teams exempt from a restriction. On GitHub, rules are rulesets whose exemptions ("bypass actors") can be teams but not individual users, so Users returns ErrNotSupported there.
type Asset ¶
type Asset struct {
ID int64 `json:"id"`
Name string `json:"name"`
Size int64 `json:"size"`
ContentType string `json:"contentType,omitzero"` // reported by GitHub only
DownloadCount int64 `json:"downloadCount"`
DownloadURL string `json:"downloadUrl"` // browser download URL
// External marks a Forgejo asset that links to a file hosted elsewhere
// (DownloadURL) instead of an uploaded file.
External bool `json:"external,omitzero"`
CreatedAt time.Time `json:"createdAt,omitzero"`
}
Asset is a file attached to a release.
type Branch ¶
type Branch struct {
Name string `json:"name"`
SHA string `json:"sha"` // head commit
Protected bool `json:"protected"`
IsDefault bool `json:"isDefault"`
// LastCommit describes the head commit. Get always reports it; List
// does on Forgejo and Bitbucket, but not on GitHub, whose branch list
// carries the commit SHA alone (nil there).
LastCommit *CommitSummary `json:"lastCommit,omitzero"`
}
Branch is a repository branch.
type BranchProtection ¶
type BranchProtection struct {
ID int64 `json:"id,omitzero"` // GitHub ruleset ID; 0 on Forgejo
// Pattern is a branch name or glob ("main", "release/*"). Rules are
// addressed by it.
Pattern string `json:"pattern"`
RequiredApprovals int `json:"requiredApprovals"`
DismissStaleApprovals bool `json:"dismissStaleApprovals"` // a new push dismisses earlier approvals
// RequiredStatusChecks lists the status check contexts that must pass.
RequiredStatusChecks []string `json:"requiredStatusChecks"`
// RequireUpToDate requires the branch to be up to date with the base
// before merging (GitHub strict checks; Forgejo blocks outdated
// branches).
RequireUpToDate bool `json:"requireUpToDate"`
RequireSignedCommits bool `json:"requireSignedCommits"`
// ApplyToAdmins enforces the rule for repository administrators too.
ApplyToAdmins bool `json:"applyToAdmins"`
// PushAllowlist restricts direct pushes to the listed users and teams;
// nil lets anyone with write access push. An empty Allowlist blocks
// direct pushes entirely (changes then go through pull requests).
PushAllowlist *Allowlist `json:"pushAllowlist,omitzero"`
AllowDeletion bool `json:"allowDeletion"` // Forgejo: not supported (protected branches cannot be deleted)
AllowForcePush bool `json:"allowForcePush"` // Forgejo: not supported
// GitHub only.
RequireLinearHistory bool `json:"requireLinearHistory,omitzero"`
RequireConversationResolution bool `json:"requireConversationResolution,omitzero"`
// Forgejo only.
MergeAllowlist *Allowlist `json:"mergeAllowlist,omitzero"` // who may merge pull requests; nil: anyone with write access
ApprovalsAllowlist *Allowlist `json:"approvalsAllowlist,omitzero"` // whose approvals count; nil: anyone with write access
BlockOnRejectedReviews bool `json:"blockOnRejectedReviews,omitzero"`
BlockOnOfficialReviewRequests bool `json:"blockOnOfficialReviewRequests,omitzero"`
ProtectedFilePatterns string `json:"protectedFilePatterns,omitzero"` // semicolon-separated globs
UnprotectedFilePatterns string `json:"unprotectedFilePatterns,omitzero"`
}
BranchProtection is a protection rule for the branches matching Pattern. On GitHub it is a branch ruleset; on Forgejo a branch protection rule.
Zero values are the protected choice: deletion and force pushes are blocked unless explicitly allowed.
type BranchProtections ¶
type BranchProtections interface {
List(ctx context.Context, owner, repo string) ([]BranchProtection, error)
Get(ctx context.Context, owner, repo, pattern string) (*BranchProtection, error)
Create(ctx context.Context, owner, repo string, rule BranchProtection) (*BranchProtection, error)
Update(ctx context.Context, owner, repo, pattern string, rule BranchProtection) (*BranchProtection, error)
Delete(ctx context.Context, owner, repo, pattern string) error
}
BranchProtections manages branch protection rules, addressed by pattern. Update replaces a rule entirely: Get it, change it, then Update.
type Branches ¶
type Branches interface {
// List returns the branches; IsDefault marks the default one.
List(ctx context.Context, owner, repo string, opts ListOptions) (Page[Branch], error)
Get(ctx context.Context, owner, repo, name string) (*Branch, error)
Create(ctx context.Context, owner, repo string, opts CreateBranchOptions) (*Branch, error)
// Rename renames a branch. Open pull requests and protection rules
// follow it.
Rename(ctx context.Context, owner, repo, name, newName string) (*Branch, error)
Delete(ctx context.Context, owner, repo, name string) error
// Compare counts the commits between base and head (branches, tags or
// commits): Ahead, those in head but not in base, and Behind, the
// reverse. Both are 0 when head and base point to the same commit.
Compare(ctx context.Context, owner, repo, base, head string) (*Comparison, error)
}
Branches manages repository branches. The default branch is changed with Repos().Edit.
type CI ¶ added in v1.1.0
CI manages the secrets and variables of CI workflows: Forgejo Actions, GitHub Actions, Bitbucket Pipelines (CapSecrets). Find it with a type assertion:
ci, ok := client.(gitoperationslib.CI)
type CIScope ¶ added in v1.1.0
type CIScope struct {
Owner string `json:"owner,omitzero"`
Repo string `json:"repo,omitzero"`
Environment string `json:"environment,omitzero"`
}
CIScope selects where CI secrets and variables live: a repository, one of its environments, an organisation or workspace (Repo empty), or the authenticated user (all empty).
func EnvCI ¶ added in v1.3.0
EnvCI is the scope of the secrets and variables of a repository's environment, on GitHub and Bitbucket (CapCIEnvironments); Forgejo has no environments and returns ErrNotSupported. The environment must exist: anything else is HTTP 404. The library does not create environments. A Bitbucket environment is named by its name or slug, ignoring case, or by its {UUID}; each call looks it up first. On a GitHub repository that is private, environments may need a paid plan.
func OrgCI ¶ added in v1.1.0
OrgCI is the scope of an organisation's (Bitbucket: workspace's) secrets and variables, available to all its repositories.
type Capability ¶
type Capability uint64
Capability is a bit set of features a Client supports.
const ( CapRepos Capability = 1 << iota CapMirrors // push mirrors and syncing mirrors (Mirrors) CapMigrate // reserved CapAdmin CapWebhooks CapSystemWebhooks // system and default webhooks (SiteHooks) CapReleases CapPullRequests CapExternalAssets CapBranches CapTags CapBranchProtection CapTagProtection CapIssues CapDirectory // Added in 1.1.0. New bits are only ever appended, so existing values // never change. CapAccount // the authenticated user's own account (Account) CapTokens // access token management (Account.Tokens) CapSecrets // CI secrets and variables (CI) CapCommits // commit history (History) // Added in 1.2.0. CapOrgAvatars // organisation avatars (OrgAvatars) // Added in 1.3.0. CapUserWebhooks // the authenticated user's webhooks (UserHooks) CapCommitDiffs // a commit's raw diff (CommitDiffs) CapPRContents // a pull request's diff, files and commits (PRContents) CapReviewComments // comments on a pull request's lines (ReviewComments) CapCollaborators // a repository's collaborators (Collaborators) CapGitHooks // a repository's server-side git hooks (GitHooks) CapHookDeliveries // a webhook's delivery history (HookDeliveries) CapCIEnvironments // secrets and variables of an environment (EnvCI) CapOrgSecrets // organisation secrets limited to some repositories (OrgSecrets) // CapCollaboratorInvitations: invitations not yet accepted (CollaboratorInvitations). CapCollaboratorInvitations )
func (Capability) Has ¶
func (c Capability) Has(want Capability) bool
Has reports whether c includes every capability in want.
func (Capability) String ¶
func (c Capability) String() string
String lists the named capabilities in c, separated by "|".
type ChangedFile ¶ added in v1.1.0
type ChangedFile struct {
Path string `json:"path"`
// PreviousPath is the old path of a renamed file. In a commit, Forgejo
// does not detect renames: it reports the old path removed and the new
// one added.
PreviousPath string `json:"previousPath,omitzero"`
Status FileStatus `json:"status"`
// Additions and Deletions count the file's changed lines. In a commit,
// they are always 0 on Forgejo, which only reports the totals
// (Commit.Stats).
Additions int `json:"additions"`
Deletions int `json:"deletions"`
}
ChangedFile is a file a commit or a pull request changed.
type Client ¶
type Client interface {
Backend() Backend
Capabilities() Capability
Repos() Repos
Releases() Releases
PullRequests() PullRequests
Webhooks() Webhooks
Branches() Branches
Tags() Tags
BranchProtections() BranchProtections
TagProtections() TagProtections
Issues() Issues
Labels() Labels
Milestones() Milestones
// Directory reads users, organisations and teams (CapDirectory).
Directory() Directory
}
Client is the entry point to a forge backend.
Areas a backend may not support are exposed through optional interfaces; check Capabilities, or use a type assertion, before relying on them.
type Collaborator ¶ added in v1.3.0
type Collaborator struct {
Login string `json:"login"`
// AccountID is the Atlassian account ID, on Bitbucket only.
AccountID string `json:"accountId,omitzero"`
// Permission is the user's level. On GitHub it can also be the name of an
// organisation's custom role. On Forgejo it is empty when the caller may
// not read it: only repository admins can, except for their own.
Permission CollaboratorPermission `json:"permission,omitzero"`
}
Collaborator is a user with their own access to a repository.
type CollaboratorInvitation ¶ added in v1.3.0
type CollaboratorInvitation struct {
ID int64 `json:"id"`
Login string `json:"login"`
Permission CollaboratorPermission `json:"permission"`
// Expired is true once the user can no longer accept it.
Expired bool `json:"expired,omitzero"`
HTMLURL string `json:"htmlUrl,omitzero"`
CreatedAt time.Time `json:"createdAt,omitzero"`
}
CollaboratorInvitation is an invitation a user has not accepted yet.
type CollaboratorInvitations ¶ added in v1.3.0
type CollaboratorInvitations interface {
ListCollaboratorInvitations(ctx context.Context, owner, repo string, opts ListOptions) (Page[CollaboratorInvitation], error)
}
CollaboratorInvitations lists who has been invited to a repository and has not accepted yet, which takes admin access to it. Only the GitHub backend implements it (CapCollaboratorInvitations): the other forges give access at once. Find it with a type assertion:
i, ok := client.(gitoperationslib.CollaboratorInvitations)
To withdraw an invitation, use Collaborators.RemoveCollaborator.
type CollaboratorPermission ¶ added in v1.3.0
type CollaboratorPermission string
CollaboratorPermission is a user's access level on a repository.
const ( CollaboratorRead CollaboratorPermission = "read" CollaboratorWrite CollaboratorPermission = "write" CollaboratorAdmin CollaboratorPermission = "admin" // CollaboratorTriage and CollaboratorMaintain only exist on GitHub. CollaboratorTriage CollaboratorPermission = "triage" CollaboratorMaintain CollaboratorPermission = "maintain" )
func (CollaboratorPermission) Valid ¶ added in v1.3.0
func (p CollaboratorPermission) Valid() bool
Valid reports whether p is one of the permissions above.
type Collaborators ¶ added in v1.3.0
type Collaborators interface {
// ListCollaborators lists those who were given access directly, not
// through a team. GitHub and Bitbucket usually include the repository's
// owner, Forgejo does not. Forgejo takes one more request per collaborator
// to read their permission.
ListCollaborators(ctx context.Context, owner, repo string, opts ListOptions) (Page[Collaborator], error)
// GetCollaborator returns a collaborator; the error is HTTP 404 for
// anybody else. On GitHub it also finds those with access through the
// organisation, and it takes two requests on Forgejo and GitHub.
GetCollaborator(ctx context.Context, owner, repo, user string) (*Collaborator, error)
// AddCollaborator gives user access to the repository, or changes the
// permission of an existing collaborator. invited is true when GitHub sent
// an invitation instead: the user has no access, and is not listed, until
// they accept it.
//
// Forgejo and Bitbucket only take read, write and admin, and return
// ErrNotSupported for the others. GitHub ignores the permission on a
// repository owned by a user, as opposed to an organisation.
AddCollaborator(ctx context.Context, owner, repo, user string, permission CollaboratorPermission) (invited bool, err error)
// RemoveCollaborator removes user's access; on GitHub it also withdraws a
// pending invitation, which takes more requests. Removing an existing user
// who has no access is not an error.
RemoveCollaborator(ctx context.Context, owner, repo, user string) error
}
Collaborators manages the users with their own access to a repository, which takes admin access to it. The Forgejo, GitHub and Bitbucket clients implement it (CapCollaborators); find it with a type assertion:
c, ok := client.(gitoperationslib.Collaborators)
On Bitbucket, a user is a nickname of a member of the workspace, an account ID or a {UUID}. To add someone from outside the workspace, use one of the last two.
type Comment ¶
type Comment struct {
ID int64 `json:"id"`
Author string `json:"author"`
Body string `json:"body"`
HTMLURL string `json:"htmlUrl"`
CreatedAt time.Time `json:"createdAt,omitzero"`
UpdatedAt time.Time `json:"updatedAt,omitzero"`
}
Comment is a comment on an issue or pull request.
type Commit ¶ added in v1.1.0
type Commit struct {
SHA string `json:"sha"`
Message string `json:"message"` // the full message; its first line is the title
Author CommitAuthor `json:"author"`
// Committer is not reported by Bitbucket.
Committer CommitAuthor `json:"committer,omitzero"`
Parents []string `json:"parents"` // parent SHAs; two or more for a merge
HTMLURL string `json:"htmlUrl"`
Stats *CommitStats `json:"stats,omitzero"`
// Files are the changes against the first parent.
Files []ChangedFile `json:"files,omitzero"`
}
Commit is a commit. Files and Stats are only filled by Commits.Get.
type CommitAuthor ¶ added in v1.1.0
type CommitAuthor struct {
Name string `json:"name"`
Email string `json:"email"`
// Login is the forge account matched to the e-mail address, if any
// (Bitbucket: the nickname).
Login string `json:"login,omitzero"`
Date time.Time `json:"date,omitzero"`
}
CommitAuthor is a commit's author or committer.
type CommitDiffs ¶ added in v1.3.0
type CommitDiffs interface {
// CommitDiff streams the changes of a commit against its first parent;
// the caller must close it. ref is a commit SHA, a branch or a tag.
CommitDiff(ctx context.Context, owner, repo, ref string, format DiffFormat) (io.ReadCloser, error)
}
CommitDiffs reads a commit's raw diff. The Forgejo, GitHub and Bitbucket clients implement it (CapCommitDiffs); find it with a type assertion:
d, ok := client.(gitoperationslib.CommitDiffs)
type CommitStats ¶ added in v1.1.0
CommitStats counts a commit's changed lines.
type CommitSummary ¶ added in v0.4.0
type CommitSummary struct {
Message string `json:"message"` // the full message; its first line is the title
Author string `json:"author"` // the author's name
Date time.Time `json:"date"` // the author date
}
CommitSummary describes a commit.
type Commits ¶ added in v1.1.0
type Commits interface {
// List returns the commits reachable from opts.Ref, newest first. Their
// Files and Stats are left empty: use Get for those.
List(ctx context.Context, owner, repo string, opts ListCommitsOptions) (Page[Commit], error)
// Get returns one commit with its changed files and line counts. ref is
// a commit SHA (full or abbreviated), a branch or a tag.
Get(ctx context.Context, owner, repo, ref string) (*Commit, error)
}
Commits lists and reads commits.
type Comparison ¶ added in v0.4.0
type Comparison struct {
Base string `json:"base"`
Head string `json:"head"`
Ahead int `json:"ahead"` // commits in Head that Base lacks
Behind int `json:"behind"` // commits in Base that Head lacks
}
Comparison tells how far apart two refs are.
type CreateBranchOptions ¶
type CreateBranchOptions struct {
Name string `json:"name"` // required
// From is the branch, tag or commit SHA to start from; empty means the
// default branch.
From string `json:"from,omitzero"`
}
CreateBranchOptions describes a branch to create.
type CreateIssueOptions ¶
type CreateIssueOptions struct {
Title string `json:"title"` // required
Body string `json:"body,omitzero"`
Labels []string `json:"labels,omitzero"` // names; they must exist
Assignees []string `json:"assignees,omitzero"`
Milestone int64 `json:"milestone,omitzero"` // Milestone.ID; 0 for none
}
CreateIssueOptions describes an issue to open.
type CreateMilestoneOptions ¶
type CreateMilestoneOptions struct {
Title string `json:"title"` // required
Description string `json:"description,omitzero"`
DueOn time.Time `json:"dueOn,omitzero"` // zero: none
}
CreateMilestoneOptions describes a milestone to create.
type CreateOrgOptions ¶
type CreateOrgOptions struct {
// Owner is the user who will own the organisation. Empty means the
// authenticated user; another user requires a site-admin token.
Owner string `json:"owner,omitzero"`
Name string `json:"name"` // required
FullName string `json:"fullName,omitzero"`
Description string `json:"description,omitzero"`
Website string `json:"website,omitzero"`
Location string `json:"location,omitzero"`
Email string `json:"email,omitzero"`
Visibility OwnerVisibility `json:"visibility,omitzero"` // zero value: backend default
RepoAdminChangeTeamAccess bool `json:"repoAdminChangeTeamAccess,omitzero"`
}
CreateOrgOptions describes an organisation to create.
type CreatePROptions ¶
type CreatePROptions struct {
Title string `json:"title"` // required
Body string `json:"body,omitzero"`
Head string `json:"head"` // branch with the changes; "user:branch" for a fork
Base string `json:"base"` // branch to merge into
// Draft opens the pull request as a draft. On Forgejo this adds the
// "WIP: " prefix to Title unless it already has a draft prefix.
Draft bool `json:"draft,omitzero"`
AllowMaintainerEdit *bool `json:"allowMaintainerEdit,omitzero"` // let base maintainers push to the head branch
}
CreatePROptions describes a pull request to open.
type CreatePushMirrorOptions ¶ added in v1.3.0
type CreatePushMirrorOptions struct {
// RemoteAddress must not hold credentials: the server refuses it.
RemoteAddress string `json:"remoteAddress"`
// Username and Password authenticate to an HTTP remote; both are stored
// by the server and never returned. They are incompatible with UseSSH.
Username string `json:"username,omitzero"`
Password string `json:"-"`
// UseSSH makes the server generate a key: see PushMirror.PublicKey.
UseSSH bool `json:"useSsh,omitzero"`
// Interval is the time between pushes; zero means no periodic push. The
// server refuses a shorter one than its minimum (by default ten minutes).
Interval time.Duration `json:"interval,omitzero"`
// SyncOnCommit also pushes after each commit.
SyncOnCommit bool `json:"syncOnCommit,omitzero"`
// BranchFilter limits the branches pushed, as a comma-separated list of
// names or patterns (main,release/*); empty means all of them.
BranchFilter string `json:"branchFilter,omitzero"`
}
CreatePushMirrorOptions describes a push mirror. RemoteAddress is required.
func (CreatePushMirrorOptions) Validate ¶ added in v1.3.0
func (o CreatePushMirrorOptions) Validate() error
Validate reports a missing or contradictory field.
type CreateReleaseOptions ¶
type CreateReleaseOptions struct {
TagName string `json:"tagName"` // required
TargetCommitish string `json:"targetCommitish,omitzero"`
Name string `json:"name,omitzero"`
Body string `json:"body,omitzero"`
Draft bool `json:"draft,omitzero"`
Prerelease bool `json:"prerelease,omitzero"`
// GenerateReleaseNotes asks the server to write the notes from merged
// pull requests (GitHub only).
GenerateReleaseNotes bool `json:"generateReleaseNotes,omitzero"`
// MakeLatest controls whether the release becomes the "latest" one;
// nil means the server decides (GitHub only).
MakeLatest *bool `json:"makeLatest,omitzero"`
// HideArchiveLinks hides the generated source archives (Forgejo only).
HideArchiveLinks *bool `json:"hideArchiveLinks,omitzero"`
}
CreateReleaseOptions describes a release to create.
If TagName does not exist yet, it is created from TargetCommitish (the default branch when empty). For a draft, both backends create the tag only when the draft is published.
type CreateRepoOptions ¶
type CreateRepoOptions struct {
// Owner is the user or organisation that will own the repository; the
// backend determines which. Empty means the authenticated user. Naming a
// user other than the authenticated one requires an admin token (Forgejo)
// and is not supported on GitHub.
Owner string `json:"owner,omitzero"`
Name string `json:"name"`
Description string `json:"description,omitzero"`
Visibility Visibility `json:"visibility,omitzero"` // zero value: backend default
DefaultBranch string `json:"defaultBranch,omitzero"`
Template bool `json:"template,omitzero"`
// AutoInit creates an initial commit, using Gitignores and License if set.
AutoInit bool `json:"autoInit,omitzero"`
// Gitignores lists gitignore template names. GitHub accepts at most one
// and returns ErrNotSupported otherwise.
Gitignores []string `json:"gitignores,omitzero"`
License string `json:"license,omitzero"` // license template name
}
CreateRepoOptions describes a repository to create.
type CreateReviewCommentOptions ¶ added in v1.3.0
type CreateReviewCommentOptions struct {
Path string `json:"path"`
Body string `json:"body"`
// Line is a line of the new version of the file, OldLine one of the old
// version (a removed line).
Line int `json:"line,omitzero"`
OldLine int `json:"oldLine,omitzero"`
// CommitID is the commit to comment on; empty means the pull request's
// head. Not supported on Bitbucket.
CommitID string `json:"commitId,omitzero"`
}
CreateReviewCommentOptions describes a line comment. Path, Body and exactly one of Line and OldLine are required.
func (CreateReviewCommentOptions) Validate ¶ added in v1.3.0
func (o CreateReviewCommentOptions) Validate() error
Validate reports a missing or contradictory field.
type CreateReviewOptions ¶
type CreateReviewOptions struct {
Event ReviewEvent `json:"event"` // required
Body string `json:"body,omitzero"` // required for request_changes and comment
CommitID string `json:"commitId,omitzero"` // empty: the current head
}
CreateReviewOptions submits a review. Authors cannot approve or request changes on their own pull requests.
type CreateTagOptions ¶
type CreateTagOptions struct {
Name string `json:"name"` // required
// Target is the branch, tag or commit SHA to tag; empty means the
// default branch.
Target string `json:"target,omitzero"`
// Message makes an annotated tag; empty makes a lightweight tag.
Message string `json:"message,omitzero"`
}
CreateTagOptions describes a tag to create. To publish a release for a tag, use Releases().Create, which also creates the tag when needed.
type CreateTeamOptions ¶
type CreateTeamOptions struct {
Name string `json:"name"` // required
Description string `json:"description,omitzero"`
Access TeamAccess `json:"access"` // required
IncludesAllRepos bool `json:"includesAllRepos,omitzero"`
CanCreateOrgRepo bool `json:"canCreateOrgRepo,omitzero"`
}
CreateTeamOptions describes a team to create.
type CreateTokenOptions ¶ added in v1.1.0
type CreateTokenOptions struct {
Name string `json:"name"` // required, unique per user
// Scopes are passed to the server unchecked; at least one is required
// ("all", "read:user", "write:repository"…).
Scopes []string `json:"scopes"`
// Repositories ("owner/name") limits the token to those repositories.
Repositories []string `json:"repositories,omitzero"`
}
CreateTokenOptions describes a token to create.
type CreateUserOptions ¶
type CreateUserOptions struct {
Login string `json:"login"` // required
Email string `json:"email"` // required
Password string `json:"-"`
FullName string `json:"fullName,omitzero"`
// MustChangePassword forces a password change at first sign-in.
// Nil means the Forgejo default, which is true.
MustChangePassword *bool `json:"mustChangePassword,omitzero"`
Visibility OwnerVisibility `json:"visibility,omitzero"` // zero value: backend default
Restricted bool `json:"restricted,omitzero"`
// SendNotify emails the user about the new account.
SendNotify bool `json:"sendNotify,omitzero"`
}
CreateUserOptions describes a user account to create.
type CreateWebhookOptions ¶
type CreateWebhookOptions struct {
URL string `json:"url"` // required
ContentType HookContentType `json:"contentType,omitzero"` // zero value: json
// Secret signs deliveries (see the webhook package). Strongly
// recommended.
Secret string `json:"-"`
Events []HookEvent `json:"events"` // required
Active *bool `json:"active,omitzero"` // nil: active
// BranchFilter limits push and branch events to matching branches, as a
// glob such as "{main,release/*}" (Forgejo only).
BranchFilter string `json:"branchFilter,omitzero"`
// AuthorizationHeader is sent with every delivery (Forgejo only).
AuthorizationHeader string `json:"-"`
// InsecureSSL delivers without checking the target's TLS certificate, so a
// third party could read or alter deliveries (GitHub, Bitbucket; on Forgejo
// it is an instance setting, and true returns ErrNotSupported).
InsecureSSL bool `json:"insecureSsl,omitzero"`
}
CreateWebhookOptions describes a webhook to create.
type CurrentUser ¶ added in v0.2.1
type CurrentUser struct {
User
// LoginName is the name used to sign in on an external authentication
// source (LDAP, OAuth…), and AuthSourceID that source; 0 for a local
// account. Forgejo only.
LoginName string `json:"loginName,omitzero"`
AuthSourceID int64 `json:"authSourceId,omitzero"`
UUID string `json:"uuid,omitzero"` // Bitbucket only
AccountID string `json:"accountId,omitzero"` // Atlassian account ID; Bitbucket only
// TwoFactorAuth reports whether two-factor authentication is enabled;
// nil when the backend does not tell. GitHub and Bitbucket only.
TwoFactorAuth *bool `json:"twoFactorAuth,omitzero"`
// Type is the account type ("User", "Bot"…); GitHub only.
Type string `json:"type,omitzero"`
Plan string `json:"plan,omitzero"` // GitHub only
Hireable bool `json:"hireable,omitzero"` // GitHub only
TwitterUsername string `json:"twitterUsername,omitzero"` // GitHub only
PublicRepos int `json:"publicRepos,omitzero"` // GitHub only
TotalPrivateRepos int64 `json:"totalPrivateRepos,omitzero"` // GitHub only
OwnedPrivateRepos int64 `json:"ownedPrivateRepos,omitzero"` // GitHub only
PublicGists int `json:"publicGists,omitzero"` // GitHub only
PrivateGists int `json:"privateGists,omitzero"` // GitHub only
DiskUsage int `json:"diskUsage,omitzero"` // in KiB; GitHub only
Collaborators int `json:"collaborators,omitzero"` // GitHub only
UpdatedAt time.Time `json:"updatedAt,omitzero"` // GitHub only
// Settings are the account preferences; Forgejo only.
Settings *UserSettings `json:"settings,omitzero"`
Emails []Email `json:"emails"`
Orgs []Org `json:"orgs"` // organisations the user belongs to, private memberships included
Teams []Team `json:"teams"`
// Repos are the repositories the user owns or reaches as a collaborator
// or organisation member, private ones included.
Repos []Repo `json:"repos"`
SSHKeys []SSHKey `json:"sshKeys"`
GPGKeys []GPGKey `json:"gpgKeys"`
// Incomplete is nil when every part was read; see UserInfo.Incomplete.
// A token lacking a scope (GitHub's user:email, read:public_key…)
// leaves the matching part empty and recorded here.
Incomplete error `json:"-"`
Missing []PartError `json:"missing,omitzero"` // see UserInfo.Missing
}
CurrentUser is the authenticated user, as returned by Directory.Me. Fields a backend does not report are left empty.
type DefaultWebhooks ¶ added in v1.3.0
type DefaultWebhooks interface {
// Create adds a default webhook. Forgejo silently drops event names it does
// not know; Create then returns the webhook together with an error.
Create(ctx context.Context, opts CreateWebhookOptions) (*Webhook, error)
Get(ctx context.Context, id int64) (*Webhook, error)
// Edit changes a webhook; dropped events are reported as in Create.
Edit(ctx context.Context, id int64, opts EditWebhookOptions) (*Webhook, error)
Delete(ctx context.Context, id int64) error
}
DefaultWebhooks manages default webhooks: templates copied into each repository created afterwards. Existing repositories are not affected, and the copies are independent repository webhooks: editing or deleting the default webhook leaves them as they are. There is no List: Forgejo's API cannot list them, so keep the ID that Create returns.
type DeleteUserOptions ¶
type DeleteUserOptions struct {
// Purge also deletes the user's repositories, organisation memberships
// and other content. Without it, deleting a user who still owns
// repositories fails.
Purge bool `json:"purge,omitzero"`
}
DeleteUserOptions controls user deletion.
type DiffFormat ¶ added in v1.3.0
type DiffFormat string
DiffFormat selects the format of a raw diff.
const ( // DiffUnified is a plain unified diff, as git diff prints it. DiffUnified DiffFormat = "diff" // DiffPatch is the mail-formatted patch git format-patch prints, with // each commit's author and message, ready for git am. DiffPatch DiffFormat = "patch" )
func (DiffFormat) Valid ¶ added in v1.3.0
func (f DiffFormat) Valid() bool
Valid reports whether f is one of the formats above.
type Directory ¶ added in v0.2.0
type Directory interface {
// Me returns the authenticated user as the credentials identify it, with
// everything the token may read about the account: private profile
// fields, e-mail addresses, memberships, repositories and keys. It is
// the only Directory method Bitbucket implements.
Me(ctx context.Context) (*CurrentUser, error)
// User returns a user account. Fields the server hides from the caller
// (e-mail, admin flags, last login…) are left empty.
User(ctx context.Context, login string) (*User, error)
// UserInfo returns a user with the organisations they belong to and the
// repositories they own, as far as the caller can see them.
UserInfo(ctx context.Context, login string) (*UserInfo, error)
Org(ctx context.Context, name string) (*Org, error)
// ListOrgs returns the organisations user belongs to; empty user means
// the authenticated user (whose private memberships are included).
ListOrgs(ctx context.Context, user string, opts ListOptions) (Page[Org], error)
// ListAllOrgs returns every organisation visible to the caller. On
// GitHub, NextPage is an opaque cursor rather than a page number: pass it
// back unchanged (All does).
ListAllOrgs(ctx context.Context, opts ListOptions) (Page[Org], error)
// OrgInfo returns an organisation with its teams, members and
// repositories, as far as the caller can see them.
OrgInfo(ctx context.Context, name string) (*OrgInfo, error)
// OrgMembers lists an organisation's members. Callers outside the
// organisation see its public members only.
OrgMembers(ctx context.Context, org string, opts ListOptions) (Page[User], error)
// ListTeams lists an organisation's teams. Forgejo shows them to
// organisation members only; GitHub hides secret teams from non-members.
ListTeams(ctx context.Context, org string, opts ListOptions) (Page[Team], error)
// Team returns the team of org called name (case-insensitive on
// Forgejo; the slug on GitHub).
Team(ctx context.Context, org, name string) (*Team, error)
// TeamInfo returns a team with its members and repositories.
TeamInfo(ctx context.Context, org, name string) (*TeamInfo, error)
TeamMembers(ctx context.Context, org, name string, opts ListOptions) (Page[User], error)
TeamRepos(ctx context.Context, org, name string, opts ListOptions) (Page[Repo], error)
}
Directory reads users, organisations and teams, with whatever rights the token has: a site admin sees everything, other users see what they could see in the web interface. Forgejo and GitHub implement it (CapDirectory); Bitbucket implements Me only and returns ErrNotSupported elsewhere.
Teams are addressed by organisation and name (GitHub: the team slug), the only addressing both forges share. Account management (creating, editing, deleting) is in Admin.
type EditAssetOptions ¶
type EditAssetOptions struct {
Name *string `json:"name,omitzero"`
}
EditAssetOptions changes an asset. Nil fields are left unchanged.
type EditIssueOptions ¶
type EditIssueOptions struct {
Title *string `json:"title,omitzero"`
Body *string `json:"body,omitzero"`
State *IssueState `json:"state,omitzero"` // close or reopen
Labels *[]string `json:"labels,omitzero"`
Assignees *[]string `json:"assignees,omitzero"`
Milestone *int64 `json:"milestone,omitzero"` // 0 removes the milestone
}
EditIssueOptions changes an issue. Nil fields are left unchanged; non-nil slices replace the current values (an empty slice clears them).
type EditLabelOptions ¶
type EditLabelOptions struct {
Name *string `json:"name,omitzero"` // renames the label
Color *string `json:"color,omitzero"`
Description *string `json:"description,omitzero"`
}
EditLabelOptions changes a label. Nil fields are left unchanged.
type EditMilestoneOptions ¶
type EditMilestoneOptions struct {
Title *string `json:"title,omitzero"`
Description *string `json:"description,omitzero"`
State *MilestoneState `json:"state,omitzero"` // close or reopen
DueOn *time.Time `json:"dueOn,omitzero"`
}
EditMilestoneOptions changes a milestone. Nil fields are left unchanged.
type EditOrgOptions ¶
type EditOrgOptions struct {
FullName *string `json:"fullName,omitzero"`
Description *string `json:"description,omitzero"`
Website *string `json:"website,omitzero"`
Location *string `json:"location,omitzero"`
Email *string `json:"email,omitzero"`
Visibility *OwnerVisibility `json:"visibility,omitzero"`
RepoAdminChangeTeamAccess *bool `json:"repoAdminChangeTeamAccess,omitzero"`
}
EditOrgOptions changes an organisation. Nil fields are left unchanged.
type EditPROptions ¶
type EditPROptions struct {
Title *string `json:"title,omitzero"`
Body *string `json:"body,omitzero"`
Base *string `json:"base,omitzero"`
// State closes (PRStateClosed) or reopens (PRStateOpen) the pull request.
State *PRState `json:"state,omitzero"`
// Draft converts to or from a draft. Forgejo adds or removes the title
// prefix; GitHub uses its GraphQL API.
Draft *bool `json:"draft,omitzero"`
AllowMaintainerEdit *bool `json:"allowMaintainerEdit,omitzero"`
}
EditPROptions changes a pull request. Nil fields are left unchanged.
type EditProfileOptions ¶ added in v1.1.0
type EditProfileOptions struct {
FullName *string `json:"fullName,omitzero"`
Description *string `json:"description,omitzero"` // GitHub: bio
Website *string `json:"website,omitzero"` // GitHub: blog
Location *string `json:"location,omitzero"`
// Forgejo only.
Pronouns *string `json:"pronouns,omitzero"`
Language *string `json:"language,omitzero"` // interface language, e.g. "fr-FR"
Settings *EditSettings `json:"settings,omitzero"`
// GitHub only.
Company *string `json:"company,omitzero"`
// PublicEmail is the address shown on the profile: one of the verified
// addresses, or "" to show none.
PublicEmail *string `json:"publicEmail,omitzero"`
Hireable *bool `json:"hireable,omitzero"`
TwitterUsername *string `json:"twitterUsername,omitzero"`
}
EditProfileOptions changes the authenticated user's profile. Nil fields are left unchanged; an empty string clears a field.
type EditReleaseOptions ¶
type EditReleaseOptions struct {
TagName *string `json:"tagName,omitzero"`
TargetCommitish *string `json:"targetCommitish,omitzero"`
Name *string `json:"name,omitzero"`
Body *string `json:"body,omitzero"`
Draft *bool `json:"draft,omitzero"`
Prerelease *bool `json:"prerelease,omitzero"`
MakeLatest *bool `json:"makeLatest,omitzero"` // GitHub only
HideArchiveLinks *bool `json:"hideArchiveLinks,omitzero"` // Forgejo only
}
EditReleaseOptions changes a release. Nil fields are left unchanged. Setting Draft to false publishes a draft.
type EditRepoOptions ¶
type EditRepoOptions struct {
Name *string `json:"name,omitzero"`
Description *string `json:"description,omitzero"`
Website *string `json:"website,omitzero"`
Visibility *Visibility `json:"visibility,omitzero"`
DefaultBranch *string `json:"defaultBranch,omitzero"`
Archived *bool `json:"archived,omitzero"`
Template *bool `json:"template,omitzero"`
}
EditRepoOptions changes repository settings. Nil fields are left unchanged; use Ptr to set a value.
type EditSettings ¶ added in v1.1.0
type EditSettings struct {
Theme *string `json:"theme,omitzero"`
DiffViewStyle *string `json:"diffViewStyle,omitzero"` // "unified" or "split"
HideEmail *bool `json:"hideEmail,omitzero"`
HideActivity *bool `json:"hideActivity,omitzero"`
HidePronouns *bool `json:"hidePronouns,omitzero"`
EnableRepoUnitHints *bool `json:"enableRepoUnitHints,omitzero"`
}
EditSettings changes a Forgejo user's preferences (see UserSettings). Nil fields are left unchanged. Forgejo stores any Theme value, even one the instance does not offer.
type EditTeamOptions ¶
type EditTeamOptions struct {
Name *string `json:"name,omitzero"`
Description *string `json:"description,omitzero"`
Access *TeamAccess `json:"access,omitzero"`
IncludesAllRepos *bool `json:"includesAllRepos,omitzero"`
CanCreateOrgRepo *bool `json:"canCreateOrgRepo,omitzero"`
}
EditTeamOptions changes a team. Nil fields are left unchanged.
type EditUserOptions ¶
type EditUserOptions struct {
Email *string `json:"email,omitzero"`
FullName *string `json:"fullName,omitzero"`
Description *string `json:"description,omitzero"`
Website *string `json:"website,omitzero"`
Location *string `json:"location,omitzero"`
Password *string `json:"-"`
MustChangePassword *bool `json:"mustChangePassword,omitzero"`
Visibility *OwnerVisibility `json:"visibility,omitzero"`
Admin *bool `json:"admin,omitzero"`
Active *bool `json:"active,omitzero"`
ProhibitLogin *bool `json:"prohibitLogin,omitzero"`
Restricted *bool `json:"restricted,omitzero"`
AllowCreateOrganization *bool `json:"allowCreateOrganization,omitzero"`
MaxRepoCreation *int `json:"maxRepoCreation,omitzero"` // -1 means the instance default
}
EditUserOptions changes a user account. Nil fields are left unchanged.
type EditWebhookOptions ¶
type EditWebhookOptions struct {
URL *string `json:"url,omitzero"`
ContentType *HookContentType `json:"contentType,omitzero"`
Secret *string `json:"-"`
Events []HookEvent `json:"events,omitzero"`
Active *bool `json:"active,omitzero"`
BranchFilter *string `json:"branchFilter,omitzero"` // Forgejo only
AuthorizationHeader *string `json:"-"` // Forgejo only
InsecureSSL *bool `json:"insecureSsl,omitzero"` // see CreateWebhookOptions
}
EditWebhookOptions changes a webhook. Nil fields are left unchanged; a non-nil Events replaces the subscription list.
type Email ¶ added in v0.2.1
type Email struct {
Address string `json:"address"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
// Visibility is "public" or "private"; GitHub only, and only for the
// primary address.
Visibility string `json:"visibility,omitzero"`
}
Email is one of the authenticated user's e-mail addresses.
type Emails ¶ added in v1.1.0
type Emails interface {
List(ctx context.Context) ([]Email, error)
// Add adds addresses and returns them as the server reports them. GitHub
// sends each a verification e-mail; Forgejo too when the instance requires
// confirmation, and otherwise reports them verified at once.
Add(ctx context.Context, addresses ...string) ([]Email, error)
// Delete removes addresses. The primary address cannot be removed.
Delete(ctx context.Context, addresses ...string) error
}
Emails manages the authenticated user's e-mail addresses. Bitbucket only lists them.
type ExternalAssets ¶
type ExternalAssets interface {
AddExternalAsset(ctx context.Context, owner, repo string, releaseID int64, name, url string) (*Asset, error)
}
ExternalAssets adds release assets that link to files hosted elsewhere. Only the Forgejo backend implements it (CapExternalAssets), on the value returned by Releases():
ext, ok := client.Releases().(gitoperationslib.ExternalAssets)
type FileStatus ¶ added in v1.1.0
type FileStatus string
FileStatus is how a commit changed a file. Values other than the constants (GitHub's "copied", "changed"…) are passed through unchanged.
const ( FileAdded FileStatus = "added" FileModified FileStatus = "modified" FileRemoved FileStatus = "removed" FileRenamed FileStatus = "renamed" )
type GPGKey ¶ added in v0.2.1
type GPGKey struct {
ID int64 `json:"id"`
KeyID string `json:"keyId"`
PublicKey string `json:"publicKey"`
Emails []GPGKeyEmail `json:"emails"`
Subkeys []GPGKey `json:"subkeys,omitzero"`
CanSign bool `json:"canSign"`
CanEncryptComms bool `json:"canEncryptComms"`
CanEncryptStorage bool `json:"canEncryptStorage"`
CanCertify bool `json:"canCertify"`
Verified bool `json:"verified,omitzero"` // Forgejo only
CreatedAt time.Time `json:"createdAt,omitzero"`
ExpiresAt time.Time `json:"expiresAt,omitzero"` // zero if the key does not expire
}
GPGKey is a GPG key of the authenticated user.
type GPGKeyEmail ¶ added in v0.2.1
GPGKeyEmail is an e-mail address bound to a GPG key.
type GPGKeys ¶ added in v1.1.0
type GPGKeys interface {
List(ctx context.Context, opts ListOptions) (Page[GPGKey], error)
Get(ctx context.Context, id int64) (*GPGKey, error)
// Add uploads an armored public key. armoredSignature is optional: a
// detached, armored signature of VerificationToken's token, which marks
// the key verified (Forgejo only; ErrNotSupported elsewhere when set).
Add(ctx context.Context, armoredPublicKey, armoredSignature string) (*GPGKey, error)
Delete(ctx context.Context, id int64) error
// VerificationToken returns the token to sign, e.g. with
// "echo -n TOKEN | gpg -a --default-key KEYID --detach-sig". It changes
// over time. Forgejo only.
VerificationToken(ctx context.Context) (string, error)
// Verify marks an added key verified, from a detached, armored signature
// of the token. keyID is GPGKey.KeyID. Forgejo only. Forgejo 15 cannot
// verify a key whose ID starts with 0 (HTTP 500, matching
// ErrNotSupported): delete such a key and Add it again with the
// signature instead.
Verify(ctx context.Context, keyID, armoredSignature string) (*GPGKey, error)
}
GPGKeys manages the authenticated user's GPG keys.
On Forgejo a key is "verified" once its owner has proven they hold it, by signing a token from VerificationToken. A key whose e-mail addresses are all unknown to the account can only be added with such a signature. Bitbucket identifies keys by fingerprint: GPGKey.ID is derived from it.
type GitHook ¶ added in v1.3.0
type GitHook struct {
Name string `json:"name"`
Active bool `json:"active"`
Content string `json:"content,omitzero"` // empty when not Active
}
GitHook is a server-side git hook.
type GitHooks ¶ added in v1.3.0
type GitHooks interface {
// ListGitHooks returns the hooks a repository can have, in use or not:
// pre-receive, update and post-receive. There are no pages.
ListGitHooks(ctx context.Context, owner, repo string) ([]GitHook, error)
// GetGitHook is HTTP 404 for a name that is not a git hook, and returns one
// that is not in use with Active false.
GetGitHook(ctx context.Context, owner, repo, name string) (*GitHook, error)
// SetGitHook writes a hook's script, which puts it in use at once. A script
// that exits with an error can refuse every push, the server's own included.
SetGitHook(ctx context.Context, owner, repo, name, content string) (*GitHook, error)
// DeleteGitHook takes a hook out of use. It is not an error if it was not in
// use.
DeleteGitHook(ctx context.Context, owner, repo, name string) error
}
GitHooks manages the git hooks of a repository: scripts the server runs when it receives a push, for instance to refuse it. Only the Forgejo backend implements it (CapGitHooks); find it with a type assertion:
h, ok := client.(gitoperationslib.GitHooks)
A hook runs on the server with the server's rights, so editing one amounts to running code there. Forgejo therefore refuses all of these with HTTP 403, even for a site admin, unless the instance sets DISABLE_GIT_HOOKS=false, and then allows only site admins and users given that right.
type History ¶ added in v1.1.0
type History interface {
Commits() Commits
}
History reads a repository's commits from the server, like git log: no local clone is needed, and only commits that were pushed are seen. The Forgejo, GitHub and Bitbucket clients implement it (CapCommits); find it with a type assertion:
h, ok := client.(gitoperationslib.History)
type HookContentType ¶
type HookContentType string
HookContentType is the encoding of webhook payloads.
const ( HookContentJSON HookContentType = "json" HookContentForm HookContentType = "form" // payload=<json>, URL-encoded )
type HookDeliveries ¶ added in v1.3.0
type HookDeliveries interface {
// ListHookDeliveries lists deliveries, newest first, without the request
// and response. GitHub keeps them for a few days.
ListHookDeliveries(ctx context.Context, scope HookScope, hookID int64, opts ListHookDeliveriesOptions) (HookDeliveryPage, error)
// GetHookDelivery returns a delivery with its request and response.
GetHookDelivery(ctx context.Context, scope HookScope, hookID, id int64) (*HookDelivery, error)
// RedeliverHook queues a delivery to be sent again, and returns at once.
// It shows up as a new delivery, with Redelivery set.
RedeliverHook(ctx context.Context, scope HookScope, hookID, id int64) error
}
HookDeliveries reads a webhook's delivery history and sends deliveries again. Only the GitHub backend implements it (CapHookDeliveries): the APIs of Forgejo and Bitbucket have no such history. Find it with a type assertion:
d, ok := client.(gitoperationslib.HookDeliveries)
type HookDelivery ¶ added in v1.3.0
type HookDelivery struct {
ID int64 `json:"id"`
// GUID is the delivery's X-GitHub-Delivery, shared by its redeliveries.
GUID string `json:"guid"`
Event string `json:"event"`
Action string `json:"action,omitzero"`
Status string `json:"status"` // "OK", or what went wrong
StatusCode int `json:"statusCode"` // the target's answer; 502 if GitHub cannot reach it
Redelivery bool `json:"redelivery"`
Duration time.Duration `json:"duration,omitzero"`
DeliveredAt time.Time `json:"deliveredAt,omitzero"`
// The rest is set by GetHookDelivery only. To decode RequestPayload with the
// webhook package, compact it first: that gives the bytes GitHub signed.
RequestHeaders map[string]string `json:"requestHeaders,omitzero"`
RequestPayload json.RawMessage `json:"requestPayload,omitzero"`
ResponseHeaders map[string]string `json:"responseHeaders,omitzero"`
ResponseBody string `json:"responseBody,omitzero"`
}
HookDelivery is one attempt to deliver an event to a webhook.
type HookDeliveryPage ¶ added in v1.3.0
type HookDeliveryPage struct {
Items []HookDelivery `json:"items"`
// NextCursor is the cursor of the next page, or empty on the last one.
NextCursor string `json:"nextCursor"`
}
HookDeliveryPage is a page of deliveries.
type HookEvent ¶
type HookEvent string
HookEvent is an event a webhook subscribes to. The constants use GitHub's names and are translated for Forgejo; other values are passed to the server unchanged, for backend-specific events.
const ( HookEventPush HookEvent = "push" HookEventCreate HookEvent = "create" // branch or tag created HookEventDelete HookEvent = "delete" // branch or tag deleted HookEventFork HookEvent = "fork" HookEventRelease HookEvent = "release" HookEventIssues HookEvent = "issues" HookEventIssueComment HookEvent = "issue_comment" HookEventPullRequest HookEvent = "pull_request" HookEventPullRequestReview HookEvent = "pull_request_review" HookEventRepository HookEvent = "repository" HookEventWiki HookEvent = "wiki" // GitHub: gollum // HookEventAll subscribes to everything. Only GitHub has a wildcard, which // also covers events added later, and reports it back as "*". For the // others the library sends the events it knows, which come back one by one. HookEventAll HookEvent = "*" )
type HookScope ¶
HookScope selects where webhooks live: a repository, or an organisation when Repo is empty.
type Issue ¶
type Issue struct {
Number int `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
State IssueState `json:"state"`
Author string `json:"author"`
Labels []string `json:"labels"` // names
Assignees []string `json:"assignees"` // logins
Milestone *Milestone `json:"milestone,omitzero"`
Comments int `json:"comments"`
Locked bool `json:"locked"`
HTMLURL string `json:"htmlUrl"`
CreatedAt time.Time `json:"createdAt,omitzero"`
UpdatedAt time.Time `json:"updatedAt,omitzero"`
ClosedAt time.Time `json:"closedAt,omitzero"`
}
Issue is an issue. Issues and pull requests share one number sequence; label, assignee and milestone methods also work on pull requests.
type IssueState ¶
type IssueState string
IssueState is the state of an issue. IssueStateAll is only meaningful as a List filter.
const ( IssueStateOpen IssueState = "open" IssueStateClosed IssueState = "closed" IssueStateAll IssueState = "all" )
type Issues ¶
type Issues interface {
List(ctx context.Context, owner, repo string, opts ListIssuesOptions) (Page[Issue], error)
Get(ctx context.Context, owner, repo string, number int) (*Issue, error)
Create(ctx context.Context, owner, repo string, opts CreateIssueOptions) (*Issue, error)
Edit(ctx context.Context, owner, repo string, number int, opts EditIssueOptions) (*Issue, error)
// Delete removes an issue permanently (repository admins only; GitHub
// through GraphQL).
Delete(ctx context.Context, owner, repo string, number int) error
AddLabels(ctx context.Context, owner, repo string, number int, labels []string) error
RemoveLabel(ctx context.Context, owner, repo string, number int, label string) error
ListComments(ctx context.Context, owner, repo string, number int, opts ListOptions) (Page[Comment], error)
CreateComment(ctx context.Context, owner, repo string, number int, body string) (*Comment, error)
EditComment(ctx context.Context, owner, repo string, id int64, body string) (*Comment, error)
DeleteComment(ctx context.Context, owner, repo string, id int64) error
}
Issues manages issues and their comments. Label and comment methods also accept pull request numbers.
type Label ¶
type Label struct {
ID int64 `json:"id"`
Name string `json:"name"`
Color string `json:"color"` // six hex digits, lower case, without "#"
Description string `json:"description"`
}
Label is a repository label.
type Labels ¶
type Labels interface {
List(ctx context.Context, owner, repo string, opts ListOptions) (Page[Label], error)
Get(ctx context.Context, owner, repo, name string) (*Label, error)
Create(ctx context.Context, owner, repo string, label Label) (*Label, error)
Edit(ctx context.Context, owner, repo, name string, opts EditLabelOptions) (*Label, error)
Delete(ctx context.Context, owner, repo, name string) error
}
Labels manages repository labels, addressed by name.
type ListCommitsOptions ¶ added in v1.1.0
type ListCommitsOptions struct {
ListOptions
// Ref is the branch, tag or commit to start from; empty means the
// default branch.
Ref string `json:"ref,omitzero"`
// Path keeps the commits that touched this file or directory. Forgejo
// then ignores PerPage.
Path string `json:"path,omitzero"`
// Since and Until keep the commits authored in that interval. GitHub
// only; ErrNotSupported elsewhere.
Since time.Time `json:"since,omitzero"`
Until time.Time `json:"until,omitzero"`
// Exclude leaves out the commits reachable from this branch, tag or
// commit, like git log Exclude..Ref. On GitHub, which needs a comparison
// for this, it takes one more request per page, and cannot be combined
// with Path, Since, Until or Author (ErrNotSupported).
Exclude string `json:"exclude,omitzero"`
// Author keeps the commits of this account or e-mail address. GitHub
// only; ErrNotSupported elsewhere.
Author string `json:"author,omitzero"`
}
ListCommitsOptions selects commits.
type ListHookDeliveriesOptions ¶ added in v1.3.0
type ListHookDeliveriesOptions struct {
// Cursor is HookDeliveryPage.NextCursor of the previous page: this list has
// no page numbers, so gitoperationslib.All does not apply.
Cursor string `json:"cursor,omitzero"`
PerPage int `json:"perPage,omitzero"`
}
ListHookDeliveriesOptions selects a page of deliveries.
type ListIssuesOptions ¶
type ListIssuesOptions struct {
ListOptions
State IssueState `json:"state,omitzero"` // zero value: open
Labels []string `json:"labels,omitzero"` // issues carrying all these labels
}
ListIssuesOptions selects issues to list. Pull requests are never included.
type ListOptions ¶
type ListOptions struct {
Page int `json:"page,omitzero"` // 1-based
PerPage int `json:"perPage,omitzero"`
}
ListOptions selects one page of a list call. Zero values mean "first page" and "backend default page size".
type ListPROptions ¶
type ListPROptions struct {
ListOptions
State PRState `json:"state,omitzero"` // zero value: open
}
ListPROptions selects pull requests to list.
type MergeMethod ¶
type MergeMethod string
MergeMethod is the strategy used to merge a pull request. Values match Forgejo's "Do" field; the GitHub backend supports only MergeMethodMerge, MergeMethodSquash and MergeMethodRebase.
MergeMethodRebase replays the commits without a merge commit; MergeMethodRebaseMerge rebases and then adds a merge commit; MergeMethodManuallyMerged only marks a pull request whose commits are already in the base branch as merged.
const ( MergeMethodMerge MergeMethod = "merge" MergeMethodRebase MergeMethod = "rebase" MergeMethodRebaseMerge MergeMethod = "rebase-merge" MergeMethodSquash MergeMethod = "squash" MergeMethodFastForwardOnly MergeMethod = "fast-forward-only" MergeMethodManuallyMerged MergeMethod = "manually-merged" )
func (MergeMethod) Valid ¶
func (m MergeMethod) Valid() bool
Valid reports whether m is one of the named merge methods.
type MergeOptions ¶
type MergeOptions struct {
// Method defaults to MergeMethodMerge. GitHub supports only merge,
// squash and rebase.
Method MergeMethod `json:"method,omitzero"`
Title string `json:"title,omitzero"` // merge or squash commit title; empty: server default
Message string `json:"message,omitzero"` // commit message body; empty: server default
// HeadSHA makes the merge fail unless the head branch is still at this
// commit.
HeadSHA string `json:"headSha,omitzero"`
// DeleteBranch deletes the head branch after a successful merge.
DeleteBranch bool `json:"deleteBranch,omitzero"`
// WhenChecksSucceed schedules the merge for when status checks pass;
// cancel it with CancelAutoMerge. GitHub (through GraphQL) accepts it
// only in repositories that allow auto-merge, while the pull request
// still waits for a required check, and not together with DeleteBranch.
WhenChecksSucceed bool `json:"whenChecksSucceed,omitzero"`
}
MergeOptions controls a merge.
type Milestone ¶
type Milestone struct {
// ID addresses the milestone: Forgejo's ID, GitHub's milestone number.
ID int64 `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
State MilestoneState `json:"state"`
DueOn time.Time `json:"dueOn,omitzero"` // zero if none
OpenIssues int `json:"openIssues"`
ClosedIssues int `json:"closedIssues"`
ClosedAt time.Time `json:"closedAt,omitzero"`
}
Milestone is a repository milestone.
type MilestoneState ¶
type MilestoneState string
MilestoneState is the state of a milestone; MilestoneStateAll is only meaningful as a List filter.
const ( MilestoneStateOpen MilestoneState = "open" MilestoneStateClosed MilestoneState = "closed" MilestoneStateAll MilestoneState = "all" )
type Milestones ¶
type Milestones interface {
List(ctx context.Context, owner, repo string, state MilestoneState, opts ListOptions) (Page[Milestone], error)
Get(ctx context.Context, owner, repo string, id int64) (*Milestone, error)
Create(ctx context.Context, owner, repo string, opts CreateMilestoneOptions) (*Milestone, error)
Edit(ctx context.Context, owner, repo string, id int64, opts EditMilestoneOptions) (*Milestone, error)
Delete(ctx context.Context, owner, repo string, id int64) error
}
Milestones manages repository milestones, addressed by Milestone.ID.
type Mirrors ¶ added in v1.3.0
type Mirrors interface {
ListPushMirrors(ctx context.Context, owner, repo string, opts ListOptions) (Page[PushMirror], error)
// GetPushMirror finds a push mirror by PushMirror.Name.
GetPushMirror(ctx context.Context, owner, repo, name string) (*PushMirror, error)
// CreatePushMirror adds a push mirror; the server chooses its name. It
// does not contact the remote, so a wrong address or password only shows
// in PushMirror.LastError after a sync. A remote the server refuses, for
// instance a host that does not resolve, gives HTTP 400.
CreatePushMirror(ctx context.Context, owner, repo string, opts CreatePushMirrorOptions) (*PushMirror, error)
DeletePushMirror(ctx context.Context, owner, repo, name string) error
// SyncPushMirrors pushes to all of the repository's push mirrors, and
// returns when that is done; Forgejo cannot sync just one. The first that
// fails gives HTTP 500 naming it, with the reason in its
// PushMirror.LastError, and those after it are not pushed. A branch can
// take a moment to show on a remote that is a forge.
SyncPushMirrors(ctx context.Context, owner, repo string) error
// SyncMirror queues a fetch for a pull mirror and returns at once. It is
// HTTP 400 for a repository that is not a mirror.
SyncMirror(ctx context.Context, owner, repo string) error
}
Mirrors manages a repository's mirrors, which takes admin access to it. The Forgejo client implements it (CapMirrors); find it with a type assertion:
m, ok := client.(gitoperationslib.Mirrors)
A push mirror sends the repository to another address. A pull mirror is a repository that copies another one, and Repo.Mirror reports it; the library cannot create one, as that takes a migration.
type NotSupportedError ¶
type NotSupportedError struct {
Backend Backend `json:"backend"`
Operation string `json:"operation"`
Reason string `json:"reason,omitzero"` // optional
}
NotSupportedError describes which operation a backend refused.
func (*NotSupportedError) Error ¶
func (e *NotSupportedError) Error() string
func (*NotSupportedError) Is ¶
func (e *NotSupportedError) Is(target error) bool
type Org ¶
type Org struct {
ID int64 `json:"id"`
Name string `json:"name"`
FullName string `json:"fullName"`
Description string `json:"description"`
Website string `json:"website"`
Location string `json:"location"`
Email string `json:"email"`
Visibility OwnerVisibility `json:"visibility"`
AvatarURL string `json:"avatarUrl"`
HTMLURL string `json:"htmlUrl,omitzero"` // GitHub only
// RepoAdminChangeTeamAccess lets repository admins change team access.
RepoAdminChangeTeamAccess bool `json:"repoAdminChangeTeamAccess,omitzero"`
}
Org is an organisation.
type OrgAvatars ¶ added in v1.2.0
type OrgAvatars interface {
// SetOrgAvatar uploads image (PNG, JPEG, GIF…; at most MaxAvatarSize bytes)
// as org's avatar. The server checks the image: Forgejo answers HTTP 500
// for an unknown format or an image wider or taller than 4096 pixels.
SetOrgAvatar(ctx context.Context, org string, image io.Reader) error
// DeleteOrgAvatar restores org's default avatar. It succeeds when org has
// none.
DeleteOrgAvatar(ctx context.Context, org string) error
}
OrgAvatars sets and deletes organisation avatars. Only the Forgejo backend implements it (CapOrgAvatars); find it with a type assertion:
avatars, ok := client.(gitoperationslib.OrgAvatars)
The caller must own the organisation or be a site admin (HTTP 403 otherwise), and a token needs the write:organization scope.
type OrgInfo ¶ added in v0.2.0
type OrgInfo struct {
Org
Teams []Team `json:"teams"`
Members []User `json:"members"` // non-members only see public members
Repos []Repo `json:"repos"`
// Incomplete is nil when every part was read; see UserInfo.Incomplete.
Incomplete error `json:"-"`
Missing []PartError `json:"missing,omitzero"` // see UserInfo.Missing
}
OrgInfo is an organisation with the teams, members and repositories the caller can see.
type OrgSecrets ¶ added in v1.3.0
type OrgSecrets interface {
// GetOrgSecretAccess returns who can use a secret.
GetOrgSecretAccess(ctx context.Context, org, name string) (*SecretAccess, error)
// SetOrgSecret creates a secret or replaces it, with its value and access.
SetOrgSecret(ctx context.Context, org, name, value string, access SecretAccess) error
// SetOrgSecretRepos replaces the repositories that can use a secret. GitHub
// answers HTTP 409 unless its visibility is SecretVisibleSelected.
SetOrgSecretRepos(ctx context.Context, org, name string, repos []string) error
}
OrgSecrets limits organisation secrets to some repositories. Only the GitHub backend implements it (CapOrgSecrets): the secrets of a Forgejo organisation or a Bitbucket workspace are available to all its repositories. Find it with a type assertion:
s, ok := client.(gitoperationslib.OrgSecrets)
Each repository named takes one more request, to find its ID. A secret's value cannot be read back, so changing its visibility takes SetOrgSecret, with the value.
type Orgs ¶
type Orgs interface {
Get(ctx context.Context, name string) (*Org, error)
// List returns the organisations user belongs to. Empty user means the
// authenticated user.
List(ctx context.Context, user string, opts ListOptions) (Page[Org], error)
// ListAll returns every organisation visible to the authenticated user
// (all of them for a site admin).
ListAll(ctx context.Context, opts ListOptions) (Page[Org], error)
Create(ctx context.Context, opts CreateOrgOptions) (*Org, error)
Edit(ctx context.Context, name string, opts EditOrgOptions) (*Org, error)
// Rename changes an organisation's name. The old name keeps redirecting
// to the new one.
Rename(ctx context.Context, name, newName string) error
// Delete removes an organisation. It fails while the organisation still
// owns repositories.
Delete(ctx context.Context, name string) error
Members(ctx context.Context, org string, opts ListOptions) (Page[User], error)
// IsMember reports whether user belongs to org. A user that does not
// exist is reported as not a member.
IsMember(ctx context.Context, org, user string) (bool, error)
// RemoveMember removes user from org and all its teams. Removing the last
// owner fails.
RemoveMember(ctx context.Context, org, user string) error
}
Orgs manages organisations and their membership. Members join an organisation through its teams; there is no direct "add member".
type OwnerVisibility ¶
type OwnerVisibility string
OwnerVisibility is the visibility of a user or organisation profile. The zero value means "use the backend default" in option structs.
const ( OwnerVisibilityPublic OwnerVisibility = "public" // OwnerVisibilityLimited is visible to signed-in users only. OwnerVisibilityLimited OwnerVisibility = "limited" OwnerVisibilityPrivate OwnerVisibility = "private" )
func (OwnerVisibility) Valid ¶
func (v OwnerVisibility) Valid() bool
Valid reports whether v is one of the named owner visibilities.
type PRBranch ¶
type PRBranch struct {
Ref string `json:"ref"` // branch name
SHA string `json:"sha"`
Repo string `json:"repo"` // "owner/name"; differs from the base repository for forks
}
PRBranch is one side of a pull request.
type PRContents ¶ added in v1.3.0
type PRContents interface {
// PullRequestDiff streams the pull request's changes; the caller must
// close it. GitHub refuses diffs that are too large (HTTP 406).
PullRequestDiff(ctx context.Context, owner, repo string, number int, format DiffFormat) (io.ReadCloser, error)
// PullRequestFiles lists the changed files. GitHub lists at most 3000.
PullRequestFiles(ctx context.Context, owner, repo string, number int, opts ListOptions) (Page[ChangedFile], error)
// PullRequestCommits lists the commits, newest first, without Files or
// Stats. GitHub lists at most 250: the oldest ones of a longer pull
// request, and it takes one more request per page to put them in order.
// Bitbucket returns them all at once, ignoring opts.
PullRequestCommits(ctx context.Context, owner, repo string, number int, opts ListOptions) (Page[Commit], error)
}
PRContents reads what a pull request changes. The Forgejo, GitHub and Bitbucket clients implement it (CapPRContents); find it with a type assertion:
c, ok := client.(gitoperationslib.PRContents)
type PRState ¶
type PRState string
PRState is the state of a pull request. PRStateAll is only meaningful as a List filter.
type Page ¶
type Page[T any] struct { Items []T `json:"items"` // NextPage is the page number to request next, or 0 if this is the last page. NextPage int `json:"nextPage"` }
Page is one page of results.
type PartError ¶ added in v0.3.0
type PartError struct {
Part string `json:"part"` // "organisations", "teams", "e-mail addresses"…
Status int `json:"status,omitzero"` // HTTP status of the refusal; 0 when the backend cannot read the part
Message string `json:"message"`
}
PartError is a part of an info call that could not be read.
type Profile ¶ added in v1.1.0
type Profile interface {
// Edit changes the profile and returns the updated user. A field the
// backend cannot change fails the whole call with ErrNotSupported,
// before any request is sent.
Edit(ctx context.Context, opts EditProfileOptions) (*User, error)
// SetAvatar uploads image (PNG, JPEG, GIF…; at most MaxAvatarSize
// bytes) as the avatar. The server checks the image: Forgejo answers
// HTTP 500 for an unknown format or an image wider or taller than 4096
// pixels. Forgejo only.
SetAvatar(ctx context.Context, image io.Reader) error
// DeleteAvatar restores the default avatar. Forgejo only.
DeleteAvatar(ctx context.Context) error
}
Profile edits the authenticated user's profile. Forgejo and GitHub implement it; Bitbucket has no API for it and returns ErrNotSupported.
type PullRequest ¶
type PullRequest struct {
Number int `json:"number"`
// Title is returned as the server stores it. On Forgejo a draft is a
// title starting with a work-in-progress prefix ("WIP:" or "[WIP]" by
// default), which therefore appears in Title.
Title string `json:"title"`
Body string `json:"body"`
State PRState `json:"state"`
Draft bool `json:"draft"`
Author string `json:"author"`
Head PRBranch `json:"head"`
Base PRBranch `json:"base"`
// Mergeable is nil while the server has not computed it yet (GitHub
// computes it in the background).
Mergeable *bool `json:"mergeable,omitzero"`
Merged bool `json:"merged"`
MergedBy string `json:"mergedBy,omitzero"`
MergedAt time.Time `json:"mergedAt,omitzero"`
MergeCommitSHA string `json:"mergeCommitSha,omitzero"`
HTMLURL string `json:"htmlUrl"`
CreatedAt time.Time `json:"createdAt,omitzero"`
UpdatedAt time.Time `json:"updatedAt,omitzero"`
ClosedAt time.Time `json:"closedAt,omitzero"`
}
PullRequest is a pull request.
type PullRequests ¶
type PullRequests interface {
List(ctx context.Context, owner, repo string, opts ListPROptions) (Page[PullRequest], error)
Get(ctx context.Context, owner, repo string, number int) (*PullRequest, error)
// Create opens a pull request. If the server does not honour Draft
// (Forgejo with custom work-in-progress prefixes), the pull request is
// returned together with an error matching ErrNotSupported.
Create(ctx context.Context, owner, repo string, opts CreatePROptions) (*PullRequest, error)
// Edit changes a pull request; see EditPROptions. A Draft change the
// server does not honour is reported as in Create.
Edit(ctx context.Context, owner, repo string, number int, opts EditPROptions) (*PullRequest, error)
// Merge merges a pull request. Drafts cannot be merged. With
// MergeOptions.WhenChecksSucceed the merge is scheduled instead.
Merge(ctx context.Context, owner, repo string, number int, opts MergeOptions) error
// CancelAutoMerge cancels a merge scheduled with WhenChecksSucceed.
CancelAutoMerge(ctx context.Context, owner, repo string, number int) error
IsMerged(ctx context.Context, owner, repo string, number int) (bool, error)
RequestReviewers(ctx context.Context, owner, repo string, number int, users, teams []string) error
RemoveReviewers(ctx context.Context, owner, repo string, number int, users, teams []string) error
ListReviews(ctx context.Context, owner, repo string, number int, opts ListOptions) (Page[Review], error)
CreateReview(ctx context.Context, owner, repo string, number int, opts CreateReviewOptions) (*Review, error)
}
PullRequests manages pull requests and their reviews.
type PushMirror ¶ added in v1.3.0
type PushMirror struct {
// Name identifies the mirror within its repository.
Name string `json:"name"`
// RemoteAddress never holds credentials. Forgejo rewrites an SSH address
// as ssh://host/path, without the user.
RemoteAddress string `json:"remoteAddress"`
// BranchFilter limits the branches pushed; empty means all of them.
BranchFilter string `json:"branchFilter,omitzero"`
// Interval is the time between pushes; zero means no periodic push.
Interval time.Duration `json:"interval,omitzero"`
SyncOnCommit bool `json:"syncOnCommit,omitzero"`
// PublicKey is set on a mirror using SSH: the remote must accept this key
// for writing, for instance as a deploy key.
PublicKey string `json:"publicKey,omitzero"`
// LastError is what went wrong with the last push.
LastError string `json:"lastError,omitzero"`
// LastSync is when the last push was tried, whether or not it worked: see
// LastError. It is zero until the first one.
LastSync time.Time `json:"lastSync,omitzero"`
CreatedAt time.Time `json:"createdAt,omitzero"`
}
PushMirror is a remote a repository is pushed to.
type Release ¶
type Release struct {
ID int64 `json:"id"`
TagName string `json:"tagName"`
TargetCommitish string `json:"targetCommitish"` // branch or commit the tag is created from
Name string `json:"name"` // title
Body string `json:"body"` // notes, Markdown
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
Author string `json:"author"` // login
HTMLURL string `json:"htmlUrl"`
TarballURL string `json:"tarballUrl"` // source archives generated by the forge
ZipballURL string `json:"zipballUrl"`
CreatedAt time.Time `json:"createdAt,omitzero"`
PublishedAt time.Time `json:"publishedAt,omitzero"` // zero for drafts
Assets []Asset `json:"assets"`
}
Release is a named, tagged point in a repository's history, with notes and attached files (assets).
type Releases ¶
type Releases interface {
List(ctx context.Context, owner, repo string, opts ListOptions) (Page[Release], error)
Get(ctx context.Context, owner, repo string, id int64) (*Release, error)
GetByTag(ctx context.Context, owner, repo, tag string) (*Release, error)
// Latest returns the most recent published release that is not a
// prerelease.
Latest(ctx context.Context, owner, repo string) (*Release, error)
Create(ctx context.Context, owner, repo string, opts CreateReleaseOptions) (*Release, error)
Edit(ctx context.Context, owner, repo string, id int64, opts EditReleaseOptions) (*Release, error)
// Delete removes a release. Its tag is kept.
Delete(ctx context.Context, owner, repo string, id int64) error
ListAssets(ctx context.Context, owner, repo string, releaseID int64, opts ListOptions) (Page[Asset], error)
GetAsset(ctx context.Context, owner, repo string, releaseID, assetID int64) (*Asset, error)
// UploadAsset streams size bytes from r as a new asset called name.
// size must be exact. An empty contentType is guessed from the name's
// extension, falling back to application/octet-stream.
UploadAsset(ctx context.Context, owner, repo string, releaseID int64, name string, r io.Reader, size int64, contentType string) (*Asset, error)
EditAsset(ctx context.Context, owner, repo string, releaseID, assetID int64, opts EditAssetOptions) (*Asset, error)
DeleteAsset(ctx context.Context, owner, repo string, releaseID, assetID int64) error
// DownloadAsset streams an uploaded asset's content; the caller must
// close it. External assets are not downloaded: fetch their DownloadURL.
DownloadAsset(ctx context.Context, owner, repo string, releaseID, assetID int64) (io.ReadCloser, error)
}
Releases manages releases and their assets.
Asset methods take the release ID as well as the asset ID: Forgejo needs both, GitHub ignores the release ID.
type Repo ¶
type Repo struct {
ID int64 `json:"id"`
Owner string `json:"owner"`
Name string `json:"name"`
FullName string `json:"fullName"` // "owner/name"
Description string `json:"description"`
Website string `json:"website"` // Forgejo "website", GitHub "homepage"
Visibility Visibility `json:"visibility"`
DefaultBranch string `json:"defaultBranch"`
Fork bool `json:"fork"`
Mirror bool `json:"mirror"`
Archived bool `json:"archived"`
Template bool `json:"template"`
Empty bool `json:"empty,omitzero"` // not reported by GitHub (always false there)
HTMLURL string `json:"htmlUrl"`
CloneURL string `json:"cloneUrl"`
SSHURL string `json:"sshUrl"`
CreatedAt time.Time `json:"createdAt,omitzero"`
UpdatedAt time.Time `json:"updatedAt,omitzero"`
}
Repo is a repository, modelled on the fields the forges share.
type Repos ¶
type Repos interface {
Get(ctx context.Context, owner, name string) (*Repo, error)
// List returns repositories owned by owner (a user or organisation).
// Empty owner lists every repository the authenticated user can access,
// including those of organisations they belong to.
List(ctx context.Context, owner string, opts ListOptions) (Page[Repo], error)
Create(ctx context.Context, opts CreateRepoOptions) (*Repo, error)
Edit(ctx context.Context, owner, name string, opts EditRepoOptions) (*Repo, error)
Delete(ctx context.Context, owner, name string) error
}
Repos manages repositories.
type RetryPolicy ¶ added in v1.1.0
type RetryPolicy struct {
// MaxAttempts is the total number of tries; 1 or less disables retries.
MaxAttempts int `json:"maxAttempts"`
// MaxWait is the longest single wait. When the server asks for a longer
// one (Retry-After, rate-limit reset), the error is returned at once,
// with APIError.RetryAt set.
MaxWait time.Duration `json:"maxWait"`
}
RetryPolicy controls how a backend retries failed requests. Every backend takes one through its WithRetry option; without it, DefaultRetryPolicy applies.
A request is retried when the server refused it without processing it (HTTP 429, a rate limit, GitHub's 409 "repository operation still in progress", Forgejo's 405 "Please try again later" on a merge). Requests that may have been processed are retried only if they are idempotent (GET, HEAD, PUT, DELETE): after HTTP 502, 503 or 504, or a connection reset mid-request. Refused connections and timeouts are not retried, so a server that is down still fails fast. Streamed uploads are never retried.
type Review ¶
type Review struct {
ID int64 `json:"id"`
Reviewer string `json:"reviewer"`
State ReviewState `json:"state"`
Body string `json:"body"`
CommitID string `json:"commitId"`
HTMLURL string `json:"htmlUrl"`
SubmittedAt time.Time `json:"submittedAt,omitzero"`
}
Review is a pull request review.
type ReviewComment ¶ added in v1.3.0
type ReviewComment struct {
ID int64 `json:"id"`
Author string `json:"author"`
Body string `json:"body"`
Path string `json:"path"`
// Line is the line in the new version of the file, OldLine in the old
// one. Only one is usually set. Bitbucket may report both.
Line int `json:"line,omitzero"`
OldLine int `json:"oldLine,omitzero"`
// CommitID is the commit commented on; Bitbucket does not report it.
CommitID string `json:"commitId,omitzero"`
// ReviewID is the review holding the comment; Bitbucket has none.
ReviewID int64 `json:"reviewId,omitzero"`
HTMLURL string `json:"htmlUrl"`
CreatedAt time.Time `json:"createdAt,omitzero"`
UpdatedAt time.Time `json:"updatedAt,omitzero"`
}
ReviewComment is a comment on a line of a pull request's diff.
type ReviewComments ¶ added in v1.3.0
type ReviewComments interface {
// ListReviewComments lists the line comments. Forgejo (one request per
// review with comments) and Bitbucket return them all at once, ignoring
// opts.
ListReviewComments(ctx context.Context, owner, repo string, number int, opts ListOptions) (Page[ReviewComment], error)
// CreateReviewComment comments on one line. On Forgejo it creates a
// review holding the comment, and the server checks neither the path nor
// the line. GitHub refuses a line outside the diff.
CreateReviewComment(ctx context.Context, owner, repo string, number int, opts CreateReviewCommentOptions) (*ReviewComment, error)
// DeleteReviewComment deletes a line comment. On Forgejo, the review
// that held it stays, empty.
DeleteReviewComment(ctx context.Context, owner, repo string, number int, id int64) error
}
ReviewComments manages the comments on a pull request's lines. The Forgejo, GitHub and Bitbucket clients implement it (CapReviewComments); find it with a type assertion:
rc, ok := client.(gitoperationslib.ReviewComments)
type ReviewEvent ¶
type ReviewEvent string
ReviewEvent is the verdict submitted with a review.
const ( ReviewEventApprove ReviewEvent = "approve" ReviewEventRequestChanges ReviewEvent = "request_changes" ReviewEventComment ReviewEvent = "comment" )
type ReviewState ¶
type ReviewState string
ReviewState is the outcome of a review.
const ( ReviewApproved ReviewState = "approved" ReviewChangesRequested ReviewState = "changes_requested" ReviewCommented ReviewState = "commented" ReviewPending ReviewState = "pending" // started, not submitted ReviewDismissed ReviewState = "dismissed" // GitHub ReviewRequested ReviewState = "requested" // Forgejo: review requested, not given )
type SSHKey ¶ added in v0.2.1
type SSHKey struct {
ID int64 `json:"id,omitzero"` // 0 on Bitbucket
Title string `json:"title"`
Key string `json:"key"`
Fingerprint string `json:"fingerprint,omitzero"` // not reported by GitHub
ReadOnly bool `json:"readOnly,omitzero"` // GitHub only
CreatedAt time.Time `json:"createdAt,omitzero"`
LastUsed time.Time `json:"lastUsed,omitzero"` // GitHub and Bitbucket only; zero if never used
}
SSHKey is a public SSH key of the authenticated user.
type SSHKeys ¶ added in v1.1.0
type SSHKeys interface {
List(ctx context.Context, opts ListOptions) (Page[SSHKey], error)
Get(ctx context.Context, id int64) (*SSHKey, error)
Add(ctx context.Context, opts AddSSHKeyOptions) (*SSHKey, error)
Delete(ctx context.Context, id int64) error
}
SSHKeys manages the authenticated user's public SSH keys (authentication keys; GitHub's signing keys are not included).
Bitbucket identifies keys by UUID: SSHKey.ID is derived from it, and Get and Delete list the keys to find it.
type Secret ¶ added in v1.1.0
type Secret struct {
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt,omitzero"` // Forgejo and GitHub
UpdatedAt time.Time `json:"updatedAt,omitzero"` // GitHub only
}
Secret is a CI secret; its value is never returned.
type SecretAccess ¶ added in v1.3.0
type SecretAccess struct {
Visibility SecretVisibility `json:"visibility"`
// Repos names the repositories, without their owner. It only applies to
// SecretVisibleSelected; empty means none.
Repos []string `json:"repos,omitzero"`
}
SecretAccess is which of an organisation's repositories can use a secret.
type SecretVisibility ¶ added in v1.3.0
type SecretVisibility string
SecretVisibility is which of an organisation's repositories can use a secret.
const ( SecretVisibleAll SecretVisibility = "all" // all of them SecretVisiblePrivate SecretVisibility = "private" // the private and internal ones SecretVisibleSelected SecretVisibility = "selected" // those listed in SecretAccess.Repos )
type Secrets ¶ added in v1.1.0
type Secrets interface {
// List returns the secrets' names. Forgejo cannot list the user's
// secrets (ErrNotSupported).
List(ctx context.Context, scope CIScope, opts ListOptions) (Page[Secret], error)
// Set creates the secret or replaces its value. On GitHub the value is
// encrypted for the scope's public key before it is sent. A new
// organisation secret is available to all the organisation's repositories,
// and an existing one keeps its access, at the cost of one or two more
// requests: see OrgSecrets to limit it.
Set(ctx context.Context, scope CIScope, name, value string) error
Delete(ctx context.Context, scope CIScope, name string) error
}
Secrets manages CI secrets. Their values are write-only: once stored they can be replaced or deleted, never read back.
Forgejo and GitHub upper-case names; Bitbucket keeps them as given. Names are letters, digits and underscores, not starting with a digit (nor, on Forgejo, with GITEA_, GITHUB_ or FORGEJO_). Empty values are refused. Forgejo turns line endings into LF: base64-encode values whose exact bytes matter.
type SiteHooks ¶ added in v1.3.0
type SiteHooks interface {
SystemWebhooks() SystemWebhooks
DefaultWebhooks() DefaultWebhooks
}
SiteHooks gives access to a Forgejo instance's system and default webhooks, which need a site-admin token (HTTP 403 otherwise). Only the Forgejo backend implements it (CapSystemWebhooks); find it with a type assertion:
h, ok := client.(gitoperationslib.SiteHooks)
Forgejo's API addresses both kinds by ID at the same path, and nothing in its answers tells them apart. Both interfaces therefore check the kind by listing the system webhooks first, and answer an ID of the other kind with a 404 *APIError, changing nothing.
type SystemWebhooks ¶ added in v1.3.0
type SystemWebhooks interface {
List(ctx context.Context, opts ListOptions) (Page[Webhook], error)
Get(ctx context.Context, id int64) (*Webhook, error)
// Edit changes a webhook; dropped events are reported as in
// Webhooks.Create.
Edit(ctx context.Context, id int64, opts EditWebhookOptions) (*Webhook, error)
Delete(ctx context.Context, id int64) error
}
SystemWebhooks manages system webhooks, which fire for events in every repository of the instance. The library has no Create, as Forgejo only offers one through an undocumented flag: create them in the web interface (Site administration, Webhooks).
type Tag ¶
type Tag struct {
Name string `json:"name"`
SHA string `json:"sha"` // commit the tag points to (annotated tags are peeled)
// Message is the annotation of an annotated tag; empty for lightweight
// tags. GitHub reports it from Get only, not from List.
Message string `json:"message,omitzero"`
TarballURL string `json:"tarballUrl"`
ZipballURL string `json:"zipballUrl"`
}
Tag is a repository tag.
type TagProtection ¶
type TagProtection struct {
ID int64 `json:"id"`
Pattern string `json:"pattern"`
Allowlist Allowlist `json:"allowlist"`
}
TagProtection restricts creating, updating and deleting the tags matching Pattern ("v*") to the users and teams in Allowlist. On GitHub it is a tag ruleset, and an empty Allowlist blocks everyone, administrators included. Forgejo requires at least one allowed user or team.
type TagProtections ¶
type TagProtections interface {
List(ctx context.Context, owner, repo string) ([]TagProtection, error)
Get(ctx context.Context, owner, repo, pattern string) (*TagProtection, error)
Create(ctx context.Context, owner, repo string, rule TagProtection) (*TagProtection, error)
Update(ctx context.Context, owner, repo, pattern string, rule TagProtection) (*TagProtection, error)
Delete(ctx context.Context, owner, repo, pattern string) error
}
TagProtections manages tag protection rules, addressed by pattern.
type Tags ¶
type Tags interface {
List(ctx context.Context, owner, repo string, opts ListOptions) (Page[Tag], error)
Get(ctx context.Context, owner, repo, name string) (*Tag, error)
Create(ctx context.Context, owner, repo string, opts CreateTagOptions) (*Tag, error)
Delete(ctx context.Context, owner, repo, name string) error
}
Tags manages repository tags. Releases are managed with Releases().
type Team ¶
type Team struct {
ID int64 `json:"id"`
Org string `json:"org"`
Name string `json:"name"`
// Slug is the URL-safe name GitHub addresses teams by; on Forgejo it is
// the name.
Slug string `json:"slug"`
Description string `json:"description"`
// Permission is the overall level: admin or owner when the team has
// that level on every unit, otherwise derived by the server from Units.
Permission TeamPermission `json:"permission"`
Units map[TeamUnit]TeamPermission `json:"units,omitzero"`
// IncludesAllRepos gives the team access to every repository of the
// organisation, current and future.
IncludesAllRepos bool `json:"includesAllRepos,omitzero"`
CanCreateOrgRepo bool `json:"canCreateOrgRepo,omitzero"`
}
Team is a team within an organisation.
type TeamAccess ¶
type TeamAccess struct {
Permission TeamPermission `json:"permission,omitzero"`
Units map[TeamUnit]TeamPermission `json:"units,omitzero"`
}
TeamAccess sets a team's permissions. Exactly one form applies:
- Permission admin: admin on every unit; Units must be empty.
- Units set: per-unit permissions (none, read or write); Permission must be empty.
- Permission read or write with no Units: that level on every unit.
type TeamInfo ¶ added in v0.2.0
type TeamInfo struct {
Team
Members []User `json:"members"`
Repos []Repo `json:"repos"`
// Incomplete is nil when every part was read; see UserInfo.Incomplete.
Incomplete error `json:"-"`
Missing []PartError `json:"missing,omitzero"` // see UserInfo.Missing
}
TeamInfo is a team with its members and repositories.
type TeamPermission ¶
type TeamPermission string
TeamPermission is a team's access level, overall or for one unit.
const ( TeamPermissionNone TeamPermission = "none" TeamPermissionRead TeamPermission = "read" TeamPermissionWrite TeamPermission = "write" TeamPermissionAdmin TeamPermission = "admin" // TeamPermissionOwner is reported for an organisation's owner team; it // cannot be assigned. TeamPermissionOwner TeamPermission = "owner" )
type TeamUnit ¶
type TeamUnit string
TeamUnit is a repository feature a team can be granted access to.
const ( TeamUnitCode TeamUnit = "repo.code" TeamUnitIssues TeamUnit = "repo.issues" TeamUnitExternalIssues TeamUnit = "repo.ext_issues" TeamUnitWiki TeamUnit = "repo.wiki" TeamUnitExternalWiki TeamUnit = "repo.ext_wiki" TeamUnitPulls TeamUnit = "repo.pulls" TeamUnitReleases TeamUnit = "repo.releases" TeamUnitProjects TeamUnit = "repo.projects" TeamUnitPackages TeamUnit = "repo.packages" TeamUnitActions TeamUnit = "repo.actions" )
type Teams ¶
type Teams interface {
List(ctx context.Context, org string, opts ListOptions) (Page[Team], error)
Get(ctx context.Context, id int64) (*Team, error)
// GetByName returns the team of org with exactly that name
// (case-insensitive), or a 404 *APIError.
GetByName(ctx context.Context, org, name string) (*Team, error)
Create(ctx context.Context, org string, opts CreateTeamOptions) (*Team, error)
// Edit changes a team. Renaming the owner team or changing its access
// returns ErrOwnerTeam.
Edit(ctx context.Context, id int64, opts EditTeamOptions) (*Team, error)
// Delete removes a team. Deleting the owner team returns ErrOwnerTeam.
Delete(ctx context.Context, id int64) error
Members(ctx context.Context, id int64, opts ListOptions) (Page[User], error)
IsMember(ctx context.Context, id int64, user string) (bool, error)
// AddMember adds user to the team, which also makes them a member of
// the organisation.
AddMember(ctx context.Context, id int64, user string) error
RemoveMember(ctx context.Context, id int64, user string) error
Repos(ctx context.Context, id int64, opts ListOptions) (Page[Repo], error)
AddRepo(ctx context.Context, id int64, owner, repo string) error
RemoveRepo(ctx context.Context, id int64, owner, repo string) error
}
Teams manages an organisation's teams, their members and repositories. Teams are addressed by ID; use GetByName to look one up.
type Tokens ¶ added in v1.1.0
type Tokens interface {
List(ctx context.Context, opts ListOptions) (Page[AccessToken], error)
// Create mints a token. Its secret is only ever returned here, in
// AccessToken.Secret.
Create(ctx context.Context, opts CreateTokenOptions) (*AccessToken, error)
Delete(ctx context.Context, id int64) error
// DeleteByName finds the token called name and deletes it (a 404
// *APIError when there is none).
DeleteByName(ctx context.Context, name string) error
}
Tokens manages the authenticated user's personal access tokens. Only Forgejo implements it (CapTokens): GitHub and Bitbucket cannot create or revoke personal tokens through their API, and return ErrNotSupported.
Forgejo lists tokens with any credentials, but creates and deletes them only with username and password (forgejo.BasicAuth, or BasicAuthOTP with two-factor authentication). With a token, Create and Delete fail with an error matching ErrPasswordRequired.
type UnsupportedVersionError ¶
type UnsupportedVersionError struct {
Backend Backend `json:"backend"`
Version string `json:"version"`
Minimum string `json:"minimum"`
}
UnsupportedVersionError is returned when a server is older than the minimum version the library supports.
func (*UnsupportedVersionError) Error ¶
func (e *UnsupportedVersionError) Error() string
type User ¶
type User struct {
ID int64 `json:"id"`
Login string `json:"login"`
FullName string `json:"fullName"`
Email string `json:"email"`
Description string `json:"description"`
Website string `json:"website"`
Location string `json:"location"`
Visibility OwnerVisibility `json:"visibility"`
IsAdmin bool `json:"isAdmin"`
Active bool `json:"active"`
Restricted bool `json:"restricted,omitzero"`
ProhibitLogin bool `json:"prohibitLogin,omitzero"`
HTMLURL string `json:"htmlUrl"`
AvatarURL string `json:"avatarUrl"`
Company string `json:"company,omitzero"` // GitHub only
Pronouns string `json:"pronouns,omitzero"` // Forgejo only
Language string `json:"language,omitzero"` // interface language; Forgejo only
Followers int `json:"followers"`
Following int `json:"following"`
StarredRepos int `json:"starredRepos,omitzero"` // Forgejo only
CreatedAt time.Time `json:"createdAt,omitzero"`
LastLogin time.Time `json:"lastLogin,omitzero"` // zero if the user never signed in
}
User is a user account.
type UserHooks ¶ added in v1.3.0
type UserHooks interface {
UserWebhooks() UserWebhooks
}
UserHooks gives access to the authenticated user's own webhooks. Only the Forgejo backend implements it (CapUserWebhooks); find it with a type assertion:
h, ok := client.(gitoperationslib.UserHooks)
type UserInfo ¶ added in v0.2.0
type UserInfo struct {
User
Orgs []Org `json:"orgs"` // organisations the user belongs to
Repos []Repo `json:"repos"` // repositories the user owns
// Incomplete is nil when every part was read. Otherwise it describes the
// parts the server refused (401, 403, 404) or the backend cannot list
// (ErrNotSupported); those fields are left empty. It is not serialised:
// Missing carries the same information as data.
Incomplete error `json:"-"`
// Missing lists the parts recorded in Incomplete, one entry each.
Missing []PartError `json:"missing,omitzero"`
}
UserInfo is a user with the organisations and repositories the caller can see.
type UserSettings ¶ added in v0.2.1
type UserSettings struct {
Theme string `json:"theme"`
DiffViewStyle string `json:"diffViewStyle"` // "unified" or "split"
HideEmail bool `json:"hideEmail"`
HideActivity bool `json:"hideActivity"`
HidePronouns bool `json:"hidePronouns"`
EnableRepoUnitHints bool `json:"enableRepoUnitHints"`
}
UserSettings are a Forgejo user's account preferences.
type UserWebhooks ¶ added in v1.3.0
type UserWebhooks interface {
List(ctx context.Context, opts ListOptions) (Page[Webhook], error)
Get(ctx context.Context, id int64) (*Webhook, error)
// Create adds a webhook. Forgejo silently drops event names it does not
// know; Create then returns the webhook together with an error.
Create(ctx context.Context, opts CreateWebhookOptions) (*Webhook, error)
// Edit changes a webhook; dropped events are reported as in Create.
Edit(ctx context.Context, id int64, opts EditWebhookOptions) (*Webhook, error)
Delete(ctx context.Context, id int64) error
}
UserWebhooks manages the webhooks of the authenticated user, which fire for events in that user's repositories. They are always the caller's own: a site admin gets a 404 for another user's hook.
type Users ¶
type Users interface {
Get(ctx context.Context, login string) (*User, error)
List(ctx context.Context, opts ListOptions) (Page[User], error)
Create(ctx context.Context, opts CreateUserOptions) (*User, error)
// Edit applies opts. If the server ignores a visibility change (Forgejo
// 15.0.x cannot switch a user back to public), Edit returns the updated
// user together with an error matching ErrNotSupported.
Edit(ctx context.Context, login string, opts EditUserOptions) (*User, error)
// Rename changes a user's login. The old login keeps redirecting to the
// new one, so Get(oldLogin) returns the renamed user.
Rename(ctx context.Context, login, newLogin string) error
Delete(ctx context.Context, login string, opts DeleteUserOptions) error
}
Users manages user accounts. All methods except Get require a site-admin token.
type Variable ¶ added in v1.1.0
type Variable struct {
Name string `json:"name"`
Value string `json:"value"`
CreatedAt time.Time `json:"createdAt,omitzero"` // GitHub only
UpdatedAt time.Time `json:"updatedAt,omitzero"` // GitHub only
}
Variable is a CI variable.
type Variables ¶ added in v1.1.0
type Variables interface {
List(ctx context.Context, scope CIScope, opts ListOptions) (Page[Variable], error)
Get(ctx context.Context, scope CIScope, name string) (*Variable, error)
// Set creates the variable or changes its value.
Set(ctx context.Context, scope CIScope, name, value string) error
Delete(ctx context.Context, scope CIScope, name string) error
}
Variables manages CI variables: like secrets, but readable.
type Visibility ¶
type Visibility string
Visibility is the visibility of a repository. The zero value means "use the backend default" in option structs.
const ( VisibilityPublic Visibility = "public" VisibilityPrivate Visibility = "private" // VisibilityInternal is visible to all members of a GitHub enterprise. // Forgejo and Bitbucket repositories only have a private flag, so those // backends return ErrNotSupported for it. VisibilityInternal Visibility = "internal" )
func (Visibility) Valid ¶
func (v Visibility) Valid() bool
Valid reports whether v is one of the named visibilities.
type Webhook ¶
type Webhook struct {
ID int64 `json:"id"`
URL string `json:"url"`
ContentType HookContentType `json:"contentType"`
// Events lists the subscribed events. Forgejo may add finer-grained
// events implied by the requested ones (e.g. issue_assign with issues);
// those keep Forgejo's names.
Events []HookEvent `json:"events"`
Active bool `json:"active"`
BranchFilter string `json:"branchFilter,omitzero"` // Forgejo only
// InsecureSSL delivers without checking the target's TLS certificate
// (GitHub, Bitbucket).
InsecureSSL bool `json:"insecureSsl,omitzero"`
CreatedAt time.Time `json:"createdAt,omitzero"`
UpdatedAt time.Time `json:"updatedAt,omitzero"`
}
Webhook is a configured webhook. The secret is never returned.
type Webhooks ¶
type Webhooks interface {
List(ctx context.Context, scope HookScope, opts ListOptions) (Page[Webhook], error)
Get(ctx context.Context, scope HookScope, id int64) (*Webhook, error)
// Create adds a webhook. Forgejo silently drops event names it does not
// know; Create then returns the webhook together with an error.
Create(ctx context.Context, scope HookScope, opts CreateWebhookOptions) (*Webhook, error)
// Edit changes a webhook; dropped events are reported as in Create.
Edit(ctx context.Context, scope HookScope, id int64, opts EditWebhookOptions) (*Webhook, error)
Delete(ctx context.Context, scope HookScope, id int64) error
// Ping asks the server to send a test delivery: a "ping" event on
// GitHub, a "push" of the latest commit on Forgejo (repositories only).
Ping(ctx context.Context, scope HookScope, id int64) error
}
Webhooks manages repository and organisation webhooks. Receiving and verifying deliveries is done by the webhook sub-package.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package bitbucket is the Bitbucket Cloud backend (REST API 2.0).
|
Package bitbucket is the Bitbucket Cloud backend (REST API 2.0). |
|
Package forgejo is the Forgejo backend.
|
Package forgejo is the Forgejo backend. |
|
Package github is the GitHub backend, built on google/go-github.
|
Package github is the GitHub backend, built on google/go-github. |
|
internal
|
|
|
bitbucketapi
Package bitbucketapi is the HTTP transport for the Bitbucket Cloud backend (REST API 2.0).
|
Package bitbucketapi is the HTTP transport for the Bitbucket Cloud backend (REST API 2.0). |
|
contracttest
Package contracttest holds behaviour checks shared by every backend's integration tests, so all backends are held to the same contract.
|
Package contracttest holds behaviour checks shared by every backend's integration tests, so all backends are held to the same contract. |
|
forgejoapi
Package forgejoapi is the HTTP transport for the Forgejo backend.
|
Package forgejoapi is the HTTP transport for the Forgejo backend. |
|
partial
Package partial helps backends build Directory info results from several reads, keeping the parts the caller may not see out of the result instead of failing the whole call.
|
Package partial helps backends build Directory info results from several reads, keeping the parts the caller may not see out of the result instead of failing the whole call. |
|
refusal
Package refusal recognises refusals in error responses and tags them with a sentinel error (APIError.Err), so callers can match them with errors.Is.
|
Package refusal recognises refusals in error responses and tags them with a sentinel error (APIError.Err), so callers can match them with errors.Is. |
|
retry
Package retry is the http.RoundTripper every backend wraps around its HTTP client to retry transient failures (see gitoperationslib.RetryPolicy).
|
Package retry is the http.RoundTripper every backend wraps around its HTTP client to retry transient failures (see gitoperationslib.RetryPolicy). |
|
Package webhook receives webhook deliveries from Forgejo, GitHub and Bitbucket Cloud: it verifies their signature, identifies the forge and event, and decodes the common payloads.
|
Package webhook receives webhook deliveries from Forgejo, GitHub and Bitbucket Cloud: it verifies their signature, identifies the forge and event, and decodes the common payloads. |