labels

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: GPL-3.0 Imports: 7 Imported by: 0

Documentation

Overview

Package labels provides label state management for PR lifecycle tracking. It implements a finite state machine for tracking PRs through discovery, qualification, merge, and deployment phases using GitHub labels as the state store.

DEPRECATED: State types and functions are being migrated to internal/domain/pr. This file maintains backward compatibility via type aliases and re-exports. New code should import internal/domain/pr directly.

Index

Constants

View Source
const (
	StateDiscovered    = pr.StateDiscovered
	StateQualifying    = pr.StateQualifying
	StateQualified     = pr.StateQualified
	StateMerging       = pr.StateMerging
	StateMerged        = pr.StateMerged
	StateDeploying     = pr.StateDeploying
	StateSynced        = pr.StateSynced
	StateFailed        = pr.StateFailed
	StateDrifted       = pr.StateDrifted
	StateUnhealthy     = pr.StateUnhealthy
	StateTestTriggered = pr.StateTestTriggered
	StateTestRunning   = pr.StateTestRunning
	StateTestPassed    = pr.StateTestPassed
	StateTestFailed    = pr.StateTestFailed
	StatePromoting     = pr.StatePromoting
	StateUnknown       = pr.StateUnknown
)

Re-exported state constants for backward compatibility.

View Source
const LabelPrefix = pr.LabelPrefix

LabelPrefix is the namespace for all cd-operator labels.

Variables

View Source
var (
	// AllStates returns all valid states. Use pr.AllStates for new code.
	AllStates = pr.AllStates

	// StateFromLabel extracts state from label. Use pr.StateFromLabel for new code.
	StateFromLabel = pr.StateFromLabel

	// ValidTransitions returns valid transitions. Use pr.ValidTransitions for new code.
	ValidTransitions = pr.ValidTransitions

	// IsValidTransition checks transition validity. Use pr.IsValidTransition for new code.
	IsValidTransition = pr.IsValidTransition

	// NextStates returns next valid states. Use pr.NextStates for new code.
	NextStates = pr.NextStates

	// NewTransitionError creates transition error. Use pr.NewTransitionError for new code.
	NewTransitionError = pr.NewTransitionError

	// ValidateTransition validates a transition. Use pr.ValidateTransition for new code.
	ValidateTransition = pr.ValidateTransition
)

Re-exported functions for backward compatibility.

Functions

This section is empty.

Types

type BatchResult

type BatchResult struct {
	// TotalOperations is the number of operations attempted
	TotalOperations int

	// SuccessfulOperations is the number of operations that succeeded
	SuccessfulOperations int

	// FailedOperations is the number of operations that failed
	FailedOperations int

	// Errors contains any errors that occurred during the batch operation
	Errors []error

	// Duration is how long the batch operation took
	Duration time.Duration
}

BatchResult represents the result of a batch label operation.

type DynamicLabelExtraction

type DynamicLabelExtraction struct {
	// FilePath is the file path in the PR to read
	FilePath string

	// Key is the simple YAML key to extract (mutually exclusive with JSONPath)
	Key string

	// JSONPath is the JSONPath expression to extract complex values
	JSONPath string

	// LabelName is the name of the label to create (e.g., "cd/version")
	LabelName string

	// Required indicates whether this extraction must succeed
	Required bool

	// DefaultValue is used if extraction fails and not required
	DefaultValue string
}

DynamicLabelExtraction represents configuration for extracting dynamic labels.

type FailureSeverity

type FailureSeverity string

FailureSeverity indicates the severity level of a validation failure.

const (
	// SeverityError indicates a failure that prevents progression
	SeverityError FailureSeverity = "error"

	// SeverityWarning indicates a failure that allows progression with caveats
	SeverityWarning FailureSeverity = "warning"

	// SeverityInfo indicates informational feedback
	SeverityInfo FailureSeverity = "info"
)

type GitHubClient

type GitHubClient interface {
	AddLabel(ctx context.Context, repo github.Repository, number int, label string) error
	RemoveLabel(ctx context.Context, repo github.Repository, number int, label string) error
	GetPR(ctx context.Context, repo github.Repository, number int) (*github.PullRequest, error)
}

GitHubClient defines the GitHub operations needed by the label manager. This interface allows mocking in tests and prevents tight coupling.

type LabelConfig

type LabelConfig struct {
	// LabelColors maps states to their GitHub label colors (hex without #)
	LabelColors map[State]string

	// DryRun if true, operations will be logged but not executed
	DryRun bool

	// MaxRetries is the number of times to retry failed GitHub API calls
	MaxRetries int

	// RetryDelay is the delay between retries
	RetryDelay time.Duration

	// DynamicLabelPrefix is the prefix for dynamic labels (default: "cd/")
	DynamicLabelPrefix string
}

LabelConfig holds configuration for label management behavior.

func DefaultConfig

func DefaultConfig() *LabelConfig

DefaultConfig returns a LabelConfig with sensible defaults.

type LabelManager

type LabelManager interface {
	// ApplyState applies a state to a PR by updating its labels atomically.
	// It removes any existing cd/state: labels and adds the new one.
	// Returns an error if the state transition is invalid or GitHub API fails.
	ApplyState(ctx context.Context, pr github.PullRequest, state State) error

	// GetCurrentState determines the current state of a PR from its labels.
	// Returns StateUnknown if no cd/state: label is found.
	GetCurrentState(pr github.PullRequest) State

	// SyncToGitHub ensures the PR's GitHub labels match the desired state.
	// This is used for reconciliation and recovery scenarios.
	SyncToGitHub(ctx context.Context, pr github.PullRequest, state State) (*SyncResult, error)

	// TransitionState performs a validated state transition.
	// It checks if the transition is valid before applying the new state.
	TransitionState(ctx context.Context, pr github.PullRequest, toState State) error

	// RemoveAllStateLabels removes all cd/state: labels from a PR.
	// Used for cleanup or manual intervention scenarios.
	RemoveAllStateLabels(ctx context.Context, pr github.PullRequest) error

	// AddDynamicLabel adds a dynamic label (e.g., cd/version:1.2.3) to a PR.
	// These labels provide metadata and don't affect state transitions.
	AddDynamicLabel(ctx context.Context, pr github.PullRequest, key, value string) error

	// RemoveDynamicLabels removes all labels with a specific prefix.
	// Used to clean up old dynamic labels before applying new ones.
	RemoveDynamicLabels(ctx context.Context, pr github.PullRequest, prefix string) error
}

LabelManager provides PR label lifecycle management with state machine enforcement. It handles atomic state transitions and synchronization with GitHub.

func NewManager

func NewManager(githubClient GitHubClient, config *LabelConfig, logger Logger) LabelManager

NewManager creates a new label manager with the provided configuration.

type LabelOperation

type LabelOperation struct {
	// Type is the operation type (add, remove)
	Type LabelOperationType

	// Label is the label name to operate on
	Label string

	// PR is the pull request number
	PRNumber int
}

LabelOperation represents a label operation for batching.

type LabelOperationType

type LabelOperationType string

LabelOperationType represents the type of label operation.

const (
	// LabelOperationAdd adds a label
	LabelOperationAdd LabelOperationType = "add"

	// LabelOperationRemove removes a label
	LabelOperationRemove LabelOperationType = "remove"
)

type Logger

type Logger interface {
	Debug(msg string, fields ...zap.Field)
	Info(msg string, fields ...zap.Field)
	Warn(msg string, fields ...zap.Field)
	Error(msg string, fields ...zap.Field)
}

Logger defines the logging interface used by the label manager.

type State

type State = pr.State

State represents a PR lifecycle state. Use pr.State for new code.

type SyncResult

type SyncResult struct {
	// InitialState is the state before synchronization
	InitialState State

	// FinalState is the state after synchronization
	FinalState State

	// LabelsAdded contains labels that were added to the PR
	LabelsAdded []string

	// LabelsRemoved contains labels that were removed from the PR
	LabelsRemoved []string

	// Errors contains any non-fatal errors that occurred during sync
	Errors []error

	// SyncTime is when the sync operation completed
	SyncTime time.Time
}

SyncResult represents the result of synchronizing labels to GitHub.

type Transition

type Transition = pr.Transition

Transition represents a state transition. Use pr.Transition for new code.

type TransitionError

type TransitionError = pr.TransitionError

TransitionError wraps transition errors. Use pr.TransitionError for new code.

type TransitionRequest

type TransitionRequest struct {
	// PR is the pull request to transition
	PR github.PullRequest

	// ToState is the target state
	ToState State

	// Reason is an optional human-readable reason for the transition
	Reason string

	// Metadata contains optional key-value pairs for context
	Metadata map[string]string

	// Force bypasses transition validation (use with caution)
	Force bool
}

TransitionRequest represents a request to transition a PR to a new state.

type TransitionResult

type TransitionResult struct {
	// Success indicates whether the transition succeeded
	Success bool

	// PreviousState is the state before transition
	PreviousState State

	// NewState is the state after transition
	NewState State

	// Timestamp is when the transition occurred
	Timestamp time.Time

	// Error contains any error that occurred during transition
	Error error

	// SyncResult contains the label synchronization details
	SyncResult *SyncResult
}

TransitionResult represents the result of a state transition operation.

type ValidationFailure

type ValidationFailure struct {
	// ValidatorName is the name of the validator that failed
	ValidatorName string

	// Reason is a human-readable description of why validation failed
	Reason string

	// Details provides additional context (e.g., expected vs actual values)
	Details map[string]interface{}

	// Severity indicates how critical this failure is
	Severity FailureSeverity
}

ValidationFailure represents a qualification validation failure with context.

func (ValidationFailure) Error

func (f ValidationFailure) Error() string

Error implements the error interface for ValidationFailure.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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