github

package
v1.24.3 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GitSshProtocolType   = "ssh"
	GitHttpsProtocolType = "https"
)

Variables

View Source
var (
	ErrGitHubCliNotLoggedIn = errors.New("gh cli is not logged in")
	ErrUserNotAuthorized    = errors.New("user is not authorized. " +
		"Try running gh auth refresh with the required scopes to request additional authorization")
	ErrRepositoryNameInUse = errors.New("repository name already in use")

	// The hostname of the public GitHub service.
	GitHubHostName = "github.com"

	// Environment variable that gh cli uses for auth token overrides
	TokenEnvVars = []string{"GITHUB_TOKEN", "GH_TOKEN"}
)
View Source
var Version semver.Version = semver.MustParse("2.92.0")

Version is the minimum version of GitHub cli that we require (and the one we fetch when we fetch gh on behalf of a user).

Functions

func BuildOIDCSubject added in v1.24.3

func BuildOIDCSubject(
	repoSlug string,
	repoInfo *RepoInfo,
	oidcConfig *OIDCSubjectConfig,
	suffix string,
) (string, error)

BuildOIDCSubject constructs the correct OIDC subject claim string for a federated identity credential based on the OIDC customization config.

This is a pure function — all needed data (repo info, config) must be pre-fetched. The suffix is the trailing part of the subject, e.g. "ref:refs/heads/main" or "pull_request".

If oidcConfig is nil or UseDefault is true, the default GitHub format is used:

repo:{owner}/{repo}:{suffix}

For custom configs, claim keys are mapped to values and joined with the suffix. Unknown claim keys cause an error so the user knows azd needs updating.

func RunningOnCodespaces

func RunningOnCodespaces() bool

RunningOnCodespaces check if the application is running on codespaces.

Types

type ApiCallOptions

type ApiCallOptions struct {
	Headers []string
}

ApiCallOptions represent the options for the ApiCall method.

type ApiError added in v1.24.3

type ApiError struct {
	// URL is the API URL that was requested (e.g., "https://api.github.com/repos/o/r/branches/main").
	URL string
	// Kind classifies the failure (SAML vs. rate-limit vs. plain 4xx etc.).
	Kind ApiErrorKind
	// StatusCode is the HTTP status code returned by the GitHub API (e.g., 401, 403, 404).
	// It is 0 when no status code could be parsed (e.g., gh failed before issuing the request).
	StatusCode int
	// Message is the human-readable message GitHub returned in the JSON
	// error body (e.g., "Resource protected by organization SAML enforcement.").
	// Empty when the failure was not an HTTP-level error (e.g., gh not installed).
	Message string
	// Stderr is the raw stderr output from `gh api`, kept for diagnostics.
	Stderr string
	// Underlying is the original error from the command runner (typically *exec.ExitError).
	Underlying error
}

ApiError represents a structured error returned from a `gh api` invocation.

It is built from the underlying gh CLI output (the JSON body that GitHub's REST API writes to stdout on errors, plus the human-readable stderr) so callers can branch on the failure mode without doing brittle substring matching against opaque error strings.

Use Kind for switch-based dispatch and the IsAuthError / IsNotFound predicates for common boolean checks.

func (*ApiError) Error added in v1.24.3

func (e *ApiError) Error() string

Error implements the error interface.

func (*ApiError) IsAuthError added in v1.24.3

func (e *ApiError) IsAuthError() bool

IsAuthError reports whether the error indicates an authentication or authorization failure (401, 403, or SAML enforcement).

func (*ApiError) IsNotFound added in v1.24.3

func (e *ApiError) IsNotFound() bool

IsNotFound reports whether the API returned 404.

func (*ApiError) Unwrap added in v1.24.3

func (e *ApiError) Unwrap() error

Unwrap exposes the underlying command-runner error so errors.Is/errors.As continue to work against the original error chain.

type ApiErrorKind added in v1.24.3

type ApiErrorKind int

ApiErrorKind classifies the cause of a `gh api` failure. A single error has exactly one Kind. Use the predicate methods on *ApiError (IsAuthError, IsNotFound) for boolean checks; switch on Kind when you need to distinguish SAML vs. plain auth vs. rate-limit.

const (
	// KindUnknown indicates the failure couldn't be classified — typically
	// because gh failed before issuing the request (network error, missing
	// binary, ctx cancelled) and there's no HTTP status to inspect.
	KindUnknown ApiErrorKind = iota
	// KindSAMLBlocked indicates the owning organization enforces SAML SSO
	// and the caller's token has not been authorized for it. Resolution
	// requires an out-of-band step in the GitHub UI; `gh auth login` alone
	// does not fix it.
	KindSAMLBlocked
	// KindRateLimited indicates GitHub rejected the request because rate
	// limits were exceeded. Authenticated requests have higher limits.
	KindRateLimited
	// KindUnauthorized indicates HTTP 401 — the request was unauthenticated
	// or the token is invalid/expired.
	KindUnauthorized
	// KindForbidden indicates HTTP 403 that is NOT SAML or rate-limit
	// related — typically missing token scopes or a permission denial.
	KindForbidden
	// KindNotFound indicates HTTP 404 — the resource doesn't exist OR is
	// private and the caller isn't authorized to know it exists.
	KindNotFound
	// KindServerError indicates a 5xx response from GitHub.
	KindServerError
	// KindOther indicates a classified non-2xx response that doesn't match
	// any of the more specific kinds above (e.g., 4xx codes other than
	// 401/403/404, or rare status codes outside the standard buckets). Has
	// a known StatusCode but no targeted suggestion is provided.
	KindOther
)

func (ApiErrorKind) String added in v1.24.3

func (k ApiErrorKind) String() string

String returns a human-readable name for the kind, used in error messages.

type AuthStatus

type AuthStatus struct {
	LoggedIn bool
}

The result from calling GetAuthStatus

type Cli

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

func NewGitHubCli

func NewGitHubCli(console input.Console, commandRunner exec.CommandRunner) *Cli

NewGitHubCli creates a new GitHub CLI wrapper. The CLI is not yet installed; call EnsureInstalled before using methods that require the gh binary.

func (*Cli) ApiCall

func (cli *Cli) ApiCall(ctx context.Context, hostname, path string, options ApiCallOptions) (string, error)

ApiCall uses gh cli to call https://api.<hostname>/<path>.

func (*Cli) BinaryPath

func (cli *Cli) BinaryPath() string

func (*Cli) CheckInstalled

func (cli *Cli) CheckInstalled(ctx context.Context) error

func (*Cli) CreateEnvironmentIfNotExist

func (cli *Cli) CreateEnvironmentIfNotExist(ctx context.Context, repoName string, envName string) error

func (*Cli) CreatePrivateRepository

func (cli *Cli) CreatePrivateRepository(ctx context.Context, name string) error

func (*Cli) DeleteEnvironment

func (cli *Cli) DeleteEnvironment(ctx context.Context, repoName string, envName string) error

func (*Cli) DeleteSecret

func (cli *Cli) DeleteSecret(ctx context.Context, repoSlug string, name string) error

func (*Cli) DeleteVariable

func (cli *Cli) DeleteVariable(ctx context.Context, repoSlug string, name string) error

func (*Cli) EnsureInstalled

func (cli *Cli) EnsureInstalled(ctx context.Context) error

EnsureInstalled checks if GitHub CLI is available and downloads/upgrades if needed. This is safe to call multiple times; successful installation is cached and failed attempts are retried. Should be called with a request-scoped context before first use.

func (*Cli) GetAuthStatus

func (cli *Cli) GetAuthStatus(ctx context.Context, hostname string) (AuthStatus, error)

func (*Cli) GetGitProtocolType

func (cli *Cli) GetGitProtocolType(ctx context.Context) (string, error)

func (*Cli) GetOIDCSubjectConfig added in v1.24.3

func (cli *Cli) GetOIDCSubjectConfig(
	ctx context.Context, repoSlug string,
) (*OIDCSubjectConfig, error)

GetOIDCSubjectConfig queries the GitHub OIDC customization API for a repository. It checks the repo-level customization endpoint. If the repo returns a valid response (even with UseDefault=true), it is returned as-is.

A repo-level 404 means the repository has not opted in to custom OIDC subjects. Per GitHub's docs, repos that haven't opted in receive default-format tokens regardless of any org-level template, so we return the default config directly without checking the org endpoint.

func (*Cli) GetRepoInfo added in v1.24.3

func (cli *Cli) GetRepoInfo(
	ctx context.Context, repoSlug string,
) (*RepoInfo, error)

GetRepoInfo queries the GitHub API for repository metadata (IDs) needed to construct OIDC subjects with custom claim keys like repository_owner_id.

func (*Cli) GitHubActionsExists

func (cli *Cli) GitHubActionsExists(ctx context.Context, repoSlug string) (bool, error)

GitHubActionsExists gets the information from upstream about the workflows and return true if there is at least one workflow in the repo.

func (*Cli) InstallUrl

func (cli *Cli) InstallUrl() string

func (*Cli) ListRepositories

func (cli *Cli) ListRepositories(ctx context.Context) ([]GhCliRepository, error)

func (*Cli) ListSecrets

func (cli *Cli) ListSecrets(ctx context.Context, repoSlug string) ([]string, error)

func (*Cli) ListVariables

func (cli *Cli) ListVariables(
	ctx context.Context,
	repoSlug string,
	options *ListVariablesOptions,
) (map[string]string, error)

func (*Cli) Login

func (cli *Cli) Login(ctx context.Context, hostname string) error

func (*Cli) Name

func (cli *Cli) Name() string

func (*Cli) SetSecret

func (cli *Cli) SetSecret(ctx context.Context, repoSlug string, name string, value string) error

func (*Cli) SetVariable

func (cli *Cli) SetVariable(
	ctx context.Context,
	repoSlug string,
	name string,
	value string,
	options *SetVariableOptions,
) error

func (*Cli) ViewRepository

func (cli *Cli) ViewRepository(ctx context.Context, name string) (GhCliRepository, error)

type GhCliRepository

type GhCliRepository struct {
	// The slug for a repository (formatted as "<owner>/<name>")
	NameWithOwner string
	// The Url for the HTTPS endpoint for the repository
	HttpsUrl string `json:"url"`
	// The Url for the SSH endpoint for the repository
	SshUrl string
}

type GitHubActionsResponse

type GitHubActionsResponse struct {
	TotalCount int `json:"total_count"`
}

type ListVariablesOptions

type ListVariablesOptions struct {
	Environment string
}

type OIDCSubjectConfig added in v1.24.3

type OIDCSubjectConfig struct {
	UseDefault       bool     `json:"use_default"`
	IncludeClaimKeys []string `json:"include_claim_keys"`
}

OIDCSubjectConfig represents the OIDC subject claim customization returned by the GitHub Actions OIDC customization API.

type RepoInfo added in v1.24.3

type RepoInfo struct {
	ID    int64 `json:"id"`
	Owner struct {
		ID int64 `json:"id"`
	} `json:"owner"`
}

RepoInfo holds GitHub API repository metadata needed for OIDC subject construction.

type SetVariableOptions

type SetVariableOptions struct {
	Environment string
}

Jump to

Keyboard shortcuts

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