github

package
v1.233.0-rc.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Overview

Package github provides GitHub Actions CI provider implementation.

Index

Constants

View Source
const (
	// ProviderName is the name of the GitHub Actions provider.
	ProviderName = "github-actions"
)

Variables

View Source
var ErrEventPathNotSet = fmt.Errorf("GITHUB_EVENT_PATH is not set")

ErrEventPathNotSet is returned when $GITHUB_EVENT_PATH is not set.

View Source
var ErrNoMergeCommitSHA = fmt.Errorf("event payload has no pull_request.merge_commit_sha")

ErrNoMergeCommitSHA is returned when a merged PR's event payload lacks pull_request.merge_commit_sha, so no merge-commit-anchored base can be computed.

View Source
var ErrNoParentCommit = fmt.Errorf("HEAD has no parents (initial commit)")

ErrNoParentCommit is returned when HEAD has no parents (initial commit).

View Source
var ErrNoPayloadBaseSHA = fmt.Errorf("event payload has no pull_request.base.sha")

ErrNoPayloadBaseSHA is returned when a fast-forward-merged PR's event payload lacks pull_request.base.sha, so no payload-base-anchored base can be computed.

Functions

func LegacyActionRepo added in v1.228.0

func LegacyActionRepo() (repo string, ok bool)

LegacyActionRepo reports the owner/repo of the currently executing GitHub Action when it is one of the deprecated marketplace actions predating Native CI. GitHub Actions sets GITHUB_ACTION_REPOSITORY for the step currently running, including a composite action's own nested run: steps, so this also detects atmos invoked from inside such an action.

func ValidateAPIURL

func ValidateAPIURL() error

ValidateAPIURL checks the API base URL from ATMOS_CI_GITHUB_API_URL or GITHUB_API_URL without needing a token, so a misconfigured runner fails before any request is built. It returns nil when neither variable is set.

Types

type Client

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

Client wraps the GitHub API client.

func NewClient

func NewClient() (*Client, error)

NewClient creates a new GitHub API client. Token precedence: ATMOS_CI_GITHUB_TOKEN > ATMOS_PRO_GITHUB_TOKEN > GITHUB_TOKEN > GH_TOKEN. ATMOS_CI_GITHUB_TOKEN allows using a separate token for CI operations (e.g., commit statuses) while GITHUB_TOKEN is used by Terraform. ATMOS_PRO_GITHUB_TOKEN is a JIT GitHub App installation token brokered by Atmos Pro's github/sts auth integration (see pkg/auth/integrations/github); unlike GITHUB_TOKEN, pushes/PRs authenticated with it trigger downstream GitHub Actions workflows, since it isn't subject to GitHub's anti-recursion restriction on the default Actions token.

API base URL precedence: ATMOS_CI_GITHUB_API_URL (explicit override) > GITHUB_API_URL (exported natively by GitHub Actions, and set to the enterprise API URL on GitHub Enterprise Server runners) > the public https://api.github.com default. An unparsable value returns an error wrapping ErrInvalidURL rather than silently sending the token to the wrong host.

func NewClientWithHTTPClient

func NewClientWithHTTPClient(httpClient *http.Client) *Client

NewClientWithHTTPClient creates a new GitHub API client with a custom HTTP client. Useful for testing.

func NewClientWithToken

func NewClientWithToken(token string) *Client

NewClientWithToken creates a new GitHub API client with the given token.

func (*Client) GitHub

func (c *Client) GitHub() *github.Client

GitHub returns the underlying go-github client.

type Provider

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

Provider implements provider.Provider for GitHub Actions. The client is lazily initialized on first use, so the provider can be registered at init time based on environment detection alone, without requiring GITHUB_TOKEN to be available at startup.

func NewProvider

func NewProvider() *Provider

NewProvider creates a new GitHub Actions provider. The GitHub API client is lazily initialized on first use.

func NewProviderWithClient

func NewProviderWithClient(client *Client) *Provider

NewProviderWithClient creates a new GitHub Actions provider with a custom client.

func (*Provider) AddPath

func (p *Provider) AddPath(dir string) error

AddPath appends dir to the file named by GITHUB_PATH so later workflow steps find executables in it. It returns an error when GITHUB_PATH is not set.

func (*Provider) Annotate added in v1.222.0

func (p *Provider) Annotate(annotations []provider.Annotation) error

Annotate implements provider.Annotator by emitting one GitHub Actions workflow annotation command per finding. GitHub renders these inline on the pull request diff (and in the run's annotations list) — the "non-CodeQL" path that needs no GitHub Advanced Security.

Workflow commands are written to stderr (the UI channel) via pkg/ui, NOT to stdout (the data channel). The GitHub Actions runner parses workflow commands from the step's combined log stream, which captures both stdout and stderr, so annotations still render when written to stderr. Writing them to stdout would corrupt the structured data (JSON/YAML) that downstream consumers read from stdout — for example, legacy actions like cloudposse/github-action-atmos-get-settings capture the stdout of `atmos describe ...` and parse it as JSON, which fails on a stray `::warning ...` line. See issue #3309 and docs/fixes/2026-10-07-ci-legacy-action-stdout-pollution.md.

Unlike log-group markers — whose `::group::`/`::endgroup::` must bracket stdout content and therefore cannot move to stderr (the runner does not guarantee ordering across the two streams) — annotations are standalone and render correctly from stderr. Writes go through pkg/ui, which routes to stderr with secret masking and logs (does not return) any write failure, matching the fire-and-forget contract of every other UI-channel write in Atmos; a dropped diagnostic annotation is never worth failing the command.

func (*Provider) Cache added in v1.222.0

func (p *Provider) Cache() (cache.Backend, error)

Cache implements the provider.CacheProvider capability for GitHub Actions. It returns the GitHub Actions cache backend, or an error wrapping errUtils.ErrCacheUnavailable (from githubcache.NewBackend) when not running inside a runner (the runtime cache token/URL are absent).

func (*Provider) Context

func (p *Provider) Context() (*provider.Context, error)

Context returns CI metadata from GitHub Actions environment variables.

SHA is the commit that is actually checked out: git HEAD of the working directory, falling back to GITHUB_SHA when HEAD cannot be read. Commit statuses and commit comments land on it. By default that equals GITHUB_SHA (the merge commit for pull_request events); a workflow that checks out the pull request head (for example under pull_request_target) gets the head commit, which is the commit a reviewer sees. Tests that need GITHUB_SHA to win run outside a git checkout.

The pull request number comes from the event payload (pull_request.number, or workflow_run.pull_requests[0].number), because GitHub sets GITHUB_REF to the base branch for pull_request_target and workflow_run. GITHUB_REF is the fallback. A pull request is a fork when its head repository's full name differs from the base repository's; a deleted fork or an unreadable payload counts as a fork.

func (*Provider) CreateCheckRun

func (p *Provider) CreateCheckRun(ctx context.Context, opts *provider.CreateCheckRunOptions) (*provider.CheckRun, error)

CreateCheckRun creates a new commit status on a commit.

GitHub commit statuses have four states (pending, success, failure, error), so the check run states map as: pending and in_progress become pending; success stays success; failure stays failure; error and cancelled become error. The returned CheckRun keeps the requested state and the details URL.

func (*Provider) Detect

func (p *Provider) Detect() bool

Detect returns true if running in GitHub Actions.

func (*Provider) EndLogGroup added in v1.223.0

func (p *Provider) EndLogGroup() error

EndLogGroup emits a GitHub Actions workflow command that closes the current collapsible log group.

func (*Provider) GetStatus

func (p *Provider) GetStatus(ctx context.Context, opts provider.StatusOptions) (*provider.Status, error)

GetStatus returns the CI status for the current branch.

func (*Provider) IsDebugMode added in v1.220.0

func (p *Provider) IsDebugMode() bool

IsDebugMode reports whether the current GitHub Actions run has runner-level or step-level debug logging enabled. Satisfies the optional provider.DebugModeDetector interface so generic callers can auto-promote their log level without depending on GitHub-specific environment variables.

Returns true when at least one of the documented debug toggles is set to the literal string "true":

  • ACTIONS_RUNNER_DEBUG — runner diagnostic logging.
  • ACTIONS_STEP_DEBUG — step debug logging.

GITHUB_ACTIONS is also required to be "true" so the method behaves safely when invoked outside of a real GHA environment (e.g., direct unit tests). In production this is redundant — the provider only registers itself when GITHUB_ACTIONS=true (see provider.go).

Reference: https://docs.github.com/actions/how-tos/manage-workflow-runs/enable-debug-logging.

func (*Provider) MaskValue

func (p *Provider) MaskValue(value string) error

MaskValue registers value with the runner's log masker by emitting the ::add-mask:: workflow command. Workflow commands are written to stderr because the runner parses them from the step log stream and stdout is reserved for data. The command is written unmasked: Atmos has already registered the value with its own masker, which would otherwise replace the payload with its placeholder and leave the runner masking nothing. An empty value is ignored since masking the empty string is meaningless.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name.

func (*Provider) OutputWriter

func (p *Provider) OutputWriter() provider.OutputWriter

OutputWriter returns an OutputWriter for GitHub Actions.

func (*Provider) PostComment added in v1.218.0

func (p *Provider) PostComment(ctx context.Context, opts *provider.PostCommentOptions) (*provider.Comment, error)

PostComment creates or upserts a PR comment using the GitHub Issues API. PR comments on GitHub are issue comments on the PR's underlying issue.

Behavior semantics:

  • CommentBehaviorCreate: always CreateComment.
  • CommentBehaviorUpdate: find by marker, EditComment; ErrCICommentNotFound if absent.
  • CommentBehaviorUpsert (default): find by marker, EditComment if found, else CreateComment.

func (*Provider) PostCommitComment

func (p *Provider) PostCommitComment(ctx context.Context, opts *provider.PostCommitCommentOptions) (*provider.Comment, error)

PostCommitComment creates or upserts a comment on a commit using the GitHub commit comments API (POST /repos/{owner}/{repo}/commits/{sha}/comments). It is how a run with no pull request, such as a push, reports where a pull request comment would otherwise land. Behavior semantics match PostComment: create always posts, update requires a marker match, and upsert edits a match or creates one.

func (*Provider) ReportSARIF added in v1.222.0

func (p *Provider) ReportSARIF(ctx context.Context, report provider.SARIFReport) error

ReportSARIF implements provider.SARIFReporter by uploading the raw SARIF to GitHub Code Scanning (the Security tab). Requires GitHub Advanced Security on private repos and a token with the `security_events` write scope. The report Category is stamped into each run's automationDetails.id so multiple uploads for the same commit are tracked as distinct analyses.

func (*Provider) ResolveBase added in v1.214.0

func (p *Provider) ResolveBase() (*provider.BaseResolution, error)

ResolveBase returns the base commit for affected detection in GitHub Actions. It reads GitHub Actions environment variables and event payloads to determine the appropriate base commit for the current event type.

Callers running in container jobs should ensure git's safe.directory is configured for $GITHUB_WORKSPACE *before* invoking ResolveBase — without it, the merge-base auto-fetch and HEAD~1 lookups will fail with "dubious ownership in repository". The cmd-layer wrapper `internal/exec.resolveBaseFromCI` does this via `git.EnsureGitSafeDirectory()` and is gated by `ci.enabled`.

func (*Provider) StartLogGroup added in v1.223.0

func (p *Provider) StartLogGroup(title string) error

StartLogGroup emits a GitHub Actions workflow command that opens a collapsible log group.

func (*Provider) SuppressLogGrouping added in v1.231.0

func (p *Provider) SuppressLogGrouping() bool

SuppressLogGrouping implements provider.LogGroupingSuppressor. It reports true while atmos runs inside a deprecated marketplace action (see LegacyActionRepo), because those actions capture the atmos process's stdout and parse it as JSON. A `::group::`/`::endgroup::` marker on stdout would corrupt that JSON, and the markers cannot move to stderr (they must bracket the stdout content they fold, and the runner does not guarantee ordering across streams), so the only safe option is to emit no group markers at all. Annotations are unaffected — they stay on stderr regardless. See #3309.

func (*Provider) UpdateCheckRun

func (p *Provider) UpdateCheckRun(ctx context.Context, opts *provider.UpdateCheckRunOptions) (*provider.CheckRun, error)

UpdateCheckRun updates an existing commit status on a commit. Statuses are keyed by their context (the check name), so UpdateCheckRunOptions.ID is not needed and is ignored. The state mapping is the one documented on CreateCheckRun.

func (*Provider) UploadSBOM added in v1.225.0

func (p *Provider) UploadSBOM(ctx context.Context, report provider.SBOMReport) (*provider.SBOMUpload, error)

UploadSBOM publishes an Atmos-generated SBOM as a GitHub Actions artifact. GitHub's dependency-graph SBOM endpoints do not accept submitted SBOMs, so this intentionally preserves the generated document as a run artifact rather than claiming dependency-graph ingestion.

func (*Provider) ValidateConfig

func (p *Provider) ValidateConfig() error

ValidateConfig fails the run early when the configured API base URL is unusable.

func (*Provider) WriteEnv

func (p *Provider) WriteEnv(key, value string) error

WriteEnv appends key=value to the file named by GITHUB_ENV so later workflow steps see the variable. Multiline values use a heredoc. It never falls back to stdout: without GITHUB_ENV the export cannot take effect, so it returns an error instead of silently dropping it.

Directories

Path Synopsis
Package ghtest is test support for the CI subsystem: a fake GitHub REST API that records every write the GitHub CI provider makes, plus a fixture that sets the GitHub Actions environment (GITHUB_*) so the real provider can be exercised end to end without network access.
Package ghtest is test support for the CI subsystem: a fake GitHub REST API that records every write the GitHub CI provider makes, plus a fixture that sets the GitHub Actions environment (GITHUB_*) so the real provider can be exercised end to end without network access.

Jump to

Keyboard shortcuts

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