ci

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package ci defines TerraCI's CI-facing domain: persisted plan/report artifacts, review-comment contracts, and provider-shared CI config types.

Index

Constants

View Source
const AggregateReportProducer = "summary"

AggregateReportProducer is the canonical producer name for the aggregated Terraform plan summary report consumed by local renderers.

View Source
const CommentMarker = "<!-- terraci-plan-comment -->"

CommentMarker is used to identify TerraCI review comments for updates.

Variables

This section is empty.

Functions

func AggregateReportFilename added in v0.10.1

func AggregateReportFilename() string

AggregateReportFilename returns the canonical artifact name for the aggregated Terraform plan summary report.

func CommentEnabled added in v0.9.4

func CommentEnabled(cfg *MRCommentConfig) bool

CommentEnabled returns the effective enabled state for MR/PR comments. Nil config, nil Enabled, and missing config all default to true.

func DecodeSection added in v0.10.0

func DecodeSection[T any](section ReportSection) (T, error)

DecodeSection JSON-decodes the section payload into T. Consumers select the expected payload type based on Section.Kind.

func HasCommentMarker added in v0.9.4

func HasCommentMarker(body string) bool

HasCommentMarker reports whether the provided body contains the TerraCI review-comment marker.

func ReportFilename added in v0.9.0

func ReportFilename(producer string) string

ReportFilename returns the canonical artifact name for a producer's report.

func SaveJSON added in v0.7.4

func SaveJSON(serviceDir, filename string, v any) error

SaveJSON writes any value as indented JSON to {serviceDir}/{filename}.

func SaveReport added in v0.7.4

func SaveReport(serviceDir string, report *Report) error

SaveReport writes a report as {serviceDir}/{producer}-report.json.

func SaveResultsAndReport added in v0.10.0

func SaveResultsAndReport(serviceDir, resultsFilename string, results any, report *Report) error

SaveResultsAndReport persists a producer's raw result payload alongside its canonical Report. Both writes are attempted independently — failures are joined into a single error so callers always know which side broke.

Replaces the recurring 6-line "save results, build report, save report" pattern in cost / policy / tfupdate. Producers must build their report up front (since report construction returns its own error) and pass it in.

Types

type CommentService

type CommentService interface {
	IsEnabled() bool
	UpsertComment(ctx context.Context, body string) error
}

CommentService defines the interface for posting plan summaries to PRs/MRs

type DependencyKind added in v0.10.0

type DependencyKind string

DependencyKind identifies the dependency category for an update row.

const (
	DependencyKindProvider DependencyKind = "provider"
	DependencyKindModule   DependencyKind = "module"
)

type DependencyUpdateRow added in v0.10.0

type DependencyUpdateRow struct {
	ModulePath string                 `json:"module_path"`
	Kind       DependencyKind         `json:"kind"`
	Name       string                 `json:"name"`
	Current    string                 `json:"current,omitempty"`
	Latest     string                 `json:"latest,omitempty"`
	Bumped     string                 `json:"bumped,omitempty"`
	Status     DependencyUpdateStatus `json:"status"`
	Issue      string                 `json:"issue,omitempty"`
}

DependencyUpdateRow is one dependency update result.

type DependencyUpdateStatus added in v0.10.0

type DependencyUpdateStatus string

DependencyUpdateStatus is the outcome of a dependency update check.

const (
	DependencyUpdateStatusUpToDate        DependencyUpdateStatus = "up_to_date"
	DependencyUpdateStatusUpdateAvailable DependencyUpdateStatus = "update_available"
	DependencyUpdateStatusApplied         DependencyUpdateStatus = "applied"
	DependencyUpdateStatusSkipped         DependencyUpdateStatus = "skipped"
	DependencyUpdateStatusError           DependencyUpdateStatus = "error"
)

type DependencyUpdatesSection added in v0.10.0

type DependencyUpdatesSection struct {
	Rows []DependencyUpdateRow `json:"rows,omitempty"`
}

DependencyUpdatesSection holds actionable dependency update rows.

type Finding added in v0.10.0

type Finding struct {
	Severity  FindingSeverity `json:"severity"`
	Message   string          `json:"message"`
	Namespace string          `json:"namespace,omitempty"`
}

Finding describes one warned/failed issue.

type FindingRow added in v0.10.0

type FindingRow struct {
	ModulePath string           `json:"module_path"`
	Status     FindingRowStatus `json:"status"`
	Findings   []Finding        `json:"findings,omitempty"`
}

FindingRow is one module or resource result in a findings report.

type FindingRowStatus added in v0.10.0

type FindingRowStatus string

FindingRowStatus is the outcome for one findings row.

const (
	FindingRowStatusPass FindingRowStatus = "pass"
	FindingRowStatusWarn FindingRowStatus = "warn"
	FindingRowStatusFail FindingRowStatus = "fail"
)

type FindingSeverity added in v0.10.0

type FindingSeverity string

FindingSeverity is the severity of a finding.

const (
	FindingSeverityWarn FindingSeverity = "warn"
	FindingSeverityFail FindingSeverity = "fail"
)

type FindingsSection added in v0.10.0

type FindingsSection struct {
	Rows []FindingRow `json:"rows,omitempty"`
}

FindingsSection holds warned/failed findings for modules or resources.

type Image added in v0.9.4

type Image struct {
	// Name is the image name (e.g., "hashicorp/terraform:1.6")
	Name string `yaml:"name,omitempty" json:"name,omitempty" jsonschema:"description=Docker image name"`
	// Entrypoint overrides the default entrypoint.
	Entrypoint []string `yaml:"entrypoint,omitempty" json:"entrypoint,omitempty" jsonschema:"description=Override default entrypoint"`
}

Image defines a Docker image configuration for CI jobs.

func (*Image) HasEntrypoint added in v0.9.4

func (img *Image) HasEntrypoint() bool

HasEntrypoint returns true if entrypoint is configured.

func (Image) MarshalYAML added in v0.10.0

func (img Image) MarshalYAML() (any, error)

MarshalYAML emits the short string form ("image:1.0") when only Name is set, preserving round-trip symmetry with UnmarshalYAML. Configs that started as shorthand stay shorthand after `terraci init` writes them back; only configs with an Entrypoint override expand to the full mapping.

func (*Image) String added in v0.9.4

func (img *Image) String() string

String returns the image name.

func (*Image) UnmarshalYAML added in v0.9.4

func (img *Image) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML supports both string shorthand ("image:1.0") and full object ({name: "image:1.0"}).

type MRCommentConfig added in v0.9.4

type MRCommentConfig struct {
	// Enabled enables MR comments (default: true when in MR pipeline).
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty" jsonschema:"description=Enable MR comments,default=true"`
	// OnChangesOnly only comments when there are changes.
	OnChangesOnly bool `` /* 126-byte string literal not displayed */
	// IncludeDetails includes full plan output in collapsible sections.
	IncludeDetails bool `` /* 151-byte string literal not displayed */
}

MRCommentConfig contains settings for MR/PR comments shared by CI providers.

type ModuleTableRow added in v0.10.0

type ModuleTableRow struct {
	ModuleID          string     `json:"module_id"`
	ModulePath        string     `json:"module_path"`
	Status            PlanStatus `json:"status"`
	Summary           string     `json:"summary,omitempty"`
	Error             string     `json:"error,omitempty"`
	StructuredDetails string     `json:"structured_details,omitempty"`
	RawPlanOutput     string     `json:"raw_plan_output,omitempty"`
}

ModuleTableRow is one actionable module entry in a module table section.

type ModuleTableSection added in v0.10.0

type ModuleTableSection struct {
	Environment string           `json:"environment,omitempty"`
	Rows        []ModuleTableRow `json:"rows,omitempty"`
}

ModuleTableSection groups module-oriented rows such as terraform plan results.

type OverviewSection added in v0.10.0

type OverviewSection struct {
	PlanStats SummaryPlanStats        `json:"plan_stats"`
	Reports   []SummaryReportOverview `json:"reports,omitempty"`
}

OverviewSection is the aggregate summary report payload.

type PlanResult

type PlanResult struct {
	ModuleID          string            `json:"module_id"`
	ModulePath        string            `json:"module_path"`
	Components        map[string]string `json:"components,omitempty"`
	Status            PlanStatus        `json:"status"`
	Summary           string            `json:"summary"`
	StructuredDetails string            `json:"structured_details,omitempty"`
	RawPlanOutput     string            `json:"raw_plan_output,omitempty"`
	Error             string            `json:"error,omitempty"`
	ExitCode          int               `json:"exit_code,omitempty"`
	Duration          time.Duration     `json:"duration,omitempty"`
}

PlanResult is the canonical representation of a single module's plan outcome — both for in-memory rendering and on-disk persistence.

func (*PlanResult) Get

func (r *PlanResult) Get(name string) string

Get returns the value of a named component from the Components map.

type PlanResultCollection

type PlanResultCollection struct {
	Results     []PlanResult `json:"results"`
	PipelineID  string       `json:"pipeline_id,omitempty"`
	CommitSHA   string       `json:"commit_sha,omitempty"`
	GeneratedAt time.Time    `json:"generated_at"`
}

PlanResultCollection is the persisted CI artifact collection for a pipeline run.

func (*PlanResultCollection) Fingerprint added in v0.10.0

func (c *PlanResultCollection) Fingerprint() string

Fingerprint returns a stable content fingerprint for the collection.

type PlanStatus

type PlanStatus string

PlanStatus represents the status of a terraform plan.

const (
	PlanStatusPending   PlanStatus = "pending"
	PlanStatusRunning   PlanStatus = "running"
	PlanStatusSuccess   PlanStatus = "success"
	PlanStatusNoChanges PlanStatus = "no_changes"
	PlanStatusChanges   PlanStatus = "changes"
	PlanStatusFailed    PlanStatus = "failed"
)

func PlanStatusFromPlan added in v0.7.4

func PlanStatusFromPlan(hasChanges bool) PlanStatus

PlanStatusFromPlan determines the CI plan status from a parsed plan.

type Report added in v0.7.4

type Report struct {
	Producer   string            `json:"producer"`
	Title      string            `json:"title"`
	Status     ReportStatus      `json:"status"`
	Summary    string            `json:"summary"`
	Provenance *ReportProvenance `json:"provenance,omitempty"`
	Sections   []ReportSection   `json:"sections,omitempty"`
}

Report is a CI enrichment artifact written by a tool and consumed by report aggregation flows. Producers persist reports as {serviceDir}/{producer}-report.json.

func BuildReport added in v0.10.0

func BuildReport(producer, title string, status ReportStatus, summary string, sections ...ReportSection) *Report

BuildReport assembles a producer Report with the standard provenance shell. Producers (cost / policy / tfupdate) call this instead of constructing the &Report{...} literal by hand — drives uniform field ordering and a single point to update when the Report shape grows.

func LoadReport added in v0.9.0

func LoadReport(path string) (*Report, error)

LoadReport reads a single report file from disk.

func LoadReports added in v0.9.0

func LoadReports(serviceDir string) ([]*Report, error)

LoadReports reads all *-report.json files from the service directory in deterministic filename order.

func (*Report) Validate added in v0.10.0

func (r *Report) Validate() error

Validate verifies the persisted report artifact contract.

type ReportProvenance added in v0.10.0

type ReportProvenance struct {
	GeneratedAt            time.Time `json:"generated_at"`
	CommitSHA              string    `json:"commit_sha,omitempty"`
	PipelineID             string    `json:"pipeline_id,omitempty"`
	PlanResultsFingerprint string    `json:"plan_results_fingerprint,omitempty"`
}

ReportProvenance captures the source run identity for a persisted report.

Producers should populate provenance for every persisted report so local consumers (e.g. localexec/render) can decide whether the artifact still matches the current workspace. Use NewProvenance to fill GeneratedAt consistently and let producer-specific fields stay omitempty.

func NewProvenance added in v0.10.0

func NewProvenance(commitSHA, pipelineID, planResultsFingerprint string) *ReportProvenance

NewProvenance returns a ReportProvenance with GeneratedAt = time.Now().UTC(). Pass empty strings for fields the producer does not have — they remain omitempty in the resulting JSON.

type ReportSection added in v0.10.0

type ReportSection struct {
	Kind           ReportSectionKind `json:"kind"`
	Title          string            `json:"title,omitempty"`
	Status         ReportStatus      `json:"status,omitempty"`
	SectionSummary string            `json:"section_summary,omitempty"`
	Payload        json.RawMessage   `json:"payload,omitempty"`
}

ReportSection is a neutral envelope describing one slice of a CI report. The Payload is opaque JSON owned by the producer — consumers decode it according to Kind. Use EncodeSection / DecodeSection for type-safe access.

func EncodeSection added in v0.10.0

func EncodeSection[T any](kind ReportSectionKind, title, sectionSummary string, status ReportStatus, body T) (ReportSection, error)

EncodeSection builds a ReportSection by JSON-encoding the body. Producers pass a typed payload (e.g. OverviewSection, FindingsSection) plus the section's neutral metadata.

type ReportSectionKind added in v0.10.0

type ReportSectionKind string

ReportSectionKind identifies an application-owned report section payload. New kinds can be added by producers without modifying pkg/ci — the section payload is opaque JSON keyed only by Kind.

const (
	ReportSectionKindOverview          ReportSectionKind = "overview"
	ReportSectionKindModuleTable       ReportSectionKind = "module_table"
	ReportSectionKindFindings          ReportSectionKind = "findings"
	ReportSectionKindDependencyUpdates ReportSectionKind = "dependency_updates"
)

type ReportStatus added in v0.7.4

type ReportStatus string

ReportStatus indicates the outcome of a producer's check.

const (
	ReportStatusPass ReportStatus = "pass"
	ReportStatusWarn ReportStatus = "warn"
	ReportStatusFail ReportStatus = "fail"
)

func StatusFromCounts added in v0.10.0

func StatusFromCounts(fail, warn int) ReportStatus

StatusFromCounts returns the strictest status implied by the given fail / warn counts: any failure → Fail; any warning → Warn; otherwise Pass. Producers can still override (e.g. tfupdate treats "updates available" as a warning); this helper covers the common case.

func (ReportStatus) Valid added in v0.10.0

func (s ReportStatus) Valid() bool

Valid reports whether the status is one of the supported CI report outcomes.

type SummaryPlanStats added in v0.10.0

type SummaryPlanStats struct {
	Total     int `json:"total"`
	Success   int `json:"success,omitempty"`
	NoChanges int `json:"no_changes,omitempty"`
	Changes   int `json:"changes,omitempty"`
	Failed    int `json:"failed,omitempty"`
	Pending   int `json:"pending,omitempty"`
	Running   int `json:"running,omitempty"`
}

SummaryPlanStats tracks aggregate terraform plan counts.

type SummaryReportOverview added in v0.10.0

type SummaryReportOverview struct {
	Kind    ReportSectionKind `json:"kind"`
	Title   string            `json:"title"`
	Status  ReportStatus      `json:"status"`
	Summary string            `json:"summary,omitempty"`
}

SummaryReportOverview captures one contributing report at a glance.

Directories

Path Synopsis
Package citest hosts test-only helpers for pkg/ci consumers and producers.
Package citest hosts test-only helpers for pkg/ci consumers and producers.

Jump to

Keyboard shortcuts

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