provider

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 17 Imported by: 4

Documentation

Overview

Package provider is the contract seam of go-git-platform: one Go interface for GitHub, GitLab, Gitea, Forgejo, Gitee, GitCode, and Tencent Code (工蜂) — the layer every platform backend implements and every consumer programs against.

This package holds the contract surface: the Provider interface and its eight core sub-interface families, the optional capability interfaces (iface_*.go), all XxxOptions parameter structs, sentinel errors and ProviderError, patch three-state resolution, CapabilitySet, the Divergence ledger types and predicates, the factory/registry (NewProvider/Register), Logger/Hooks/TokenSource, shared pure helpers (state mapping, pagination, file decoding, diff stats), and Version().

Entity types (repositories, change requests, issues, reviews, events, commit statuses, deployments, …) live in package model; the machines that drive these contracts (platform detection, Ensure* convergence, CI gating, batch reads, page-walking iterators, webhook validation, the token cache Manager) live in package runtime. This package imports only model — never runtime, adapter or anything below it (spec §4.1 edge table).

Overview

Start with NewProvider and the blank import that registers every shipped backend:

import (
    _ "github.com/yi-nology/go-git-platform/adapter/all"

    "github.com/yi-nology/go-git-platform/model"
    "github.com/yi-nology/go-git-platform/provider"
)

p, err := provider.NewProvider(provider.Config{
    Platform: model.PlatformGitHub,
    Token:    "ghp_...",
})

The returned Provider composes eight core sub-interface families — repositories, change requests (PRs/MRs), webhooks, branches, diffs, commits, files, and releases — so consumer code can depend on the narrow slice it needs. A further 23 capability families are optional: backends declare them via Capabilities() and consumers reach them with a type assertion (the README capability matrix lists all of them per platform).

Configuration surface

Config carries everything a backend needs: platform, base URL (for self-hosted instances), credentials, retry, hooks, and logging. Two newer knobs are worth knowing:

  • Config.TokenSource replaces the static Token with a per-request source, so expiring credentials (GitHub App installation tokens, OAuth flows) rotate without rebuilding the provider.
  • Config.ConditionalRequests enables ETag-based conditional GETs: the transport replays cached 304 answers, which on GitHub do not count against the rate-limit budget — a large win for polling workloads like runtime.WaitForCommitStatus.

Cross-platform consistency

Behavior parity is enforced, not aspirational: contracttest runs the same suite against every platform, and every deliberate departure from unified semantics is registered in the backend's Divergence ledger (rendered to docs/divergence-ledger.md). The webhook event corpus (testdata/webhooks under each adapter) pins the normalized event vocabulary — cr./push/tag./branch./issue./comment. — across platforms with golden files.

Automation helpers

The agent- and CI-facing machines live one layer up in package runtime: DetectPlatform, WaitForCommitStatus (CI gating), GetFileContents (bounded-concurrency batch reads), Each/Collect (page-walking iterators), EnsureWebhook/EnsureBranchProtection/EnsureDeployKey (idempotent desired-state convergence), webhook signature validation, and the Manager token cache. RateLimitRecovery stays here: it reads the server-advised backoff window off this package's rate-limit errors.

Index

Constants

View Source
const (
	DefaultPage    = 1
	DefaultPerPage = 20
	MaxPerPage     = 100
)

Variables

View Source
var (
	ErrNotFound             = errors.New("resource not found")
	ErrAuthentication       = errors.New("authentication failed")
	ErrRateLimited          = errors.New("rate limited")
	ErrForbidden            = errors.New("forbidden")
	ErrConflict             = errors.New("conflict")
	ErrNotImplemented       = errors.New("not implemented")
	ErrInvalidInput         = errors.New("invalid input")
	ErrGone                 = errors.New("resource permanently gone")
	ErrServerSide           = errors.New("server-side failure")
	ErrWebhookValidation    = errors.New("webhook validation failed")
	ErrConnectionFailed     = errors.New("connection failed")
	ErrPlatformNotSupported = errors.New("platform not supported")
	// ErrClearNotSupported 是三态 Update 的 B 级哨兵(2A 能力矩阵):
	// 调用方经 XxxPatch 显式要求清空,但该平台+字段的 wire 无法表达
	// 清空(结构不可表达且无侧端点,或既有登记 no-op)。只由 patch
	// 字段触发;旧字段路径永不返回。kv 携带 platform/op/field。
	ErrClearNotSupported = errors.New("clear not supported on this platform")
	// ErrDraftNotSupported 是创建面值级平台限制哨兵(#160):平台读得到
	// draft(ChangeRequest.Draft 统一映射),但创建 SDK/API 面无法表达
	// Draft=true——CreateCR(Draft=true) 显式返回本哨兵,绝不静默产出
	// 非 draft CR。分界:ErrNotImplemented=方法级不支持(台账 stub);
	// ErrClearNotSupported=清空不可表达(2A);本哨兵=创建 Draft=true
	// 不可表达。Draft=false(缺省)不受影响,七后端现行为逐字保留。
	ErrDraftNotSupported = errors.New("draft=true not supported on this platform")
	// ErrPermissionDenied 是凭据权限类哨兵(2B):操作级声明判定
	// 「平台支持但当前 token 无权」时由 CheckOperation 返回。
	// 分界:ErrNotImplemented=平台不支持(台账锁定);ErrForbidden=
	// 服务端 403(资源策略/权限 wire 不可分,不做猜测);本哨兵=
	// 本库声明面的凭据轴。
	ErrPermissionDenied = errors.New("permission denied for this credential")
	// ErrEmptyResponse 是「请求成功(2xx)但响应体为空」的协议异常哨兵
	// (issue #164):流式下载面(ReleaseAssetManager.DownloadReleaseAsset)
	// 在状态码成功、但实际写入 0 字节时返回。调用方因此能把「下载成功且
	// 有内容」与「服务端回了成功状态但没有任何字节」区分开——后者绝不
	// 以零字节静默成功。与 transport.ErrEmptyResponse(DoJSON 的 2xx 空体)
	// 同义;provider 包不依赖 transport,故在本包保留同义哨兵供契约层判定。
	ErrEmptyResponse = errors.New("empty response body")
)

Sentinel errors classify transport and provider failures so callers can branch on category without inspecting status codes or wrapped causes.

View Source
var ErrWebhookFiltered = errors.New("webhook event filtered out (noise policy)")

ErrWebhookFiltered 是 ParseWebhookEvent 的「噪声过滤」哨兵(issue #45): 后端按平台噪声策略丢弃事件(如 GitLab pipeline 的 success/running 态) 时返回 (nil, ErrWebhookFiltered),而不是 (nil, nil)——后者是契约陷阱, 只判 err 的调用方会在 ev 上空指针。调用方以 errors.Is(err, ErrWebhookFiltered) 识别并显式忽略;哨兵经 provider.Wrap 包装后链路 保持可判。

Functions

func BuildRawDiff

func BuildRawDiff(files []*model.ChangedFile) string

BuildRawDiff constructs a raw diff string from a list of ChangedFiles.

func CheckOperation added in v0.137.0

func CheckOperation(p Provider, op Operation) error

CheckOperation 返回 nil(可执行)/ ErrNotImplemented(平台不支持)/ ErrPermissionDenied(凭据无权限)。未知 op 按 Unsupported 处理。

func ClassifyStatus

func ClassifyStatus(statusCode int) error

ClassifyStatus maps an HTTP status code to a sentinel error. Exposed so transports and platform implementations can produce consistent error categories without importing each other.

The full mapping (issue #64): 400 and 422 → ErrInvalidInput, 401 → ErrAuthentication, 403 → ErrForbidden, 404 → ErrNotFound, 409 → ErrConflict, 410 → ErrGone, 429 → ErrRateLimited, 5xx → ErrServerSide; every other status yields a plain formatted error (classify by IsStatus). Statuses without a dedicated sentinel above stay text-only by design — match them with ProviderError.IsStatus, not errors.Is.

func CountDiffLines

func CountDiffLines(diff string) (additions, deletions int)

CountDiffLines counts additions and deletions in a unified diff string.

func DecodeFileContent added in v0.99.7

func DecodeFileContent(platform model.Platform, encoding, content string) (string, error)

DecodeFileContent 按平台返回的 Encoding 解码文件内容。

平台的「取文件内容」端点有两种形态:raw(直接给字节)与 JSON(base64 字段)。 **不按 Encoding 解码 ⇒ 调用方拿到 base64 串** —— 按 GitHub 直觉读文件会全错 (解析 YAML/JSON 直接失败),而调用方无从察觉。

只认 `base64`(大小写不敏感);其它 encoding 原样返回。

func Ignores

func Ignores(divs []Divergence, method, field string) bool

Ignores reports whether the ledger registers an ignore of field on method. 保留手写循环:slicex 无早退谓词原语(Any/FindFunc),Filter 会为一次布尔判定白分配全量结果。

func IsAuthentication

func IsAuthentication(err error) bool

IsAuthentication reports whether err wraps ErrAuthentication (HTTP 401).

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err wraps ErrConflict (HTTP 409).

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether err wraps ErrForbidden (HTTP 403).

func IsGone added in v0.125.0

func IsGone(err error) bool

IsGone reports whether err wraps ErrGone (HTTP 410): the resource existed and is now permanently gone — distinct from IsNotFound ("never existed").

func IsInvalidInput

func IsInvalidInput(err error) bool

IsInvalidInput reports whether err wraps ErrInvalidInput.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err wraps ErrNotFound (HTTP 404).

func IsNotImplemented

func IsNotImplemented(err error) bool

IsNotImplemented reports whether err wraps ErrNotImplemented.

func IsPlatformNotSupported

func IsPlatformNotSupported(err error) bool

IsPlatformNotSupported reports whether err wraps ErrPlatformNotSupported.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether err wraps ErrRateLimited (HTTP 429).

func IsRegistered

func IsRegistered(p model.Platform) bool

IsRegistered checks if a platform has been registered.

func IsServerSide added in v0.125.0

func IsServerSide(err error) bool

IsServerSide reports whether err wraps ErrServerSide (any HTTP 5xx). True here means "retrying after backoff is meaningful"; a false result with IsClientError true means the request itself must change.

func IsStub added in v0.137.0

func IsStub(divs []Divergence, capability, method string) bool

IsStub 报告台账是否登记了 capability 方法的 stub(2B)——与 Stubs 的 差别:同时匹配 Capability,防未来跨能力方法名撞车(Stubs 只按 Method)。

字段级 stub(Field != "")在此按方法级计入——派生面刻意保守(宁可 Unsupported 也不误报 Supported),不区分 Field;DivergenceSuite 对 Field != "" 的条目豁免行为检查(字段级条目是文档性质、调用本身可用), 因此未来某个种子 op 若命中一条字段级 stub,OperationSuite 是响亮绊线 (CheckOperation 拒但直调成功 → 行为钉红)。

func IsWebhookValidation

func IsWebhookValidation(err error) bool

IsWebhookValidation reports whether err wraps ErrWebhookValidation.

func MapBoolStateToCR

func MapBoolStateToCR(state string, merged bool) model.CRState

MapBoolStateToCR is a convenience for platforms with a separate merged boolean (Gitea, Forgejo).

func MapMRStateToCR

func MapMRStateToCR(state string) model.CRState

MapMRStateToCR is a convenience for platforms with explicit "merged" state (GitLab, Tencent Code).

func MapStateToCR

func MapStateToCR(state string, mergedFn func() bool) model.CRState

MapStateToCR maps common string state representations to CRState. mergedFn is called when state is "closed" to determine if it was merged. For platforms that use a separate "merged" field (Gitea, Forgejo), pass a non-nil mergedFn. For platforms where "merged" is a distinct state string (GitLab, Tencent Code), pass nil.

func New

func New(platform model.Platform, op string, status int, body string) error

New builds a ProviderError directly from the given status code.

func NormalizePageOpts

func NormalizePageOpts(page, perPage int) (int, int)

NormalizePageOpts applies default values for page/perPage: Page falls back to DefaultPage when below 1, and PerPage to DefaultPerPage when out of the (0, MaxPerPage] range.

NormalizePageOpts is also the documentation anchor for the SDK-wide Page semantics (issue #60) — the contract every list option type's Page field follows. Two families exist, chosen per manager by the boundedness of the result set; each option type's doc states which one it belongs to:

  • Exhaustive family (bounded sets — labels, milestones, notifications). Page == 0 (the zero value, the default) walks EVERY page of the result set and returns all items; Page > 0 returns exactly that single caller-driven page at the normalized sizes. Walks are budget-capped and fail loud (error wrapping ErrPageBudgetExceeded) when a platform's pagination never advances, so a silent partial list is impossible.

  • Caller-paged family (unbounded sets — change requests and the issue family's ListIssues, unified by issue #51). Page == 0 returns the platform's FIRST page at the normalized page size — one request, no walk, because a default call's request volume must not scale silently with the repository's size. Page > 0 returns exactly that page; callers page through explicitly until a short page comes back. On ListIssues the int return is uniformly len(result) (the served rows' count), never a platform total.

Per-backend departures from either family are machine-readable in each backend's divergence ledger (Provider.Divergences, regenerated into docs/divergence-ledger.md) — never prose-only.

func ParseTotalCountHeader

func ParseTotalCountHeader(headers http.Header, fallback int) int

ParseTotalCountHeader reads X-Total-Count or X-Total from response headers. Falls back to the provided default if neither header is present or valid.

func RateLimitRecovery added in v0.72.0

func RateLimitRecovery(err error) (retryAfter time.Duration, resetAt time.Time, ok bool)

RateLimitRecovery extracts the server-advised recovery window from a rate-limited error, walking the wrapped chain for the transport hints (Retry-After / X-RateLimit-Reset). ok is true only when at least one of retryAfter or resetAt is known — callers rate-limited without hints should fall back to their own backoff. The walk covers both `Unwrap() error` chains and `Unwrap() []error` branches(多 %w / errors.Join, issue #146)——判定口径与 errors.Is 一致,同一份错误上 IsRateLimited 为真 时本函数不会再因链形态不同而丢恢复窗口。

if ra, reset, ok := provider.RateLimitRecovery(err); ok {
    wait := ra
    if reset.After(time.Now()) && (wait == 0 || time.Until(reset) > wait) {
        wait = time.Until(reset)
    }
    time.Sleep(wait)
}

func Register

func Register(p model.Platform, ctor ProviderConstructor)

Register registers a provider constructor for a platform. This is typically called from init() functions in platform implementation files. Panics on duplicate registration (fail-fast convention shared by every registry in this package).

func RegisterStatusExtractor added in v0.83.0

func RegisterStatusExtractor(p model.Platform, fn StatusExtractor)

RegisterStatusExtractor teaches Wrap how to read the HTTP status out of the named platform's SDK error values — the explicit, type-safe replacement for the old reflection + error-message-parsing fallback. Backends register one extractor at init covering their SDK's error types via errors.As; a nil extractor (or no registration) means the platform's errors carry no status on the error value itself (use WrapStatusError / New at the call site, or thread the *Response status through the port as the family backends do). Panics on duplicate registration (same convention as Register).

func RegisterThrottleClassifier added in v0.125.0

func RegisterThrottleClassifier(p model.Platform, fn ThrottleClassifier)

RegisterThrottleClassifier teaches Wrap which of the named platform's SDK error values are throttle verdicts. Consulted per link of the chain Wrap walks, before the bare-status classification, wherever a status extractor produced a code. Backends register at init next to RegisterStatusExtractor; a platform without a classifier keeps the status-only behavior. Panics on duplicate registration (same convention as RegisterStatusExtractor).

func RegisteredPlatforms

func RegisteredPlatforms() []model.Platform

RegisteredPlatforms returns a list of all registered platforms.

func ResolvePatch added in v0.135.0

func ResolvePatch[T any](patch *T, legacy T, isEmpty func(T) bool) (val T, specified bool)

ResolvePatch 是 Update*Options 三态解析核心(2A,spec 2026-11-12-phase2a-tristate-design):

  • patch 非 nil:全量替换——返回 *patch,specified=true;空值("" / 空切片)即显式清空;
  • patch nil:回落旧字段语义——isEmpty(legacy) 时 specified=false(不 动),否则返回 legacy、specified=true(置值);
  • 双字段同设:patch 立即返回(优先,spec 裁决 3)。

specified=false → 后端不动该 wire 字段;specified && isEmpty(val) → 清空(平台 B 级则返回 ErrClearNotSupported);specified && !isEmpty → 置值。

func Stubs

func Stubs(divs []Divergence, method string) bool

Stubs reports whether the ledger registers method as a stub. 同 Ignores:早退谓词无 slicex 原语对应,保留手写循环。

func SumDiffStats

func SumDiffStats(files []*model.ChangedFile) (additions, deletions int)

SumDiffStats returns total additions and deletions from a list of ChangedFiles.

func Version added in v0.72.0

func Version() string

Version returns the runtime version of the go-git-platform module, as resolved from Go build info. It reports "dev" for development builds (in-module go run/go test) where no module version is stamped.

The value is also injected as part of the default User-Agent header on every outgoing HTTP request made through the transport layer, so platform operators can identify (and, where offered, rate-limit-mercy) SDK-driven traffic.

func Wrap

func Wrap(platform model.Platform, op string, err error) error

Wrap creates a ProviderError from a raw error, classifying it when the cause is a transport error with a known status code. The original error chain is always preserved: Cause stays rooted at the raw error (with the classification sentinel wrapped in front via %w), so errors.Is matches both the sentinel (ErrNotFound & co.) and any error from the original chain, and the Error() message retains the platform's original detail. Use this in platform implementations to convert transport errors into the unified shape.

func WrapStatusError

func WrapStatusError(err error, statusCode int) error

WrapStatusError wraps an error with an explicit HTTP status code. This is the preferred way to attach status codes to third-party SDK errors instead of relying on reflection-based detection.

func Wrapf

func Wrapf(platform model.Platform, op, format string, args ...any) error

Wrapf is a convenience for creating a ProviderError with a formatted message. The format is intentionally simple ("%s/%s") so platform code can embed the resource identifier without re-implementing the prefix logic.

Types

type AddCollaboratorOptions

type AddCollaboratorOptions struct {
	Permission string `json:"permission,omitempty"` // "read", "write", "admin"
}

AddCollaboratorOptions contains options for adding a collaborator.

type AddDeployKeyOptions

type AddDeployKeyOptions struct {
	Title    string `json:"title"`
	Key      string `json:"key"`
	ReadOnly bool   `json:"read_only,omitempty"`
}

AddDeployKeyOptions contains options for adding a deploy key.

type BranchManager

type BranchManager interface {
	ListBranches(ctx context.Context, owner, repo string) ([]*model.PlatformBranch, error)
	CreateBranch(ctx context.Context, owner, repo, branch, ref string) (*model.PlatformBranch, error)
	DeleteBranch(ctx context.Context, owner, repo, branch string) error
}

BranchManager handles branch operations.

type BranchProtectionManager

type BranchProtectionManager interface {
	// ListBranchProtections returns all branch protection rules for a repo.
	ListBranchProtections(ctx context.Context, owner, repo string) ([]*model.BranchProtection, error)
	// GetBranchProtection returns the protection rule for a specific branch.
	// 契约:绝不返回 (nil, nil)——规则不存在时是 (nil, ErrNotFound)
	// (tencentcode #90 同族语义);非 nil 实体必伴 err==nil。
	// EnsureBranchProtection 对违约的 (nil, nil) 有防御(视为缺席→Create)。
	GetBranchProtection(ctx context.Context, owner, repo, branch string) (*model.BranchProtection, error)
	// CreateBranchProtection creates a new branch protection rule.
	CreateBranchProtection(ctx context.Context, owner, repo string, opts CreateBranchProtectionOptions) (*model.BranchProtection, error)
	// UpdateBranchProtection updates an existing branch protection rule.
	UpdateBranchProtection(ctx context.Context, owner, repo, branch string, opts UpdateBranchProtectionOptions) (*model.BranchProtection, error)
	// DeleteBranchProtection removes the protection rule for a branch.
	DeleteBranchProtection(ctx context.Context, owner, repo, branch string) error
}

BranchProtectionManager provides branch protection rule CRUD. It is an optional capability interface: consumers should gate on Provider.Capabilities().BranchProtections (or type-assert) before use.

Platform support: GitHub, GitCode, GitLab, Gitea, Forgejo, Gitee, TencentCode. TencentCode's list returns branch-row summaries (the platform has no list-protected endpoint; approver rules surface via GetBranchProtection), and allow-force-push is write-only there — see the tencentcode divergence ledger for the registered details. The platform- specific TencentCodeExtras still exposes the finer-grained protected- branch member management the unified contract does not model.

type CILogManager added in v0.67.0

type CILogManager interface {
	// ListFailedJobLogs returns the failed jobs of the most recent pipeline
	// run for a commit, each with the tail of its execution log. A commit
	// with no CI run (or a green one) yields an empty slice, not an error.
	// Platforms whose CI fans out a commit into multiple pipelines (one per
	// workflow) report the latest run per pipeline definition — see each
	// backend's divergence ledger for the exact fan-out semantics.
	ListFailedJobLogs(ctx context.Context, owner, repo, sha string) ([]model.JobLog, error)
}

CILogManager fetches failure diagnostics from a platform's CI system. It is an optional capability interface: consumers should check Capabilities().CILogs (or type-assert) before use. GitLab reads its native pipelines; GitHub, Gitea, and GitCode map onto their Actions surfaces (runs-by-SHA → failed jobs → job log tails); platforms without a job-log wire express absence by not declaring the capability.

type CapabilitySet

type CapabilitySet struct {
	Issues            bool // provider.IssueManager
	Search            bool // provider.SearchManager
	Labels            bool // provider.LabelManager
	Milestones        bool // provider.MilestoneManager
	Reviews           bool // provider.ReviewManager
	CommitStatuses    bool // provider.CommitStatusManager
	Notifications     bool // provider.NotificationManager
	Reactions         bool // provider.ReactionManager
	BranchProtections bool // provider.BranchProtectionManager
	Collaborators     bool // provider.CollaboratorManager
	WebhookConfig     bool // provider.WebhookConfigManager
	DeployKeys        bool // provider.DeploymentKeyManager
	RepoStats         bool // provider.RepoStatsManager
	Users             bool // provider.UserManager
	Gists             bool // provider.GistManager
	Starred           bool // provider.StarredManager
	Migrations        bool // provider.MigrationManager
	ReleaseAssets     bool // provider.ReleaseAssetManager
	CILogs            bool // provider.CILogManager
	Deployments       bool // provider.DeploymentManager
	RepoTemplates     bool // provider.TemplateRepoManager
	ForkSync          bool // provider.ForkSyncManager
	TeamReviews       bool // provider.TeamReviewManager
}

CapabilitySet statically declares which optional capability interfaces a Provider implements. Values are compile-time constants per backend; no runtime probing is performed. Consumers should route on these flags instead of probing with type assertions:

if p.Capabilities().Labels {
	lm := p.(provider.LabelManager)
	// ...
}

When a new optional capability interface is added to the SDK, add a field here and update every backend's Capabilities method; the contract suite enforces that declarations match implementations.

func DeriveCapabilities added in v0.82.0

func DeriveCapabilities(p Provider) CapabilitySet

DeriveCapabilities builds a CapabilitySet from the concrete provider's optional-manager implementations — the runtime type assertion is the SINGLE source of truth for what a backend supports. Backend Capabilities() methods delegate here, so the declaration can no longer drift from the implementation (contracttest's bidirectional check then guards against a backend bypassing the derivation with a hand-written literal).

This collapses the historical dual channel: pre-0.82 each backend wrote a literal of 12–17 bools that consumers cross-checked against assertions.

type ChangeRequestManager

type ChangeRequestManager interface {
	CreateCR(ctx context.Context, opts CreateCROptions) (*model.ChangeRequest, error)
	GetCR(ctx context.Context, owner, repo, number string) (*model.ChangeRequest, error)
	// ListCRs lists change requests. Page semantics: caller-paged family
	// (issue #60, see NormalizePageOpts) — Page == 0 returns the platform's
	// first page in one request; Page > 0 returns exactly that page.
	//
	// total carries the platform's own metadata for the served page: exact
	// (X-Total / X-Total-Count / response payload) or header-derived
	// (GitHub's Link header yields LastPage*PerPage — an upper bound for
	// the served page, registered as a mapping divergence on the GitHub
	// backend). total is nil when the platform provided no authoritative
	// count — an unknown is reported as unknown, never as the page length.
	ListCRs(ctx context.Context, opts ListCROptions) ([]*model.ChangeRequest, *int, error)
	MergeCR(ctx context.Context, owner, repo, number string, opts MergeCROptions) (*model.ChangeRequest, error)
	CloseCR(ctx context.Context, owner, repo, number string) (*model.ChangeRequest, error)
	ReopenCR(ctx context.Context, owner, repo, number string) (*model.ChangeRequest, error)
	UpdateCR(ctx context.Context, owner, repo, number string, opts UpdateCROptions) (*model.ChangeRequest, error)
	UpdateCRLabels(ctx context.Context, owner, repo, number string, labels []string) error
	ListCRComments(ctx context.Context, owner, repo, number string) ([]*model.CRComment, error)
	ListCRCommits(ctx context.Context, owner, repo, number string) ([]*model.CRCommit, error)
}

ChangeRequestManager handles pull request / merge request lifecycle. Change request numbers are strings (same addressing scheme as IssueManager); numeric platforms parse with strconv and fail with a wrapped "invalid pull request number" error.

type CollaboratorManager

type CollaboratorManager interface {
	// ListCollaborators returns all collaborators on a repository.
	ListCollaborators(ctx context.Context, owner, repo string) ([]*model.Collaborator, error)
	// AddCollaborator adds a user as a collaborator. Permission is
	// platform-specific ("read", "write", "admin"; empty = default).
	AddCollaborator(ctx context.Context, owner, repo, username string, opts AddCollaboratorOptions) error
	// RemoveCollaborator removes a user from the repository.
	RemoveCollaborator(ctx context.Context, owner, repo, username string) error
}

CollaboratorManager provides repository collaborator management. It is an optional capability interface: consumers should gate on Provider.Capabilities().Collaborators (or type-assert) before use.

Platform support: GitHub, GitCode, GitLab, Gitea, Forgejo, Gitee, TencentCode. GitLab-family platforms (GitLab, TencentCode) back this with the project-members API: mutations resolve the username to a numeric user ID first (TTL-cached), and the read/write/admin permission vocabulary maps onto platform access levels (registered mappings).

type CommitManager

type CommitManager interface {
	GetCommit(ctx context.Context, owner, repo, sha string) (*model.CommitInfo, error)
	ListCommits(ctx context.Context, owner, repo string, opts ListCommitsOptions) ([]*model.CommitInfo, error)
	CompareCommits(ctx context.Context, owner, repo, base, head string) (*model.CompareResult, error)
}

CommitManager handles commit operations.

Commit statuses are NOT part of CommitManager: they are a CI reporting concern that not every platform exposes (Gitee's public REST API has no commit-status endpoint). See the optional CommitStatusManager capability interface and CapabilitySet.CommitStatuses.

type CommitStatusManager

type CommitStatusManager interface {
	CreateCommitStatus(ctx context.Context, owner, repo, sha string, opts CommitStatusOptions) error
	// ListCommitStatuses returns the statuses reported on a commit,
	// newest first (the platforms' native order). State is normalized
	// into the CommitStatusState vocabulary by the backend.
	ListCommitStatuses(ctx context.Context, owner, repo, sha string) ([]model.CommitStatus, error)
}

CommitStatusManager reports CI statuses on commits. It is an optional capability interface: consumers should gate on Provider.Capabilities().CommitStatuses (or type-assert) before use.

It is deliberately separate from CommitManager: commit statuses are a CI reporting concern that not every platform exposes (Gitee's public REST API has no commit-status endpoint), so absence is expressed by not declaring the capability instead of stubbing the method.

type CommitStatusOptions

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

CommitStatusOptions contains options for creating a commit status.

type Config

type Config struct {
	Platform model.Platform
	BaseURL  string
	Token    string
	SkipTLS  bool

	// TokenSource, when non-nil, supplies the access token on every
	// request through the transport layer and takes precedence over Token.
	// Use it for credentials that rotate or expire (GitHub App installation
	// tokens, OAuth flows); see the TokenSource interface. Static tokens
	// keep using Token.
	TokenSource TokenSource

	// ConditionalRequests enables HTTP conditional requests for GETs: the
	// transport caches responses keyed by their ETag, sends If-None-Match
	// on re-reads, and replays the cached body when the platform answers
	// 304. On platforms that meter 304s favorably (GitHub) this raises
	// sustainable polling rates for wait-for-CI style workloads. Off by
	// default; see transport.ETagCache for the exact semantics.
	ConditionalRequests bool

	// TokenStyle overrides the default authentication header style.
	// Supported values: "private" (PRIVATE-TOKEN, default for GitLab),
	// "bearer" (Authorization: Bearer). Empty string uses platform default.
	TokenStyle string

	// Logger for provider operations. Defaults to a no-op logger.
	Logger Logger
	// RetryConfig for automatic retry on transient failures. nil means no retry.
	RetryConfig *RetryConfig
	// Hooks for request/response lifecycle interception.
	Hooks *Hooks
}

Config holds the configuration for creating a Provider.

type CreateBranchProtectionOptions

type CreateBranchProtectionOptions struct {
	BranchName               string `json:"branch_name"`
	RequiredApprovingReviews int    `json:"required_approving_reviews,omitempty"`
	RequiredStatusChecks     bool   `json:"required_status_checks,omitempty"`
	AllowForcePushes         bool   `json:"allow_force_pushes,omitempty"`
	AllowDeletions           bool   `json:"allow_deletions,omitempty"`
}

CreateBranchProtectionOptions contains options for creating a branch protection rule.

type CreateCROptions

type CreateCROptions struct {
	Owner              string   `json:"owner"`
	Repo               string   `json:"repo"`
	Title              string   `json:"title"`
	Description        string   `json:"description,omitempty"`
	SourceBranch       string   `json:"source_branch"`
	TargetBranch       string   `json:"target_branch"`
	Labels             []string `json:"labels,omitempty"`
	RemoveSourceBranch bool     `json:"remove_source_branch,omitempty"`
	// Draft 以草稿/work-in-progress 形态创建 CR(#160,读侧 ChangeRequest.Draft
	// 对齐)。缺省 false = 现行为,wire 逐字不变。true 仅平台创建面可表达时
	// 下发(GitHub/Gitee/GitCode);gitlab/gitea/forgejo/tencentcode 的
	// SDK/API 创建面无该参数——显式返回 ErrDraftNotSupported(台账
	// Field:"opts.Draft" 登记),绝不静默产出非 draft CR。
	Draft bool `json:"draft,omitempty"`
}

CreateCROptions contains options for creating a change request.

type CreateDeploymentOptions added in v0.106.0

type CreateDeploymentOptions struct {
	// Task is the deployment task name ("deploy" default on the wire).
	Task string `json:"task,omitempty"`
	// Description is the payload description.
	Description string `json:"description,omitempty"`
	// AutoMerge / RequiredContexts / Payload fields are GitHub-specific;
	// leave zero to take the platform defaults. RequiredContexts: nil = not
	// sent, non-nil (even empty) = replace the required-context set.
	AutoMerge        *bool             `json:"auto_merge,omitempty"`
	RequiredContexts []string          `json:"required_contexts,omitempty"`
	Payload          map[string]string `json:"payload,omitempty"`
}

CreateDeploymentOptions carries the optional fields of a deployment request. Ref and Environment are positional.

type CreateIssueOptions

type CreateIssueOptions struct {
	Owner     string   `json:"owner"`
	Repo      string   `json:"repo"`
	Title     string   `json:"title"`
	Body      string   `json:"body,omitempty"`
	Assignees []string `json:"assignees,omitempty"`
	Labels    []string `json:"labels,omitempty"`
	Milestone string   `json:"milestone,omitempty"` // milestone number/ID as a string; "" = do not set
}

CreateIssueOptions contains options for creating an issue.

type CreateLabelOptions

type CreateLabelOptions struct {
	Name        string `json:"name"`
	Color       string `json:"color"`
	Description string `json:"description,omitempty"`
}

CreateLabelOptions contains options for creating a repository label. Color uses the canonical 6-digit hex form without '#' (e.g. "ff0000").

type CreateMigrationOptions added in v0.72.0

type CreateMigrationOptions struct {
	// LockRepositories 迁移期间锁定仓库(防止导出过程中数据变动)。
	LockRepositories bool `json:"lock_repositories"`
	// ExcludeMetadata 跳过 issues/PR 等元数据、只导出仓库内容。
	ExcludeMetadata bool `json:"exclude_metadata"`
}

CreateMigrationOptions 发起归档迁移的选项。json tag 与 GitHub 迁移 API 请求体字段一致,便于后端直接序列化上送。

type CreateMilestoneOptions

type CreateMilestoneOptions struct {
	Title       string     `json:"title"`
	Description string     `json:"description,omitempty"`
	DueOn       *time.Time `json:"due_on,omitempty"`
}

CreateMilestoneOptions contains options for creating a repository milestone.

type CreateReleaseOptions

type CreateReleaseOptions struct {
	TagName    string `json:"tag_name"`
	Target     string `json:"target,omitempty"`
	Title      string `json:"title"`
	Body       string `json:"body,omitempty"`
	Draft      bool   `json:"draft,omitempty"`
	Prerelease bool   `json:"prerelease,omitempty"`
}

CreateReleaseOptions contains options for creating a release.

type CreateRepoFromTemplateOptions added in v0.106.0

type CreateRepoFromTemplateOptions struct {
	// Owner is the target owner/org login; empty = authenticated user.
	Owner string `json:"owner,omitempty"`
	// Name is the new repository's name (required).
	Name string `json:"name"`
	// Description of the new repository.
	Description string `json:"description,omitempty"`
	// Private controls visibility.
	Private bool `json:"private,omitempty"`
	// IncludeAllBranches copies every branch instead of the default branch
	// alone (GitHub wire; Gitea takes the platform default).
	IncludeAllBranches bool `json:"include_all_branches,omitempty"`
}

CreateRepoFromTemplateOptions carries the new repository's fields.

type CreateRepoOptions

type CreateRepoOptions struct {
	Name          string `json:"name"`
	Description   string `json:"description,omitempty"`
	Private       bool   `json:"private,omitempty"`
	AutoInit      bool   `json:"auto_init,omitempty"`
	DefaultBranch string `json:"default_branch,omitempty"`
}

CreateRepoOptions contains options for creating a repository.

type CreateReviewOptions

type CreateReviewOptions struct {
	CommitID string                `json:"commit_id,omitempty"`
	Event    string                `json:"event,omitempty"`
	Body     string                `json:"body,omitempty"`
	Comments []model.ReviewComment `json:"comments,omitempty"`
}

CreateReviewOptions contains options for creating a review.

type CreateWebhookOptions

type CreateWebhookOptions struct {
	Owner  string   `json:"owner"`
	Repo   string   `json:"repo"`
	URL    string   `json:"url"`
	Secret string   `json:"secret,omitempty"`
	Events []string `json:"events,omitempty"`
	// EnsureSecretMode is consumed only by EnsureWebhook (CreateWebhook
	// ignores it): EnsureSecretKeep trusts a URL+events match and keeps
	// the platform-held secret; EnsureSecretAlwaysUpdate rewrites the
	// secret on a match, converging host-side rotations. See
	// EnsureSecretMode for the write-only rationale.
	EnsureSecretMode EnsureSecretMode `json:"ensure_secret_mode,omitempty"`
}

CreateWebhookOptions contains options for creating a webhook.

type DeploymentKeyManager

type DeploymentKeyManager interface {
	// ListDeployKeys returns all deploy keys for a repository.
	ListDeployKeys(ctx context.Context, owner, repo string) ([]*model.DeployKey, error)
	// AddDeployKey adds a new deploy key to the repository.
	AddDeployKey(ctx context.Context, owner, repo string, opts AddDeployKeyOptions) (*model.DeployKey, error)
	// DeleteDeployKey removes a deploy key by its platform ID.
	DeleteDeployKey(ctx context.Context, owner, repo string, keyID int64) error
}

DeploymentKeyManager provides deploy key CRUD for CI/CD. It is an optional capability interface: consumers should gate on Provider.Capabilities().DeployKeys (or type-assert) before use.

Platform support: GitHub, GitCode, GitLab, Gitea, Forgejo. Gitee and TencentCode have no deploy key API.

type DeploymentManager added in v0.106.0

type DeploymentManager interface {
	// CreateDeployment requests a deployment of ref to environment.
	CreateDeployment(ctx context.Context, owner, repo, ref, environment string, opts CreateDeploymentOptions) (*model.Deployment, error)
	// ListDeployments lists a repository's deployment records, newest first,
	// optionally filtered by environment. The int return is the number of
	// items on the returned page (the IssueManager total convention); the
	// platform serves no repository-wide total on this endpoint.
	ListDeployments(ctx context.Context, owner, repo string, environment string, page, perPage int) ([]*model.Deployment, int, error)
	// CreateDeploymentStatus reports state on a deployment.
	CreateDeploymentStatus(ctx context.Context, owner, repo string, deploymentID int64, opts DeploymentStatusOptions) error
}

DeploymentManager reports and drives a platform-native deployment pipeline. Optional capability interface: check Capabilities().Deployments (or type-assert) before use. Currently GitHub-only — its deployments API is the only wire with a manual create-deployment + deployment-status state machine (GitLab's deployment records are CI-produced and carry no manual status wire).

type DeploymentStatusOptions added in v0.106.0

type DeploymentStatusOptions struct {
	// State is required: pending|in_progress|queued|success|failure|error|
	// canceled|inactive (GitHub deployment-status vocabulary).
	State string `json:"state"`
	// Description is a short status description.
	Description string `json:"description,omitempty"`
	// LogURL is the link to the deployment output.
	LogURL string `json:"log_url,omitempty"`
	// EnvironmentURL is the URL exposed to users when the deployment
	// succeeded.
	EnvironmentURL string `json:"environment_url,omitempty"`
	// AutoInactive marks earlier "in_progress" environments inactive when
	// this one succeeds (GitHub semantics; nil = platform default).
	AutoInactive *bool `json:"auto_inactive,omitempty"`
}

DeploymentStatusOptions carries one deployment state report.

type DiffManager

type DiffManager interface {
	GetCRDiff(ctx context.Context, owner, repo, number string) (*model.MergeDiff, error)
	GetCRFiles(ctx context.Context, owner, repo, number string) ([]*model.ChangedFile, error)
	CreateNote(ctx context.Context, owner, repo, number, body string) (string, error)
	DeleteNote(ctx context.Context, owner, repo, number string, noteID string) error
	CreateDiscussion(ctx context.Context, owner, repo, number string, opts DiscussionOptions) (string, error)
}

DiffManager handles diff and discussion operations. Review operations (CreateReview and friends) live on the optional ReviewManager capability interface; DiffManager itself carries five methods. Change request numbers are strings (same addressing scheme as IssueManager); numeric platforms parse with strconv and fail with a wrapped "invalid pull request number" error.

type DiscussionOptions

type DiscussionOptions struct {
	Body         string `json:"body"`
	FilePath     string `json:"file_path,omitempty"`
	NewLine      int    `json:"new_line,omitempty"`
	OldLine      int    `json:"old_line,omitempty"`
	StartNewLine int    `json:"start_new_line,omitempty"`
	BaseSHA      string `json:"base_sha,omitempty"`
	StartSHA     string `json:"start_sha,omitempty"`
	HeadSHA      string `json:"head_sha,omitempty"`
}

DiscussionOptions contains options for creating a discussion comment.

type Divergence

type Divergence struct {
	Capability string
	Method     string
	Field      string
	Kind       DivergenceKind
	Reason     string
}

Divergence is one registered entry of a backend's divergence ledger. Capability and Method carry the provider interface and method names; Field names the affected option/result field for ignore and mapping entries (empty when the divergence is method-scoped). Reason is a one-sentence explanation surfaced in docs/divergence-ledger.md.

Backends expose their ledger via a package-level Divergences function and the Provider.Divergences method; the ledger is the machine-readable successor of the former "(spec §4.6)" comment registrations.

func FindByMethod

func FindByMethod(divs []Divergence, method string) []Divergence

FindByMethod returns the ledger entries registered for method.

type DivergenceKind

type DivergenceKind string

DivergenceKind classifies how a backend's behavior departs from the unified provider semantics for a given method.

const (
	// DivergenceStub marks a method the platform cannot serve at all: the
	// call returns an error wrapping ErrNotImplemented and touches no wire.
	DivergenceStub DivergenceKind = "stub"
	// DivergenceIgnore marks a field or parameter that is silently dropped:
	// the call succeeds but the ignored input has no effect.
	DivergenceIgnore DivergenceKind = "ignore"
	// DivergenceMapping marks a semantic mapping: the call succeeds and
	// returns the closest platform equivalent, an approximation of the
	// unified semantics.
	DivergenceMapping DivergenceKind = "mapping"
	// DivergenceDetour marks an implementation detour: the method bypasses
	// the platform's third-party SDK and drives the raw transport client.
	// Behavior is unchanged; the entry exists for maintainers.
	DivergenceDetour DivergenceKind = "detour"
)

type EnsureSecretMode added in v0.114.0

type EnsureSecretMode string

EnsureSecretMode controls how EnsureWebhook treats a matching hook's secret. Platform webhook secrets are write-only on every platform (list responses never return them), so a hook that already matches URL + events cannot be verified to carry the desired secret — it may be stale after a host-side rotation, and a stale secret makes every delivery fail signature validation (fail-closed, silently).

位置裁定(S2 runtime 剖离):本类型是 CreateWebhookOptions 的字段类型 (契约参数面,C5 留 provider),而 runtime/ensure.go 依赖 provider —— 若随 ensure.go 迁 runtime 即成 provider→runtime 反向边与 import 环, 故与所属字段同留 provider;EnsureWebhook(runtime)单向引用它。

const (
	// EnsureSecretKeep (default, also the zero value) trusts the match:
	// a hook that already matches URL + events is left untouched even if
	// opts.Secret differs from what the platform may hold.
	EnsureSecretKeep EnsureSecretMode = ""
	// EnsureSecretAlwaysUpdate rewrites the secret whenever the hook
	// matches and opts.Secret is non-empty, converging rotations in the
	// same ensure call: the in-place patch goes through
	// WebhookConfigManager.UpdateWebhook (implemented by every backend),
	// keeps the hook's platform ID, and reports EnsureUpdated. A manager
	// that does not also implement WebhookConfigManager is an error —
	// silently keeping a possibly-stale secret would defeat the mode.
	EnsureSecretAlwaysUpdate EnsureSecretMode = "always-update"
)

type FileDeleteOptions

type FileDeleteOptions struct {
	Path    string `json:"path"`
	Message string `json:"message"`
	Branch  string `json:"branch,omitempty"`
	SHA     string `json:"sha,omitempty"`
	Author  string `json:"author,omitempty"`
	Email   string `json:"email,omitempty"`
}

FileDeleteOptions contains options for deleting a file.

type FileManager

type FileManager interface {
	GetFileContent(ctx context.Context, owner, repo, path, ref string) (string, error)
	CreateFile(ctx context.Context, owner, repo string, opts FileOptions) (*model.FileResult, error)
	UpdateFile(ctx context.Context, owner, repo string, opts FileOptions) (*model.FileResult, error)
	DeleteFile(ctx context.Context, owner, repo string, opts FileDeleteOptions) (*model.FileResult, error)
}

FileManager handles file CRUD operations on repositories.

Content crosses this seam as plaintext: GetFileContent returns the decoded bytes and FileOptions.Content is what should land in the repository. Adapters apply platform wire encodings internally — the gitea/forgejo family base64-encodes content at its port boundary because both SDKs require it, GitHub's SDK base64-encodes []byte, and GitLab takes the string verbatim. A caller writes one code path and never branches on the platform's encoding (issue #169).

type FileOptions

type FileOptions struct {
	Path string `json:"path"`
	// Content is the file's plaintext content, never base64: the adapter
	// applies the platform's wire encoding (gitea/forgejo family: base64).
	Content string `json:"content"`
	Message string `json:"message"`
	Branch  string `json:"branch,omitempty"`
	SHA     string `json:"sha,omitempty"`
	Author  string `json:"author,omitempty"`
	Email   string `json:"email,omitempty"`
}

FileOptions contains options for creating or updating a file.

Content is PLAINTEXT — the bytes as they should land in the repository. The wire form differs by platform: the gitea/forgejo family's SDKs require their content field base64-encoded (gitea.dev/sdk and forgejo-sdk: "content must be base64 encoded"; the family adapter applies that codec), GitHub's SDK encodes []byte internally, and GitLab takes the string verbatim. Callers must NOT pre-encode: the adapter that needs a codec applies it, and pre-encoding would make the base64 text itself the file on the platforms that take plaintext (issue #169).

type ForkRepoOptions

type ForkRepoOptions struct {
	Organization string `json:"organization,omitempty"`
	Name         string `json:"name,omitempty"`
}

ForkRepoOptions contains options for forking a repository.

type ForkSyncManager added in v0.106.0

type ForkSyncManager interface {
	// SyncFork merges the upstream branch into the fork's branch of the
	// same name; conflicts are NOT resolved server-side — the call errors
	// and leaves the conflict for manual resolution.
	SyncFork(ctx context.Context, owner, repo, branch string) error
}

ForkSyncManager syncs a fork's branch with its upstream counterpart. Optional capability interface: check Capabilities().ForkSync before use (GitHub merge-upstream).

type GistManager added in v0.72.0

type GistManager interface {
	// ListMyGists 分页列出 token 用户可见的 gist(GET /gists:已认证调用
	// 返回当前用户的 gist 列表)。page/perPage 语义与其他分页方法一致,
	// 非法值经 NormalizePageOpts 归一。
	ListMyGists(ctx context.Context, page, perPage int) ([]*model.Gist, error)
}

GistManager 提供认证用户自己的 gist 列表。可选能力接口:使用前先看 Provider.Capabilities().Gists(或类型断言)。目前只读——下游备份场景 只需要分页列出,创建/修改 gist 不在统一接口范围内。

type Hooks

type Hooks struct {
	Request  []RequestHook
	Response []ResponseHook
}

Hooks holds request and response lifecycle hooks. These are mapped into transport.Hooks by each backend's constructor; direct callers should use the Hooks struct to register hooks via provider.Config.

func (*Hooks) AddRequestHook

func (h *Hooks) AddRequestHook(hook RequestHook)

AddRequestHook appends a request hook.

func (*Hooks) AddResponseHook

func (h *Hooks) AddResponseHook(hook ResponseHook)

AddResponseHook appends a response hook.

type IssueManager

type IssueManager interface {
	// ListIssues lists a repository's issues under the caller-paged
	// pagination contract (issue #51 — see NormalizePageOpts, which anchors
	// the SDK-wide Page semantics): opts.Page == 0 (the zero value, the
	// default) serves the platform's FIRST page at the normalized page
	// size — one request, no walk; opts.Page > 0 returns exactly that
	// page; callers page through explicitly until a short page comes back.
	// The int return is uniformly len(issues), the served rows' count —
	// NOT a platform total. Callers that need the total should page until
	// a short page and count, or read it off the platform's own headers
	// via a raw client.
	ListIssues(ctx context.Context, opts ListIssuesOptions) ([]*model.Issue, int, error)
	GetIssue(ctx context.Context, owner, repo, number string) (*model.Issue, error)
	CreateIssue(ctx context.Context, opts CreateIssueOptions) (*model.Issue, error)
	UpdateIssue(ctx context.Context, owner, repo, number string, opts UpdateIssueOptions) (*model.Issue, error)
	CloseIssue(ctx context.Context, owner, repo, number string) (*model.Issue, error)
	ReopenIssue(ctx context.Context, owner, repo, number string) (*model.Issue, error)
	// ListIssueComments returns the issue's comments in full, exhausting
	// the platform's pagination — the result is the complete comment list,
	// not a single page, in the platform's default order.
	ListIssueComments(ctx context.Context, owner, repo, number string) ([]*model.IssueComment, error)
	CreateIssueComment(ctx context.Context, owner, repo, number, body string) (*model.IssueComment, error)
	// UpdateIssueComment replaces a comment's body wholesale: every
	// platform's edit surface is a body-only PATCH/PUT with no
	// partial-update semantics, mirroring CreateIssueComment. The platform
	// enforces authorship — only the comment's author (typically the token
	// identity, e.g. a review bot updating its own comment) may edit — so
	// the call fails for anyone else's comment. commentID is the
	// IssueComment.ID from CreateIssueComment or ListIssueComments. number
	// is ignored on platforms whose edit endpoint addresses the comment
	// directly (GitHub, Gitea, Forgejo, GitCode, Gitee); GitLab and Tencent
	// 工蜂 route through the issue, so it must carry that issue's number.
	UpdateIssueComment(ctx context.Context, owner, repo, number string, commentID int64, body string) (*model.IssueComment, error)
	// DeleteIssueComment removes a comment. commentID is the
	// IssueComment.ID from CreateIssueComment or ListIssueComments, the
	// same address space UpdateIssueComment writes to; the platform
	// enforces authorship — only the comment's author (typically the token
	// identity rotating its own report comment) may delete — so the call
	// fails for anyone else's comment. number is ignored on platforms
	// whose delete endpoint addresses the comment directly (GitHub, Gitea,
	// Forgejo, GitCode, Gitee); GitLab and Tencent 工蜂 route through the
	// issue, so it must carry that issue's number. Deletion is permanent:
	// callers wanting "edit instead" semantics (summary-comment rotation
	// that preserves history) should prefer UpdateIssueComment.
	DeleteIssueComment(ctx context.Context, owner, repo, number string, commentID int64) error
	ListIssueLabels(ctx context.Context, owner, repo string) ([]*model.IssueLabel, error)
	AddIssueLabels(ctx context.Context, owner, repo, number string, labels []string) error
	RemoveIssueLabel(ctx context.Context, owner, repo, number, name string) error
	// RemoveIssueLabels 移除多个标签(AddIssueLabels 的对称面,#163):
	// 保序处理、首错即停——已移除的不回滚,部分失败语义在本方法单点收口,
	// 消费方不再各自循环 N 次 HTTP。labels 为空返回 nil、零请求。
	// 无原生 bulk-remove-some 的平台在后端内部循环保序收口
	// (GitHub/Gitea/Forgejo/GitCode/Gitee);GitLab 走 remove_labels
	// 单请求、TencentCode 走读改写单次 PUT(其整集写限制见 divergence 台账)。
	RemoveIssueLabels(ctx context.Context, owner, repo, number string, labels []string) error
}

IssueManager provides issue CRUD, comments, and label management. Issue numbers are strings: every platform address is representable as a string, and Gitee natively uses alphanumeric identifiers (e.g. "IAINVA"). Backends on numeric platforms parse with strconv.Atoi and fail with a wrapped "invalid issue number" error.

type LabelManager

type LabelManager interface {
	// ListLabels lists the repository's labels. Page semantics: exhaustive
	// family (issue #60, see NormalizePageOpts) — Page == 0 walks every
	// page and returns all labels; Page > 0 returns exactly that page.
	ListLabels(ctx context.Context, owner, repo string, opts ListLabelsOptions) ([]*model.Label, error)
	// CreateLabel creates a repository label.
	CreateLabel(ctx context.Context, owner, repo string, opts CreateLabelOptions) (*model.Label, error)
	// UpdateLabel updates the label with the given name. Nil fields in opts
	// are left unchanged.
	UpdateLabel(ctx context.Context, owner, repo, name string, opts UpdateLabelOptions) (*model.Label, error)
	// DeleteLabel deletes the label with the given name.
	DeleteLabel(ctx context.Context, owner, repo, name string) error
}

LabelManager provides repository-level label CRUD. It is an optional capability interface: consumers should gate on Provider.Capabilities() (or type-assert) before use. Labels are addressed by name; backends whose platform API addresses labels by numeric ID (GitLab, Gitea, Forgejo) resolve the name internally. Such backends scan labels with server-side pagination (100 per page, bounded to 50 pages); beyond that bound a label may be reported as not found by UpdateLabel/DeleteLabel even though it exists.

The issue-scoped operations (ListIssueLabels, AddIssueLabels, RemoveIssueLabel) remain on IssueManager because they operate on an issue, not on the repository's label set.

type ListCROptions

type ListCROptions struct {
	Owner string `json:"owner"`
	Repo  string `json:"repo"`
	// State 过滤状态。**空 = 不过滤(全部)**。
	//
	// 各后端的原生词表不同(open/closed/merged 与 opened/closed)⇒ 平台层的
	// "空" 语义必须统一,否则同一个调用在有的平台只拿到 open、在别的平台拿到全部
	// —— 调用方无从察觉 closed/merged 的那部分**静默丢失**。
	// (GitHub / GitLab / 工蜂 本来就是"空=不过滤";Gitee / Gitea / Forgejo /
	//  GitCode 曾把空值映射成 open ⇒ 已对齐。)
	State model.CRState `json:"state,omitempty"`
	// SourceBranch filters by the source branch. The cross-backend contract
	// (issue #78): a pure branch name ("feature-x") matches every change
	// request whose head branch is named so - including fork-sourced ones
	// (the unified ChangeRequest.SourceBranch is the namespace-free head
	// ref everywhere). An "owner:branch" form is honored on GitHub's
	// namespace-pinned server filter as an exact match; on GitLab-family
	// backends the same string filters server-side by branch name.
	SourceBranch string `json:"source_branch,omitempty"`
	TargetBranch string `json:"target_branch,omitempty"`
	// Page semantics: caller-paged family (issue #60 — see
	// NormalizePageOpts). Page == 0 returns the platform's first page in a
	// single request; Page > 0 returns exactly that page. Tencent Code is
	// the registered departure: its Page == 0 walks every page (divergence
	// ledger).
	Page    int `json:"page,omitempty"`
	PerPage int `json:"per_page,omitempty"`
}

ListCROptions contains options for listing change requests.

type ListCommitsOptions

type ListCommitsOptions struct {
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
	Branch  string `json:"branch,omitempty"`
	Since   string `json:"since,omitempty"` // RFC3339
	Until   string `json:"until,omitempty"` // RFC3339
}

ListCommitsOptions contains options for listing commits in a repository.

type ListIssuesOptions

type ListIssuesOptions struct {
	Owner    string           `json:"owner"`
	Repo     string           `json:"repo"`
	State    model.IssueState `json:"state,omitempty"`
	Assignee string           `json:"assignee,omitempty"`
	Labels   string           `json:"labels,omitempty"`
	Page     int              `json:"page,omitempty"`
	PerPage  int              `json:"per_page,omitempty"`
	// Sort 排序字段("created"|"updated"|"comments"),空 = 平台默认。
	//
	// **增量备份必须用它**:平台默认按 created 倒序 ⇒ "上次备份后被改动的
	// **老** issue"正好被挤在第一页之外,客户端再按 updated 过滤也捞不到
	// (捞到的永远是"最新创建"的那批)。
	//
	// 支持情况(逐后端登记在各自的 divergence 账本里):
	//   - GitHub:支持(sort + direction);
	//   - GitLab:支持(order_by=created_at|updated_at + sort=asc|desc);
	//   - Gitee / Gitea / Forgejo / GitCode / 工蜂:当前 SDK 不暴露(或词表无法确证)
	//     ⇒ 传入被忽略(调用方需自己兜底,见 core 的增量采集)。
	Sort string `json:"sort,omitempty"`
	// Direction 排序方向("asc"|"desc"),空 = 平台默认。
	Direction string `json:"direction,omitempty"`
}

ListIssuesOptions contains options for listing issues.

type ListLabelsOptions

type ListLabelsOptions struct {
	Page    int `json:"page,omitempty"`
	PerPage int `json:"per_page,omitempty"`
}

ListLabelsOptions contains options for listing repository labels.

Page semantics: exhaustive family (issue #60 — see NormalizePageOpts). Page == 0 walks every page and returns all labels; Page > 0 returns exactly that page.

type ListMilestonesOptions

type ListMilestonesOptions struct {
	State   string `json:"state,omitempty"`
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
}

ListMilestonesOptions contains options for listing repository milestones.

State contract (issue #61): "open" and "closed" filter; an empty State lists ALL milestones. Every backend that can express the "all" value on the wire sends it explicitly — the pre-contract behavior (forward the zero value, let the platform default) silently dropped closed milestones on the platforms whose own default is open-only. Tencent Code's list endpoint exposes no state filter at all: explicit states are dropped there (registered divergence), and its unfiltered output already matches the empty-State contract.

Page semantics: exhaustive family (issue #60 — see NormalizePageOpts). Page == 0 walks every page and returns all milestones; Page > 0 returns exactly that page.

type ListNotificationsOptions

type ListNotificationsOptions struct {
	All     bool   `json:"all,omitempty"`   // include already-read notifications
	Since   string `json:"since,omitempty"` // RFC3339 timestamp
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
}

ListNotificationsOptions contains options for listing notifications.

Page semantics: exhaustive family (issue #60 — see NormalizePageOpts). Page == 0 walks every page and returns all notifications — matching the interface's "exhausting the platform's pagination" promise; Page > 0 returns exactly that page.

type ListRepoOptions

type ListRepoOptions struct {
	Owner   string `json:"owner,omitempty"`
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
}

ListRepoOptions contains options for listing repositories on a platform.

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...any)
	Info(msg string, keysAndValues ...any)
	Warn(msg string, keysAndValues ...any)
	Error(msg string, keysAndValues ...any)
}

Logger is a minimal logging interface compatible with most Go logging libraries. Implementations include slog, zap, zerolog, logrus, etc.

func NewLogxLogger added in v0.85.0

func NewLogxLogger(component string) Logger

NewLogxLogger returns a Logger backed by the oekit/logx facade, for consumers who run the oekit observability stack. The logger is lazily resolved (logx.Delegating): it follows whatever implementation the consumer installs via logx.SetDefault / logx.UseSlog, even when that happens after NewProvider. component identifies this SDK in log output (the logx convention: service name belongs to the consumer, packages identify themselves via the component attribute).

p, err := provider.NewProvider(provider.Config{
    Platform: model.PlatformGitHub,
    Token:    token,
    Logger:   provider.NewLogxLogger("git-platform"),
})

func NewNoopLogger

func NewNoopLogger() Logger

NewNoopLogger returns a Logger that discards all output.

type MarkNotificationsOptions

type MarkNotificationsOptions struct {
	LastReadAt string `json:"last_read_at,omitempty"` // RFC3339; empty = mark all
}

MarkNotificationsOptions contains options for marking notifications as read.

type MergeCROptions

type MergeCROptions struct {
	MergeCommitMessage string `json:"merge_commit_message,omitempty"`
	Squash             bool   `json:"squash,omitempty"`
	RemoveSourceBranch bool   `json:"remove_source_branch,omitempty"`
}

MergeCROptions contains options for merging a change request.

type MigrationManager added in v0.72.0

type MigrationManager interface {
	// CreateMigration 发起迁移导出。org == "" 表示用户级迁移
	// (POST /user/migrations),非空表示组织级(POST /orgs/{org}/migrations)
	// ——同一语义贯穿本接口全部方法。
	CreateMigration(ctx context.Context, org string, opts CreateMigrationOptions) (*model.MigrationInfo, error)
	// GetMigration 查询迁移状态,org 语义与 CreateMigration 一致。
	GetMigration(ctx context.Context, org string, id int64) (*model.MigrationInfo, error)
}

MigrationManager 提供平台原生的「一键全量归档导出」(GitHub Migrations API)。可选能力接口:使用前先看 Provider.Capabilities().Migrations (或类型断言)。迁移是异步的:CreateMigration 立即返回任务 ID,消费方 轮询 GetMigration 直到 state 进入终态。

type MilestoneManager

type MilestoneManager interface {
	// ListMilestones lists the repository's milestones. State contract
	// (issue #61): "open"/"closed" filter, empty State lists ALL
	// milestones — platforms whose own default is open-only send the
	// platform's explicit "all" value instead of relying on the default,
	// so an empty State never silently drops closed milestones. Tencent
	// Code's list endpoint has no state filter (registered divergence).
	//
	// Page semantics: exhaustive family (issue #60, see NormalizePageOpts)
	// — Page == 0 walks every page; Page > 0 returns exactly that page.
	ListMilestones(ctx context.Context, owner, repo string, opts ListMilestonesOptions) ([]model.Milestone, error)
	// GetMilestone fetches the milestone with the given number.
	GetMilestone(ctx context.Context, owner, repo, number string) (*model.Milestone, error)
	// CreateMilestone creates a repository milestone.
	CreateMilestone(ctx context.Context, owner, repo string, opts CreateMilestoneOptions) (*model.Milestone, error)
	// UpdateMilestone updates the milestone with the given number. Nil
	// fields in opts are left unchanged.
	UpdateMilestone(ctx context.Context, owner, repo, number string, opts UpdateMilestoneOptions) (*model.Milestone, error)
	// DeleteMilestone deletes the milestone with the given number.
	DeleteMilestone(ctx context.Context, owner, repo, number string) error
}

MilestoneManager provides repository-level milestone CRUD. It is an optional capability interface: consumers should gate on Provider.Capabilities() (or type-assert) before use.

Milestones are addressed by a string `number`, but what that string carries is platform-specific — the same identifier MilestoneRef.Number and Milestone.Number expose:

  • GitHub: the milestone *number* (its per-repo serial number).
  • GitLab, Gitea, Forgejo, GitCode, Tencent Code: the platform milestone *ID* (the write endpoints take exactly that identifier, so per-platform round-trips hold).
  • Gitee: the milestone *serial number* (the "number" field of Gitee's milestone payload — the identifier Gitee's own issue and milestone write endpoints take; the SDK model exposes no id).

Values obtained from MilestoneRef.Number (issue payloads) or Milestone.Number (list/get results) round-trip back into these methods on the platform they came from.

type NoteManager added in v0.67.2

type NoteManager interface {
	// UpdateNote rewrites the body of one CR comment.
	UpdateNote(ctx context.Context, owner, repo, number, noteID, body string) (*model.IssueComment, error)
	// ListNotes returns every comment on the CR, oldest first (all pages).
	ListNotes(ctx context.Context, owner, repo, number string) ([]*model.IssueComment, error)
}

NoteManager provides targeted update and full pagination over CR (MR/PR) comments — an optional capability (v0.67.2). Semantics are anchored to the CR comment thread: on GitLab these hit the MergeRequest Notes API, because IssueManager's comment methods go through the Issues Notes API and always 404 for merge requests (MRs and issues live in separate iid namespaces). Platforms where an issue IS the PR (GitHub, Gitea, Gitee) are already covered by IssueManager and need not implement this interface.

type NotificationManager

type NotificationManager interface {
	// ListNotifications returns the authenticated user's notifications,
	// exhausting the platform's pagination.
	ListNotifications(ctx context.Context, opts ListNotificationsOptions) ([]*model.Notification, error)
	// ListRepoNotifications returns notifications for a specific repository.
	ListRepoNotifications(ctx context.Context, owner, repo string, opts ListNotificationsOptions) ([]*model.Notification, error)
	// MarkNotificationRead marks a single notification thread as read.
	MarkNotificationRead(ctx context.Context, threadID string) error
	// MarkNotificationsRead marks all (or filtered) notifications as read.
	MarkNotificationsRead(ctx context.Context, opts MarkNotificationsOptions) error
	// MarkRepoNotificationsRead marks all notifications for a repository as read.
	MarkRepoNotificationsRead(ctx context.Context, owner, repo string, opts MarkNotificationsOptions) error
}

NotificationManager provides access to a user's notification inbox and per-repository notification streams. It is an optional capability interface: consumers should gate on Provider.Capabilities().Notifications (or type-assert) before use.

Platform support (aligned with DeriveCapabilities and the divergence ledger, issue #124): GitHub, Gitea, Forgejo and Gitee serve the full surface. GitLab implements the interface over its Todos API — thread IDs are todo IDs and MarkRepoNotificationsRead is a registered ErrNotImplemented stub (the Todos API has no per-project mark-all), see the GitLab divergence ledger. GitCode serves only the repo-scoped half: the global routes 404 live (probe round 2026-11-03), so the three global methods return ErrNotImplemented and only ListRepoNotifications / MarkRepoNotificationsRead are usable — see the README matrix's ⚠² note. TencentCode has no notification API at all and reports Notifications=false.

type Operation added in v0.137.0

type Operation string

Operation 是操作级能力的封闭枚举(2B spec):只增不改,值即契约。 粒度案例:仓库级 vs 全局通知、单 webhook get/update——CapabilitySet 的 manager 级 bool 表达不了的层。

const (
	OpListRepoNotifications   Operation = "list_repo_notifications"
	OpListGlobalNotifications Operation = "list_global_notifications"
	OpUpdateGlobalInbox       Operation = "update_global_inbox"
	OpGetSingleWebhook        Operation = "get_single_webhook"
	OpUpdateSingleWebhook     Operation = "update_single_webhook"
)

func AllOperations added in v0.138.0

func AllOperations() []Operation

AllOperations 返回种子操作全集(按值升序,每次返回新切片)——消费方 遍历能力矩阵(下游 TestConnection 能力输出等)的权威入口, 单一真源 = opRequirements:SDK 按「只增不改」演进时全集自动跟随, 消费方勿再硬编码种子清单。全集遍历后逐 op 走 DeriveOperationSupport / CheckOperation。

type OperationCapable added in v0.137.0

type OperationCapable interface {
	OperationSupport(op Operation) OperationSupport
}

OperationCapable 是可选能力接口(规则二:新面走可选接口):实现方可 覆盖派生(典型:凭据轴声明)。未实现的 provider 走 DeriveOperationSupport。

type OperationSupport added in v0.137.0

type OperationSupport uint8

OperationSupport 是操作级三态(2B):平台轴与凭据轴分开表示。

const (
	Supported        OperationSupport = iota // 平台支持且未声明凭据限制
	Unsupported                              // 平台不支持——调用必得 ErrNotImplemented
	CredentialDenied                         // 平台支持但当前凭据无权限
)

func DeriveOperationSupport added in v0.137.0

func DeriveOperationSupport(p Provider, op Operation) OperationSupport

DeriveOperationSupport 从既有单一真源推导操作级支持态(2B spec 2.2): OperationCapable 覆盖 > 台账 stub > 门接口缺失 > Supported。 凭据轴静态派生不了——只经 OperationCapable 声明。 全集遍历用 AllOperations。

type Provider

type Provider interface {
	// Platform returns the platform type.
	Platform() model.Platform
	// TestConnection verifies the connection and checks capabilities.
	TestConnection(ctx context.Context) (*model.TestConnectionResult, error)
	// Capabilities statically declares the optional capability interfaces
	// this provider implements. See CapabilitySet.
	Capabilities() CapabilitySet
	// Divergences statically declares this backend's divergence ledger: the
	// registered places where its behavior departs from the unified
	// semantics (stub / ignore / mapping / detour). Consumers can route on
	// these entries — e.g. provider.Ignores — and docs/divergence-ledger.md
	// is generated from them. Like CapabilitySet this is a compile-time
	// declaration; the contract suite locks ledger entries to behavior.
	Divergences() []Divergence

	RepoManager
	ChangeRequestManager
	WebhookManager
	BranchManager
	DiffManager
	CommitManager
	FileManager
	ReleaseManager
}

Provider is the unified interface for all Git hosting platforms. It composes 8 focused sub-interfaces for high cohesion and low coupling.

Consumers can depend on smaller interfaces (e.g., WebhookManager) when they don't need full Provider capabilities.

IssueManager, SearchManager, and CommitStatusManager are NOT part of Provider: only some platforms support them. Consumers that need issues, search, or commit statuses should type-assert against the optional capability interfaces:

if ism, ok := p.(provider.IssueManager); ok { ... }
if sm, ok := p.(provider.SearchManager); ok { ... }
if csm, ok := p.(provider.CommitStatusManager); ok { ... }

Caps declares the same information programmatically: consumers can route
on p.Capabilities() instead of probing with type assertions.

func NewProvider

func NewProvider(cfg Config) (Provider, error)

NewProvider creates a Provider for the given platform using the registry. Returns ErrPlatformNotSupported if the platform is not registered.

Platform backends are registered via init() functions. Import "github.com/yi-nology/go-git-platform/adapter/all" with a blank identifier to register every platform shipped with the SDK.

type ProviderConstructor

type ProviderConstructor func(cfg Config) (Provider, error)

ProviderConstructor is a function that creates a Provider from a Config.

type ProviderError

type ProviderError struct {
	Platform   model.Platform
	Op         string // operation name, e.g., "ListRepos"
	Resource   string // optional resource identifier, e.g., "owner/repo"
	StatusCode int    // 0 when not applicable (e.g. configuration errors)
	// RetryAfter / ResetAt carry the server-advised recovery window when
	// the error is a rate-limit rejection and the platform sent hints
	// (Retry-After header; X-RateLimit-Reset unix seconds). Zero when
	// absent. Copied from the underlying transport error by Wrap; see
	// RateLimitRecovery for the ergonomic accessor.
	RetryAfter time.Duration
	ResetAt    time.Time
	Cause      error // underlying cause; nil when constructed from raw fields
}

ProviderError is a structured error from a provider operation. It carries enough context (platform, op, resource, status code, cause) to support logging, retry, and user-facing messages. It implements errors.Is so the sentinel errors above are matched by Cause, and errors.As for typed access.

func (*ProviderError) Error

func (e *ProviderError) Error() string

Error implements the error interface.

func (*ProviderError) Is

func (e *ProviderError) Is(target error) bool

Is implements errors.Is. It matches when the wrapped Cause equals the target, which lets callers write `errors.Is(err, provider.ErrNotFound)`.

func (*ProviderError) IsClientError

func (e *ProviderError) IsClientError() bool

IsClientError reports 4xx.

func (*ProviderError) IsServerError

func (e *ProviderError) IsServerError() bool

IsServerError reports 5xx.

func (*ProviderError) IsStatus

func (e *ProviderError) IsStatus(code int) bool

IsStatus reports whether the error has the given HTTP status code.

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

Unwrap implements errors.Unwrap.

type ReactionManager

type ReactionManager interface {
	// ListIssueReactions returns all reactions on an issue.
	ListIssueReactions(ctx context.Context, owner, repo, number string) ([]*model.Reaction, error)
	// AddIssueReaction adds a reaction emoji to an issue. emoji is one of
	// the Reaction* constants (e.g. ReactionHeart).
	AddIssueReaction(ctx context.Context, owner, repo, number, emoji string) (*model.Reaction, error)
	// RemoveIssueReaction removes a reaction by its platform ID.
	RemoveIssueReaction(ctx context.Context, owner, repo, number string, reactionID int64) error

	// ListIssueCommentReactions returns all reactions on an issue comment.
	ListIssueCommentReactions(ctx context.Context, owner, repo string, commentID int64) ([]*model.Reaction, error)
	// AddIssueCommentReaction adds a reaction emoji to an issue comment.
	AddIssueCommentReaction(ctx context.Context, owner, repo string, commentID int64, emoji string) (*model.Reaction, error)
	// RemoveIssueCommentReaction removes a reaction by its platform ID.
	RemoveIssueCommentReaction(ctx context.Context, owner, repo string, commentID int64, reactionID int64) error

	// ListCRReactions returns all reactions on a change request (PR/MR).
	ListCRReactions(ctx context.Context, owner, repo, number string) ([]*model.Reaction, error)
	// ListCRCommentReactions returns all reactions on a change-request
	// comment (PR review comment / MR note).
	ListCRCommentReactions(ctx context.Context, owner, repo string, commentID int64) ([]*model.Reaction, error)
	// AddCRCommentReaction adds a reaction emoji to a change-request comment.
	AddCRCommentReaction(ctx context.Context, owner, repo string, commentID int64, emoji string) (*model.Reaction, error)
	// RemoveCRCommentReaction removes a reaction by its platform ID.
	RemoveCRCommentReaction(ctx context.Context, owner, repo string, commentID int64, reactionID int64) error
}

ReactionManager provides emoji reaction CRUD on issues and their comments (both issue comments and change-request comments). It is an optional capability interface: consumers should gate on Provider.Capabilities().Reactions (or type-assert) before use.

Platform support: GitHub, GitLab (issues/CRs via award-emoji; the note-level half is a registered stub family, issue #57), Gitea, Forgejo (PR-level reactions ride the issue endpoints — a PR is an issue sharing the same index). Gitee, GitCode and TencentCode have no reaction API and report Reactions=false in CapabilitySet.

GitLab maps reactions to its "award emoji" API; the SDK normalizes emoji names (e.g. +1 ↔ thumbsup, hooray ↔ tada) so callers use the same constants across all platforms.

type ReleaseAssetManager added in v0.72.0

type ReleaseAssetManager interface {
	// DownloadReleaseAsset 下载 assetID 对应附件并流式写入 w。
	// 非 2xx 响应、传输错误或响应体为空(实际写入 0 字节)时返回错误;
	// 空体错误链可经 errors.Is(err, ErrEmptyResponse) 判定(issue #164)。
	// 注意:合法的 0 字节附件同样命中该错误——需要放行的调用方可先按
	// ReleaseAsset.Size 判定资产本身是否为空。
	DownloadReleaseAsset(ctx context.Context, owner, repo string, assetID int64, w io.Writer) error
}

ReleaseAssetManager 下载 Release 附件。可选能力接口:使用前先看 Provider.Capabilities().ReleaseAssets(或类型断言)。附件可能很大, 因此是流式接口而非返回 []byte,避免整读内存。

type ReleaseManager

type ReleaseManager interface {
	ListTags(ctx context.Context, owner, repo string) ([]*model.TagInfo, error)
	ListReleases(ctx context.Context, owner, repo string) ([]*model.ReleaseInfo, error)
	CreateRelease(ctx context.Context, owner, repo string, opts CreateReleaseOptions) (*model.ReleaseInfo, error)
	GetReleaseByTag(ctx context.Context, owner, repo, tag string) (*model.ReleaseInfo, error)
	UpdateRelease(ctx context.Context, owner, repo, tag string, opts UpdateReleaseOptions) (*model.ReleaseInfo, error)
	DeleteRelease(ctx context.Context, owner, repo, tag string) error
	GetArchive(ctx context.Context, owner, repo, ref, format string) ([]byte, error)
}

ReleaseManager handles tags, releases, and archives. Releases are addressed by tag name across every method: tag names are stable and human-addressable, while the underlying numeric release IDs are not.

type RepoManager

type RepoManager interface {
	ListRepos(ctx context.Context, opts ListRepoOptions) ([]*model.PlatformRepo, error)
	GetRepo(ctx context.Context, owner, repo string) (*model.PlatformRepo, error)
	CreateRepo(ctx context.Context, owner string, opts CreateRepoOptions) (*model.PlatformRepo, error)
	DeleteRepo(ctx context.Context, owner, repo string) error
	UpdateRepo(ctx context.Context, owner, repo string, opts UpdateRepoOptions) (*model.PlatformRepo, error)
	ForkRepo(ctx context.Context, owner, repo string, opts ForkRepoOptions) (*model.PlatformRepo, error)
}

RepoManager handles repository CRUD operations.

type RepoStatsManager

type RepoStatsManager interface {
	// ListForks returns all forks of the repository.
	ListForks(ctx context.Context, owner, repo string) ([]*model.PlatformRepo, error)
	// ListStargazers returns users who have starred the repository.
	ListStargazers(ctx context.Context, owner, repo string) ([]*model.CRUser, error)
	// ListContributors returns contributors ranked by commit count.
	ListContributors(ctx context.Context, owner, repo string) ([]*model.Contributor, error)
}

RepoStatsManager provides read-only repository statistics: forks, stargazers, and contributors. It is an optional capability interface: consumers should gate on Provider.Capabilities().RepoStats (or type-assert) before use.

Not every backend implements every method; backends that lack a specific method return ErrNotImplemented and register the gap in their divergence ledger. A backend declares RepoStats=true if it implements at least one method.

type RequestHook

type RequestHook func(ctx context.Context, req *http.Request) context.Context

RequestHook is called before an HTTP request is sent. It can modify the context (e.g., add tracing headers) or inspect the request.

type ResponseHook

type ResponseHook func(ctx context.Context, req *http.Request, resp *http.Response, duration time.Duration, err error)

ResponseHook is called after an HTTP response is received.

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts (not counting the
	// initial request). <= 0 disables retry.
	MaxRetries int
	// BaseDelay is the initial backoff delay before the first retry.
	BaseDelay time.Duration
	// MaxDelay caps the backoff delay. Zero means 30s (the transport
	// default).
	MaxDelay time.Duration
	// RetryOn lists extra HTTP status codes to retry on, in addition to the
	// transport's default set (429 and 5xx).
	RetryOn []int
}

RetryConfig controls automatic retry behavior for HTTP requests issued by the transport layer. It is the public-facing configuration type passed via provider.Config; the transport package has its own internal transport.RetryConfig that this is mapped into.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a sensible default retry configuration: 3 retries, 500ms base delay, 30s cap, no extra status codes.

type ReviewManager

type ReviewManager interface {
	CreateReview(ctx context.Context, owner, repo, number string, opts CreateReviewOptions) (*model.ReviewResult, error)
	ListReviews(ctx context.Context, owner, repo, number string) ([]model.Review, error)
	GetReview(ctx context.Context, owner, repo, number string, reviewID int64) (*model.Review, error)
	RequestReviewers(ctx context.Context, owner, repo, number string, reviewers []string) error
	DismissReview(ctx context.Context, owner, repo, number string, reviewID int64, message string) error
}

ReviewManager provides code-review operations on change requests. Change request numbers are strings (same addressing scheme as IssueManager); individual reviews are addressed by their numeric platform ID. It is an optional capability: consumers should check Capabilities().Reviews before type-asserting.

type SearchIssuesOptions

type SearchIssuesOptions struct {
	Query   string `json:"q"`
	Repo    string `json:"repo,omitempty"`
	State   string `json:"state,omitempty"`
	Sort    string `json:"sort,omitempty"`
	Order   string `json:"order,omitempty"`
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
}

SearchIssuesOptions contains options for searching issues.

type SearchManager

type SearchManager interface {
	SearchRepos(ctx context.Context, opts SearchReposOptions) ([]*model.SearchRepoResult, *int, error)
	SearchIssues(ctx context.Context, opts SearchIssuesOptions) ([]*model.SearchIssueResult, *int, error)
	SearchUsers(ctx context.Context, opts SearchUsersOptions) ([]*model.SearchUserResult, *int, error)
}

SearchManager provides cross-platform search for repositories, issues, and users.

The *int return is the server-side total when the platform reports one, and nil when it does not — callers must not treat a total as guaranteed.

type SearchReposOptions

type SearchReposOptions struct {
	Query   string `json:"q"`
	Sort    string `json:"sort,omitempty"`
	Order   string `json:"order,omitempty"`
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
}

SearchReposOptions contains options for searching repositories.

Sort and Order are platform-dependent: each backend forwards them to its platform's own vocabulary (e.g. GitHub's stars/forks/updated with asc/desc), so values valid on one platform may be ignored or rejected on another (gitea/forgejo reject unknown sort/order values with HTTP 422; gitlab's search API exposes no sort/order at all — a registered ignore). Consult the target platform's search documentation for the accepted values.

type SearchUsersOptions

type SearchUsersOptions struct {
	Query   string `json:"q"`
	Sort    string `json:"sort,omitempty"`
	Order   string `json:"order,omitempty"`
	Page    int    `json:"page,omitempty"`
	PerPage int    `json:"per_page,omitempty"`
}

SearchUsersOptions contains options for searching users.

type StarredManager added in v0.72.0

type StarredManager interface {
	// ListStarred 分页列出认证用户 star 的仓库(GET /user/starred)。
	// page/perPage 语义与其他分页方法一致,非法值经 NormalizePageOpts 归一。
	ListStarred(ctx context.Context, page, perPage int) ([]*model.PlatformRepo, error)
}

StarredManager 列出认证用户 star 过的仓库。可选能力接口:使用前先看 Provider.Capabilities().Starred(或类型断言)。

直接复用 PlatformRepo 而非再造摘要类型:下游导入/org 镜像场景只消费 FullName/Name/Owner/CloneURL/Description/Archived/Fork/Stars/Language/ Private 这些现成字段,再造一套会引入无谓的字段映射漂移。GitHub 专属 (无跨平台抽象价值),故仅 github 后端实现。

type StatusError

type StatusError struct {
	Status int
	Cause  error
}

StatusError wraps an error with an explicit HTTP status code. Use this in platform backends when you need to attach a status code to an error from a third-party SDK that doesn't implement the statusCoder interface. This avoids the need for the reflection-based fallback in Wrap.

Example:

err := someSDK.DoSomething()
if err != nil {
    return provider.WrapStatusError(err, 404)
}

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) StatusCode

func (e *StatusError) StatusCode() int

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

type StatusExtractor added in v0.83.0

type StatusExtractor func(err error) (int, bool)

StatusExtractor reports the HTTP status carried by one of a platform's SDK error types. It is called per link of the chain Wrap walks, so the extractor only needs to handle its own error values (the chain walk handles wrapping).

type TeamReviewManager added in v0.125.0

type TeamReviewManager interface {
	// RequestTeamReviewers requests review from the given team slugs. Team
	// slugs are namespace-free ("platform-team", not "org/platform-team")
	// on every platform that serves this capability. The call is additive:
	// existing user review requests are left untouched, mirroring
	// ReviewManager.RequestReviewers.
	RequestTeamReviewers(ctx context.Context, owner, repo, number string, teams []string) error
}

TeamReviewManager requests team review requests on change requests. It is an optional capability (issue #79): the unified ReviewManager only carries user logins, while GitHub/Gitea/Forgejo expose a separate team_reviewers wire channel — organizations that gate on CODEOWNERS-driven team review had to bypass the SDK for it. Consumers should check Capabilities().TeamReviews (or type-assert) before use.

Backends whose platform has no team-review wire channel simply do not implement the interface (TeamReviews stays false); there is deliberately no stub: the capability gate is the discovery mechanism, mirroring the other optional-manager families.

type TemplateRepoManager added in v0.106.0

type TemplateRepoManager interface {
	// CreateRepoFromTemplate generates a new repository owned by
	// opts.Owner (empty = the authenticated user) from the template
	// templateOwner/templateRepo.
	CreateRepoFromTemplate(ctx context.Context, templateOwner, templateRepo string, opts CreateRepoFromTemplateOptions) (*model.PlatformRepo, error)
}

TemplateRepoManager instantiates a repository from a platform template repository. Optional capability interface: check Capabilities().RepoTemplates before use (GitHub + Gitea).

type ThrottleClassifier added in v0.125.0

type ThrottleClassifier func(err error) (retryAfter time.Duration, resetAt time.Time, throttled bool)

ThrottleClassifier reports whether one of the platform's SDK error values is an authoritative throttle verdict (issue #50), optionally carrying the server-advised recovery window. It is the SDK-error-path counterpart of rateLimitedMarker: SDK error types (go-github's *RateLimitError — always HTTP 403 with the primary quota exhausted — and *AbuseRateLimitError for secondary limits) implement neither StatusCode() int nor IsRateLimited(), so Wrap's status classification alone would drop them into ErrForbidden. retryAfter/resetAt mirror ProviderError's recovery fields (zero values when the platform sent no hint).

type TokenSource added in v0.72.0

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

TokenSource supplies the access token used to authenticate platform API requests. When a Config.TokenSource is set, the transport layer consults it on every request, so rotating or expiring credentials — OAuth device-flow tokens, GitHub App installation tokens (hourly expiry), short-lived CI job tokens — take effect on the next request without rebuilding the provider.

The interface is deliberately identical to transport.TokenSource, so any implementation satisfies both and backends can forward the value unchanged. Implementations must be safe for concurrent use.

func StaticTokenSource added in v0.72.0

func StaticTokenSource(token string) TokenSource

StaticTokenSource returns a TokenSource that always returns token; it is the TokenSource equivalent of Config.Token and mostly useful for tests and for swapping a static credential into TokenSource-taking code paths.

type UpdateBranchProtectionOptions

type UpdateBranchProtectionOptions struct {
	RequiredApprovingReviews *int  `json:"required_approving_reviews,omitempty"`
	RequiredStatusChecks     *bool `json:"required_status_checks,omitempty"`
	AllowForcePushes         *bool `json:"allow_force_pushes,omitempty"`
	AllowDeletions           *bool `json:"allow_deletions,omitempty"`
}

UpdateBranchProtectionOptions contains options for updating a branch protection rule. Nil fields are left unchanged.

type UpdateCROptions

type UpdateCROptions struct {
	Title string `json:"title,omitempty"`
	// DescriptionPatch 三态描述(2A):nil = 不动;非 nil = 全量替换,"" = 清空。
	// 与 Description 同设时本字段优先。平台无法表达清空(A/B 矩阵 B 级)时
	// UpdateCR 返回 ErrClearNotSupported。
	DescriptionPatch *string `json:"description_patch,omitempty"`
	// AssigneesPatch 三态指派人:nil = 不动;非 nil = 全量替换,
	// 空切片 = 清空。语义同 DescriptionPatch。
	AssigneesPatch *[]string `json:"assignees_patch,omitempty"`
	//
	// 三态(2A 起):清空/置空用 DescriptionPatch(见上);本字段语义不变
	// (空 = 不动),保留为兼容路径——MCP 工具「参数未提供 = 不变」
	// 即此语义。
	Description  string `json:"description,omitempty"`
	TargetBranch string `json:"target_branch,omitempty"`
	// Assignees 全量替换 CR 指派人(logins;后端按平台词表解析为 ID/单值线)。
	// 空(nil 或空切片)= 指派人不变。**清空不可表达**——与
	// UpdateIssueOptions.Assignees 同款口径(len>0 才落线)。
	//
	// 三态(2A 起):清空/置空用 AssigneesPatch(见上);本字段语义不变
	// (空 = 不动),保留为兼容路径——MCP 工具「参数未提供 = 不变」
	// 即此语义。
	Assignees []string `json:"assignees,omitempty"`
}

UpdateCROptions contains options for updating a change request.

func (UpdateCROptions) ResolveAssignees added in v0.135.0

func (o UpdateCROptions) ResolveAssignees() ([]string, bool)

func (UpdateCROptions) ResolveDescription added in v0.135.0

func (o UpdateCROptions) ResolveDescription() (string, bool)

type UpdateIssueOptions

type UpdateIssueOptions struct {
	Title string `json:"title,omitempty"`
	// BodyPatch 三态正文(2A):nil = 不动;非 nil = 全量替换,"" = 清空。
	// 与 Body 同设时本字段优先。平台无法表达清空(A/B 矩阵 B 级)时
	// UpdateIssue 返回 ErrClearNotSupported。
	BodyPatch *string `json:"body_patch,omitempty"`
	// AssigneesPatch 三态指派人:nil = 不动;非 nil = 全量替换,
	// 空切片 = 清空。语义同 BodyPatch。
	AssigneesPatch *[]string `json:"assignees_patch,omitempty"`
	// LabelsPatch 三态标签:nil = 不动;非 nil = 全量替换,空 = 清空。
	LabelsPatch *[]string `json:"labels_patch,omitempty"`
	// MilestonePatch 三态里程碑:nil = 不动;非 nil = 全量替换,
	// "" = 清空(各平台映射 null/0,见能力矩阵)。
	MilestonePatch *string `json:"milestone_patch,omitempty"`
	//
	// 三态(2A 起):清空/置空用 BodyPatch(见上);本字段语义不变
	// (空 = 不动),保留为兼容路径——MCP 工具「参数未提供 = 不变」
	// 即此语义。
	Body  string           `json:"body,omitempty"`
	State model.IssueState `json:"state,omitempty"`
	//
	// 三态(2A 起):清空/置空用 AssigneesPatch(见上);本字段语义不变
	// (空 = 不动),保留为兼容路径——MCP 工具「参数未提供 = 不变」
	// 即此语义。
	Assignees []string `json:"assignees,omitempty"`
	//
	// 三态(2A 起):清空/置空用 LabelsPatch(见上);本字段语义不变
	// (空 = 不动),保留为兼容路径——MCP 工具「参数未提供 = 不变」
	// 即此语义。
	Labels []string `json:"labels,omitempty"`
	// milestone number/ID as a string; "" = leave unchanged
	//
	// 三态(2A 起):清空/置空用 MilestonePatch(见上);本字段语义不变
	// (空 = 不动),保留为兼容路径——MCP 工具「参数未提供 = 不变」
	// 即此语义。
	Milestone string `json:"milestone,omitempty"`
}

UpdateIssueOptions contains options for updating an issue.

func (UpdateIssueOptions) ResolveAssignees added in v0.135.0

func (o UpdateIssueOptions) ResolveAssignees() ([]string, bool)

func (UpdateIssueOptions) ResolveBody added in v0.135.0

func (o UpdateIssueOptions) ResolveBody() (string, bool)

func (UpdateIssueOptions) ResolveLabels added in v0.135.0

func (o UpdateIssueOptions) ResolveLabels() ([]string, bool)

func (UpdateIssueOptions) ResolveMilestone added in v0.135.0

func (o UpdateIssueOptions) ResolveMilestone() (string, bool)

type UpdateLabelOptions

type UpdateLabelOptions struct {
	NewName     *string `json:"new_name,omitempty"`
	Color       *string `json:"color,omitempty"`
	Description *string `json:"description,omitempty"`
}

UpdateLabelOptions contains options for updating a repository label. Nil fields are left unchanged.

type UpdateMilestoneOptions

type UpdateMilestoneOptions struct {
	Title       *string              `json:"title,omitempty"`
	Description *string              `json:"description,omitempty"`
	State       model.MilestoneState `json:"state,omitempty"`
	DueOn       *time.Time           `json:"due_on,omitempty"`
}

UpdateMilestoneOptions contains options for updating a repository milestone. Nil fields are left unchanged.

type UpdateReleaseOptions

type UpdateReleaseOptions struct {
	Name       *string `json:"name,omitempty"`
	Body       *string `json:"body,omitempty"`
	Draft      *bool   `json:"draft,omitempty"`
	Prerelease *bool   `json:"prerelease,omitempty"`
}

UpdateReleaseOptions contains options for updating a release addressed by tag. Nil fields are left unchanged.

type UpdateRepoOptions

type UpdateRepoOptions struct {
	Name          string `json:"name,omitempty"`
	Description   string `json:"description,omitempty"`
	DefaultBranch string `json:"default_branch,omitempty"`
	Private       *bool  `json:"private,omitempty"`
}

UpdateRepoOptions contains options for updating a repository.

type UpdateWebhookOptions added in v0.99.9

type UpdateWebhookOptions struct {
	URL    *string  `json:"url,omitempty"`
	Secret *string  `json:"secret,omitempty"`
	Events []string `json:"events,omitempty"`
}

UpdateWebhookOptions contains options for updating a webhook (patch-style: nil fields are left unchanged). Events is the exception — see WebhookConfigManager for the full-replacement semantics.

type UserManager

type UserManager interface {
	// GetUser returns the user profile for the given username.
	GetUser(ctx context.Context, username string) (*model.CRUser, error)

	// ResolveUsernames maps a list of usernames to their platform IDs.
	// The returned slice preserves input order; each entry's ID field
	// carries the resolved numeric ID. If a username cannot be resolved,
	// an error is returned for that entry (the partial result up to that
	// point is still valid).
	ResolveUsernames(ctx context.Context, usernames []string) ([]*model.CRUser, error)
}

UserManager provides user lookup and username-to-ID resolution. It is an optional capability interface: consumers should gate on Provider.Capabilities().Users (or type-assert) before use.

Not every backend needs this — GitHub, Gitea, Forgejo, Gitee, and GitCode accept usernames directly in their APIs. GitLab and TencentCode require numeric user IDs for assignees and reviewers, so they implement this interface to expose their resolution logic.

Consumers can also use this interface to look up user profiles or validate that a username exists before passing it to other operations.

type WebhookConfigManager added in v0.99.9

type WebhookConfigManager interface {
	// GetWebhook returns one webhook by its platform ID.
	GetWebhook(ctx context.Context, owner, repo string, webhookID int64) (*model.PlatformWebhook, error)
	// UpdateWebhook patches one webhook. Nil URL/Secret leave the
	// corresponding setting untouched; a nil Events slice leaves the event
	// set untouched while a non-nil one replaces it wholesale.
	UpdateWebhook(ctx context.Context, owner, repo string, webhookID int64, opts UpdateWebhookOptions) (*model.PlatformWebhook, error)
}

WebhookConfigManager provides single-webhook read and update on top of the core WebhookManager. It is an optional capability interface: consumers should gate on Provider.Capabilities().WebhookConfig (or type-assert) before use.

Platform support: all seven backends (GitHub, GitLab, Gitee, GitCode, Gitea, Forgejo, TencentCode). Update is patch-style — nil fields are left unchanged — with one documented exception: a non-nil Events slice always replaces the full event set (an empty slice clears every event), because event membership cannot be expressed incrementally on the platforms whose webhooks are boolean-flag based (GitLab/Gitee/TencentCode). The secret is write-only on every platform: GetWebhook never returns it.

type WebhookManager

type WebhookManager interface {
	CreateWebhook(ctx context.Context, opts CreateWebhookOptions) (*model.PlatformWebhook, error)
	DeleteWebhook(ctx context.Context, owner, repo string, webhookID int64) error
	ListWebhooks(ctx context.Context, owner, repo string) ([]*model.PlatformWebhook, error)
	ParseWebhookEvent(r *http.Request, secret string) (*model.NormalizedEvent, error)
	ValidateWebhookSignature(r *http.Request, secret string) error
}

WebhookManager handles webhook CRUD and event parsing.

Jump to

Keyboard shortcuts

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