gitops

package
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gitops provides read/write operations for the gitops repository hosting preview environment values.yaml files.

Package gitops provides read/write operations for the gitops repository.

Index

Constants

View Source
const DefaultLabel = "preview"

DefaultLabel is the preview label when preview.label is absent.

View Source
const MaxListedPullRequestFiles = 3000

MaxListedPullRequestFiles is the most files GitHub lists for a pull request: "Responses include a maximum of 3000 files."

View Source
const MaxWriteRetries = 3

MaxWriteRetries is the cap on 409-conflict retries for WritePreviewWithRetry.

View Source
const PRCommentMarker = "<!-- badil:preview -->"

PRCommentMarker is the HTML comment used as a sentinel for find-or-create semantics on PR comments.

Variables

View Source
var (
	ErrNotFound     = errors.New("gitops: not found")
	ErrUnauthorized = errors.New("gitops: unauthorized")
)

Sentinel errors. Callers should test with errors.Is.

Functions

This section is empty.

Types

type ChangedFile added in v0.22.0

type ChangedFile struct {
	Filename         string
	PreviousFilename string
}

ChangedFile is a file a pull request changes, its path relative to the repository root. PreviousFilename is its path before a rename, empty otherwise.

type Client

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

Client wraps a go-github client scoped to a specific gitops owner/repo.

func NewClient

func NewClient(client *gh.Client, owner, repo string, opts ...Option) *Client

NewClient binds the gh client to owner/repo. owner is the GitHub organization or user; repo is the bare repository name.

func (*Client) DeletePreviewWithRetry

func (c *Client) DeletePreviewWithRetry(
	ctx context.Context,
	slug, message string,
	stillDelete func(preview.PreviewValues) bool,
) (*DeleteResult, error)

DeletePreviewWithRetry deletes previews/<slug>/values.yaml with message, provided stillDelete holds on the file read just before the delete. On a 409 conflict the file is re-fetched and stillDelete re-checked, up to MaxWriteRetries attempts. A stillDelete returning false, or a missing file (on read, re-fetch or delete), deletes nothing: an empty DeleteResult and a nil error.

func (*Client) FanOutPRComments

func (c *Client) FanOutPRComments(ctx context.Context, vals preview.PreviewValues, body string) error

FanOutPRComments posts (or updates) the same markdown body as a comment on every open PR referenced in vals.Services.Metadata.pr-url. Closed PRs are skipped, so a stale summary never overwrites their teardown comment. Failures on individual services (including a PR state lookup) are collected but do not abort the loop — best-effort delivery.

Find-or-create semantics: the comment body is prefixed with PRCommentMarker (HTML comment), so subsequent runs find and update the existing comment rather than spamming new ones.

func (*Client) FetchServiceCatalog

func (c *Client) FetchServiceCatalog(ctx context.Context) (*ServiceCatalog, error)

FetchServiceCatalog reads badil.yaml from the gitops repo and returns its validated service catalog (the keys of its services mapping, with each service's repo and branch) and `preview` block. A malformed file is an error.

func (*Client) FetchServiceCatalogSHA added in v0.21.0

func (c *Client) FetchServiceCatalogSHA(ctx context.Context) (*ServiceCatalog, string, error)

FetchServiceCatalogSHA is FetchServiceCatalog, plus the blob SHA of the badil.yaml it read on the default branch. When the file was read but its content can't be decoded or parsed, the SHA is returned with the error; it is "" when the file could not be read.

func (*Client) FullName added in v0.21.0

func (c *Client) FullName() string

FullName returns the gitops repo as owner/repo.

func (*Client) GetPreview

func (c *Client) GetPreview(ctx context.Context, slug string) (*preview.PreviewValues, string, error)

GetPreview reads previews/<slug>/values.yaml and returns the parsed values plus the file SHA (needed for subsequent updates). Returns ErrNotFound when the file does not exist.

func (*Client) GetPullRequest

func (c *Client) GetPullRequest(ctx context.Context, owner, repo string, number int) (*PullRequest, error)

GetPullRequest reads owner/repo#number. Lookup failures (including 404 and 403) are returned as errors.

func (*Client) ListPreviews

func (c *Client) ListPreviews(ctx context.Context) ([]string, error)

ListPreviews returns the sorted names of the directories under previews/. A missing previews/ directory yields an empty slice. The contents API caps a directory listing at 1,000 entries; this is not paginated.

func (*Client) ListPullRequestFiles added in v0.22.0

func (c *Client) ListPullRequestFiles(ctx context.Context, owner, repo string, number int) ([]ChangedFile, error)

ListPullRequestFiles lists the files owner/repo#number changes, reading every page (100 files each). GitHub lists at most MaxListedPullRequestFiles. A failure on any page is returned as an error.

func (*Client) SyncPreviewWithRetry added in v0.19.0

func (c *Client) SyncPreviewWithRetry(ctx context.Context, slug string, catalog *ServiceCatalog) (*SyncResult, error)

SyncPreviewWithRetry rewrites previews/<slug>/values.yaml as its projection on catalog (applyCatalog) when that differs from the file (preview.Equal), with the message "chore(preview): sync <slug> with badil.yaml". On a 409 conflict the file is re-fetched and the projection recomputed, up to MaxWriteRetries attempts. A file that already matches is not written. A missing file (on read or re-fetch) is a no-op: a SyncResult with only NotFound set and a nil error.

Its duration, retries included, is observed as the sync operation.

func (*Client) TeardownPreviewWithRetry

func (c *Client) TeardownPreviewWithRetry(
	ctx context.Context,
	slug, owner, repo string,
	prNumber int,
) (*TeardownResult, error)

TeardownPreviewWithRetry unpins every service of previews/<slug>/values.yaml deployed by the PR owner/repo#prNumber. The file is deleted when no pin remains. Otherwise it is updated, projected on badil.yaml after the unpin (applyCatalog), so that an unpinned entry gets its branch-tracking imageTag in the same commit: badil.yaml is read once, before the first update, and a read or parse error fails the teardown with nothing written. A deletion does not read badil.yaml. On a 409 conflict the file is re-fetched, the unpin re-applied and update vs delete decided again, up to MaxWriteRetries attempts. A missing file (on read, re-fetch or delete) or a PR that pinned nothing is a no-op: an empty TeardownResult and a nil error.

Its duration, retries included, is observed as the teardown operation.

func (*Client) UnpinServicesWithRetry added in v0.22.0

func (c *Client) UnpinServicesWithRetry(
	ctx context.Context,
	slug, owner, repo string,
	prNumber int,
	services []string,
) (*TeardownResult, error)

UnpinServicesWithRetry unpins, in previews/<slug>/values.yaml, the entries deployed by the PR owner/repo#prNumber whose service is in services (preview.UnpinPRServices); the PR's other entries stay pinned. It is TeardownPreviewWithRetry except that the file is never deleted: it is updated, projected on badil.yaml, even when no pin remains, so Deleted is always false.

Its duration, retries included, is observed as the teardown operation.

func (*Client) UpsertPRComment

func (c *Client) UpsertPRComment(ctx context.Context, owner, repo string, prNumber int, body string) error

UpsertPRComment posts body as badil's comment on owner/repo#prNumber, prefixed with PRCommentMarker: the existing marked comment is updated, or a new one is created.

func (*Client) WritePreview

func (c *Client) WritePreview(
	ctx context.Context,
	slug string,
	vals preview.PreviewValues,
	sha, message string,
) (string, error)

WritePreview persists vals at previews/<slug>/values.yaml. When sha is empty the file is created; otherwise an update is performed against that SHA. Returns the html_url of the resulting commit.

func (*Client) WritePreviewWithRetry

func (c *Client) WritePreviewWithRetry(
	ctx context.Context,
	slug string,
	catalog *ServiceCatalog,
	serviceName, commitSha string,
	inputs preview.DeployInputs,
	createMessage, updateMessage string,
	skipUnchanged bool,
) (*WriteResult, error)

WritePreviewWithRetry composes Get → (Build|Update)PreviewValues → Write and retries up to MaxWriteRetries times on 409 conflicts (someone else updated the file between our read and write). On every retry the latest file is re-fetched and the deploy is re-applied via preview.UpdatePreviewValues, so the merge is always against the freshest baseline.

On a fresh create the full catalog is materialized via BuildPreviewValues so the resulting values.yaml lists every service (the triggering one pinned to commitSha, the rest tracking their branch).

After every build or merge, the file is projected on catalog (applyCatalog). The written file follows the current catalog.

With skipUnchanged, when the file exists and the values to write differ from it only in serviceName's updated-at (preview.EqualExceptUpdatedAt), nothing is written: on the first read and after every 409 re-fetch. The result is then Unchanged.

Returns a WriteResult capturing the final PreviewValues that was written, the gitops commit URL, and the commit message used — callers (e.g. the deploy handler) can render PR summaries without re-fetching.

Its duration, retries included, is observed as the write operation, and a write that Created the file increments the previews gauge.

type DeleteResult

type DeleteResult struct {
	Deleted   bool
	Values    preview.PreviewValues
	CommitURL string
}

DeleteResult is the outcome of DeletePreviewWithRetry. Deleted is false when nothing was deleted; Values then is empty. Values holds the content that was deleted.

type Option

type Option func(*Client)

Option configures a Client built by NewClient.

func WithMetrics

func WithMetrics(m *metrics.Metrics) Option

WithMetrics times WritePreviewWithRetry, TeardownPreviewWithRetry (and UnpinServicesWithRetry, as the teardown operation) and SyncPreviewWithRetry in m, and counts the previews WritePreviewWithRetry creates.

type PullRequest

type PullRequest struct {
	// Open is true when the state is open; a merged PR is closed.
	Open    bool
	HeadRef string
	HeadSHA string
	// Author is the PR author's login.
	Author string
	// URL is the PR's html_url.
	URL string
	// Labels holds the names of the PR's labels.
	Labels []string
	// FullName is the base repository's owner/repo.
	FullName string
	// HeadFullName is the head repository's owner/repo; it differs from
	// FullName on a fork PR.
	HeadFullName string
	// ChangedFiles is the number of files the PR changes (changed_files).
	ChangedFiles int
}

PullRequest is the state of a pull request as read from GitHub.

type ServiceCatalog

type ServiceCatalog struct {
	preview.Catalog

	// URLs is the validated `preview` block; its zero value means off.
	URLs preview.URLConfig
	// Label is the pull request label that requests a preview (preview.label,
	// default "preview"). GitHub label names compare case-insensitively.
	Label string
	// MaxPreviews is preview.maxPreviews, the most previews that may exist
	// before a deploy that would create a new one is refused. 0 means no cap.
	MaxPreviews int
	// ArgoCDURL is preview.argocdURL, the base URL of the Argo CD UI without
	// a trailing slash. When set, the preview summary links the preview's
	// Applications in Argo CD. It is empty when absent.
	ArgoCDURL string
	// Paths holds services.<name>.paths, for the services that set it: the
	// doublestar patterns, relative to the service's repository root, of the
	// files that belong to it. A pull request pins such a service only when
	// it changes one of them. It plays no part in a preview file's projection.
	Paths map[string][]string
}

ServiceCatalog is the parsed badil.yaml of the gitops repo. Its Catalog holds the services and dependencies, in file order, and their settings; GitopsRepoURL is left empty, set by the client when it projects a preview file. A map or slice of it is nil when no entry sets it.

func ParseCatalog added in v0.18.0

func ParseCatalog(raw []byte) (*ServiceCatalog, error)

ParseCatalog parses and validates the content of badil.yaml.

func (*ServiceCatalog) ServicesForRepo

func (c *ServiceCatalog) ServicesForRepo(owner, repo string) []string

ServicesForRepo returns, in catalog order, the services whose git URL is https://github.com/<owner>/<repo>, compared lowercased and with a trailing "/" then ".git" removed. Other URL forms (SSH, GitHub Enterprise) never match.

type SyncResult added in v0.19.0

type SyncResult struct {
	Values        preview.PreviewValues
	Excluded      []string
	CommitURL     string
	CommitMessage string
	Changed       bool
	Notify        bool
	NotFound      bool
}

SyncResult is the outcome of SyncPreviewWithRetry. Changed is true when the file was rewritten; Values, Excluded (preview.Projection.Excluded), CommitURL and CommitMessage then describe that write. Notify is true when the written file's ordered list of service or dependency names, or any entry's host, differs from the file it replaced. NotFound is true when the file does not exist.

type TeardownResult

type TeardownResult struct {
	Values        preview.PreviewValues
	Excluded      []string
	Catalog       *ServiceCatalog
	Removed       []string
	Deleted       bool
	CommitURL     string
	CommitMessage string
}

TeardownResult is the outcome of TeardownPreviewWithRetry and UnpinServicesWithRetry. Removed lists the services unpinned from the PR; it is empty when there was nothing to tear down. Values, Excluded (preview.Projection.Excluded) and Catalog, the badil.yaml the file was projected on, are set only when Deleted is false.

type WriteResult

type WriteResult struct {
	Values        preview.PreviewValues
	Excluded      []string
	CommitURL     string
	CommitMessage string
	Unchanged     bool
	Created       bool
}

WriteResult is the outcome of a successful WritePreviewWithRetry call. CommitMessage is whichever of {createMessage, updateMessage} was actually used for the gitops commit, so callers can label PR summaries consistently with what GitHub shows when the user clicks through to the commit.

Unchanged is true when skipUnchanged skipped the write: Values then holds the fetched file, and CommitURL and CommitMessage are empty. Created is true when the write created the file (the first attempt on a missing file); a write after a 409 re-fetch is an update. Excluded is the projection's (preview.Projection.Excluded).

Jump to

Keyboard shortcuts

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