qualification

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: 14 Imported by: 0

Documentation

Overview

Package qualification provides PR qualification validation for the cd-operator. It implements an extensible validation framework with configurable rules for determining whether PRs are ready for auto-merge.

Index

Constants

View Source
const (
	LayoutStandard = domainQual.LayoutStandard
	LayoutTMC      = domainQual.LayoutTMC
	LayoutUnknown  = domainQual.LayoutUnknown
)

Re-export layout type constants for backward compatibility.

View Source
const (
	SeverityError   = domainQual.SeverityError
	SeverityWarning = domainQual.SeverityWarning
	SeverityInfo    = domainQual.SeverityInfo
)

Re-export severity constants for backward compatibility.

Variables

View Source
var (
	NewSuccessResult = domainQual.NewSuccessResult
	NewFailureResult = domainQual.NewFailureResult
)

Re-export constructor functions for backward compatibility.

Functions

This section is empty.

Types

type ApprovalValidatorConfig

type ApprovalValidatorConfig struct {
	// MinApprovals is the minimum number of approvals required
	MinApprovals int `json:"minApprovals" yaml:"minApprovals"`

	// RequiredReviewers are users who must review the PR
	RequiredReviewers []string `json:"requiredReviewers,omitempty" yaml:"requiredReviewers,omitempty"`

	// RequiredTeams are teams that must have at least one member review
	RequiredTeams []string `json:"requiredTeams,omitempty" yaml:"requiredTeams,omitempty"`

	// IgnoreBotApprovals when true excludes bot approvals from the count
	IgnoreBotApprovals bool `json:"ignoreBotApprovals" yaml:"ignoreBotApprovals"`
}

ApprovalValidatorConfig defines configuration for approval validation.

type ApprovalsValidator

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

ApprovalsValidator validates that a PR has sufficient approvals.

func NewApprovalsValidator

func NewApprovalsValidator(config *ApprovalValidatorConfig, githubClient GitHubClient, logger Logger) *ApprovalsValidator

NewApprovalsValidator creates a new approvals validator with the given configuration.

func (*ApprovalsValidator) Name

func (av *ApprovalsValidator) Name() string

Name returns the name of this validator.

func (*ApprovalsValidator) Validate

func (av *ApprovalsValidator) Validate(ctx context.Context, pr github.PullRequest) (Result, error)

Validate checks if the PR has sufficient approvals.

type ChecksGitHubClient

type ChecksGitHubClient interface {
	ListStatuses(ctx context.Context, repo github.Repository, ref string) ([]github.Status, error)
}

ChecksGitHubClient defines the GitHub operations needed by the checks validator.

type ChecksValidator

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

ChecksValidator validates that required CI/CD status checks pass.

func NewChecksValidator

func NewChecksValidator(config *ChecksValidatorConfig, githubClient ChecksGitHubClient, logger Logger) *ChecksValidator

NewChecksValidator creates a new checks validator with the given configuration.

func (*ChecksValidator) Name

func (cv *ChecksValidator) Name() string

Name returns the name of this validator.

func (*ChecksValidator) Validate

func (cv *ChecksValidator) Validate(ctx context.Context, pr github.PullRequest) (Result, error)

Validate checks if all required status checks are passing.

type ChecksValidatorConfig

type ChecksValidatorConfig struct {
	// RequiredChecks are status checks that must pass
	RequiredChecks []string `json:"requiredChecks" yaml:"requiredChecks"`

	// OptionalChecks are checks that may be present but don't affect validation
	OptionalChecks []string `json:"optionalChecks,omitempty" yaml:"optionalChecks,omitempty"`

	// AllowedFailures are checks that are allowed to fail
	AllowedFailures []string `json:"allowedFailures,omitempty" yaml:"allowedFailures,omitempty"`

	// Timeout is the maximum time to wait for checks to complete
	Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
}

ChecksValidatorConfig defines configuration for CI/CD checks validation.

type CompositeStrategy

type CompositeStrategy string

CompositeStrategy defines how multiple validators are combined.

const (
	// StrategyAllMustPass requires all validators to pass (AND logic)
	StrategyAllMustPass CompositeStrategy = "all_must_pass"

	// StrategyAnyCanPass allows any validator to pass (OR logic)
	StrategyAnyCanPass CompositeStrategy = "any_can_pass"

	// StrategyMajorityMustPass requires majority of validators to pass
	StrategyMajorityMustPass CompositeStrategy = "majority_must_pass"

	// StrategyContinueOnError runs all validators regardless of failures
	StrategyContinueOnError CompositeStrategy = "continue_on_error"
)

type CompositeValidator

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

CompositeValidator combines multiple validators with configurable strategies.

func CreateDefaultComposite

func CreateDefaultComposite(logger Logger) *CompositeValidator

CreateDefaultComposite creates a composite validator with default validators.

func CreateDefaultCompositeWithDynamicLabels

func CreateDefaultCompositeWithDynamicLabels(client *github.Client, logger Logger) (*CompositeValidator, error)

CreateDefaultCompositeWithDynamicLabels creates a composite validator with dynamic label extraction.

func NewCompositeValidator

func NewCompositeValidator(validators []Validator, strategy CompositeStrategy) *CompositeValidator

NewCompositeValidator creates a new composite validator.

func (*CompositeValidator) GetStrategy

func (cv *CompositeValidator) GetStrategy() CompositeStrategy

GetStrategy returns the composite strategy.

func (*CompositeValidator) GetValidators

func (cv *CompositeValidator) GetValidators() []Validator

GetValidators returns the list of validators in this composite.

func (*CompositeValidator) Name

func (cv *CompositeValidator) Name() string

Name returns the name of the composite validator.

func (*CompositeValidator) Validate

func (cv *CompositeValidator) Validate(ctx context.Context, pr github.PullRequest) (Result, error)

Validate runs all validators according to the configured strategy.

func (*CompositeValidator) WithLogger

func (cv *CompositeValidator) WithLogger(logger Logger) *CompositeValidator

WithLogger adds a logger to the composite validator.

type ConfigLoader

type ConfigLoader struct{}

ConfigLoader provides methods to load qualification configuration from various sources.

func NewConfigLoader

func NewConfigLoader() *ConfigLoader

NewConfigLoader creates a new configuration loader.

func (*ConfigLoader) BuildRegistry

func (cl *ConfigLoader) BuildRegistry(config *QualificationConfig, githubClient interface{}, logger Logger) (*Registry, error)

BuildRegistry builds a validator registry from configuration. This is a helper function that creates and configures all validators.

func (*ConfigLoader) LoadApprovalValidatorConfig

func (cl *ConfigLoader) LoadApprovalValidatorConfig(filepath string) (*ApprovalValidatorConfig, error)

LoadApprovalValidatorConfig loads approval validator configuration from a file.

func (*ConfigLoader) LoadChecksValidatorConfig

func (cl *ConfigLoader) LoadChecksValidatorConfig(filepath string) (*ChecksValidatorConfig, error)

LoadChecksValidatorConfig loads checks validator configuration from a file.

func (*ConfigLoader) LoadFilePatternValidatorConfig

func (cl *ConfigLoader) LoadFilePatternValidatorConfig(filepath string) (*FilePatternValidatorConfig, error)

LoadFilePatternValidatorConfig loads file pattern validator configuration from a file.

func (*ConfigLoader) LoadFromBytes

func (cl *ConfigLoader) LoadFromBytes(data []byte, format string) (*QualificationConfig, error)

LoadFromBytes loads qualification configuration from raw bytes.

func (*ConfigLoader) LoadFromFile

func (cl *ConfigLoader) LoadFromFile(filepath string) (*QualificationConfig, error)

LoadFromFile loads qualification configuration from a YAML or JSON file.

func (*ConfigLoader) LoadLabelValidatorConfig

func (cl *ConfigLoader) LoadLabelValidatorConfig(filepath string) (*LabelValidatorConfig, error)

LoadLabelValidatorConfig loads label validator configuration from a file.

func (*ConfigLoader) LoadLayoutConfig

func (cl *ConfigLoader) LoadLayoutConfig(filepath string) (*LayoutConfig, error)

LoadLayoutConfig loads layout configuration from a file.

func (*ConfigLoader) Validate

func (cl *ConfigLoader) Validate(config *QualificationConfig) error

Validate validates a qualification configuration.

type DynamicLabelConfig

type DynamicLabelConfig struct {
	// FilePath is the file path in the PR to read
	FilePath string `json:"filePath" yaml:"filePath"`

	// Key is the simple YAML/JSON key to extract (mutually exclusive with JSONPath)
	Key string `json:"key,omitempty" yaml:"key,omitempty"`

	// JSONPath is the JSONPath expression to extract complex values
	JSONPath string `json:"jsonPath,omitempty" yaml:"jsonPath,omitempty"`

	// LabelName is the name of the label to create (e.g., "cd/version")
	LabelName string `json:"labelName" yaml:"labelName"`

	// Required indicates whether this extraction must succeed for qualification
	Required bool `json:"required" yaml:"required"`

	// DefaultValue is used if extraction fails and not required
	DefaultValue string `json:"defaultValue,omitempty" yaml:"defaultValue,omitempty"`

	// ValueTransform is an optional transformation to apply to extracted values
	ValueTransform string `json:"valueTransform,omitempty" yaml:"valueTransform,omitempty"`
}

DynamicLabelConfig defines configuration for dynamic label extraction.

type DynamicLabelValidator

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

DynamicLabelValidator validates PRs and extracts dynamic labels based on configuration.

func NewDynamicLabelValidator

func NewDynamicLabelValidator(
	client *github.Client,
	config *DynamicLabelValidatorConfig,
	logger Logger,
) (*DynamicLabelValidator, error)

NewDynamicLabelValidator creates a new dynamic label validator.

func (*DynamicLabelValidator) GetExtractedMetadata

func (dlv *DynamicLabelValidator) GetExtractedMetadata(ctx context.Context, pr github.PullRequest) (map[string]string, map[string]string, error)

GetExtractedMetadata extracts metadata without validation (for external use).

func (*DynamicLabelValidator) Name

func (dlv *DynamicLabelValidator) Name() string

Name returns the validator name.

func (*DynamicLabelValidator) Validate

Validate performs PR validation and dynamic label extraction.

type DynamicLabelValidatorConfig

type DynamicLabelValidatorConfig struct {
	// Extractors configuration
	Extractors []extraction.ExtractorConfig `json:"extractors" yaml:"extractors"`

	// LabelTemplates for rendering labels
	LabelTemplates []extraction.LabelTemplate `json:"labelTemplates" yaml:"labelTemplates"`

	// Timeout for extraction operations
	Timeout time.Duration `json:"timeout" yaml:"timeout"`

	// FailOnExtractionError determines if validator fails when required extraction fails
	FailOnExtractionError bool `json:"failOnExtractionError" yaml:"failOnExtractionError"`

	// CacheEnabled controls whether file caching is enabled
	CacheEnabled bool `json:"cacheEnabled" yaml:"cacheEnabled"`

	// CacheTTL is the cache time-to-live duration
	CacheTTL time.Duration `json:"cacheTTL" yaml:"cacheTTL"`

	// MaxCacheSize is the maximum number of files to cache
	MaxCacheSize int `json:"maxCacheSize" yaml:"maxCacheSize"`
}

DynamicLabelValidatorConfig configures the dynamic label validator.

func DefaultDynamicLabelConfig

func DefaultDynamicLabelConfig() *DynamicLabelValidatorConfig

DefaultDynamicLabelConfig returns a default configuration.

type FilePatternGitHubClient

type FilePatternGitHubClient interface {
	ListPRFiles(ctx context.Context, repo github.Repository, number int) ([]github.PRFile, error)
}

FilePatternGitHubClient defines the GitHub operations needed by the file pattern validator.

type FilePatternValidator

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

FilePatternValidator validates that PR file changes don't violate restrictions.

func NewFilePatternValidator

func NewFilePatternValidator(config *FilePatternValidatorConfig, githubClient FilePatternGitHubClient, logger Logger) *FilePatternValidator

NewFilePatternValidator creates a new file pattern validator with the given configuration.

func (*FilePatternValidator) Name

func (fv *FilePatternValidator) Name() string

Name returns the name of this validator.

func (*FilePatternValidator) Validate

Validate checks if PR file changes comply with configured patterns.

type FilePatternValidatorConfig

type FilePatternValidatorConfig struct {
	// RestrictedPatterns are file patterns that are not allowed to be modified
	RestrictedPatterns []string `json:"restrictedPatterns" yaml:"restrictedPatterns"`

	// AllowedPatterns are file patterns that are allowed (whitelist approach)
	AllowedPatterns []string `json:"allowedPatterns,omitempty" yaml:"allowedPatterns,omitempty"`

	// Mode determines whether to use blacklist (restricted) or whitelist (allowed) approach
	Mode string `json:"mode" yaml:"mode"` // "blacklist" or "whitelist"

	// MaxFileSize is the maximum allowed size for individual files in bytes
	MaxFileSize int64 `json:"maxFileSize,omitempty" yaml:"maxFileSize,omitempty"`
}

FilePatternValidatorConfig defines configuration for file pattern restrictions.

func DefaultFilePatternConfig

func DefaultFilePatternConfig() *FilePatternValidatorConfig

DefaultFilePatternConfig returns a file pattern configuration with common restrictions.

type GitHubClient

type GitHubClient interface {
	ListReviews(ctx context.Context, repo github.Repository, number int) ([]github.Review, error)
}

GitHubClient defines the GitHub operations needed by the approvals validator.

type LabelValidatorConfig

type LabelValidatorConfig struct {
	// RequiredLabels are labels that must be present on the PR
	RequiredLabels []string `json:"requiredLabels" yaml:"requiredLabels"`

	// ForbiddenLabels are labels that must not be present on the PR
	ForbiddenLabels []string `json:"forbiddenLabels,omitempty" yaml:"forbiddenLabels,omitempty"`

	// RequiredLabelPattern is a regex pattern that at least one label must match
	RequiredLabelPattern string `json:"requiredLabelPattern,omitempty" yaml:"requiredLabelPattern,omitempty"`
}

LabelValidatorConfig defines configuration for label validation.

type LabelsValidator

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

LabelsValidator validates that a PR has required labels.

func NewLabelsValidator

func NewLabelsValidator(config *LabelValidatorConfig, logger Logger) *LabelsValidator

NewLabelsValidator creates a new labels validator with the given configuration.

func (*LabelsValidator) Name

func (lv *LabelsValidator) Name() string

Name returns the name of this validator.

func (*LabelsValidator) Validate

func (lv *LabelsValidator) Validate(ctx context.Context, pr github.PullRequest) (Result, error)

Validate checks if the PR has all required labels.

type LayoutConfig

type LayoutConfig struct {
	// Layouts defines the supported layout patterns with their configurations
	Layouts []LayoutDefinition `json:"layouts" yaml:"layouts"`

	// StrictMode when true requires exact pattern match, when false allows partial matches
	StrictMode bool `json:"strictMode" yaml:"strictMode"`
}

LayoutConfig defines configuration for layout validation.

func DefaultLayoutConfig

func DefaultLayoutConfig() *LayoutConfig

DefaultLayoutConfig returns a layout configuration with standard patterns.

type LayoutDefinition

type LayoutDefinition struct {
	// Name is the human-readable name of this layout
	Name string `json:"name" yaml:"name"`

	// Type is the layout type (standard, tmc, etc.)
	Type LayoutType `json:"type" yaml:"type"`

	// Patterns are the file path patterns that define this layout
	// Supports placeholders like <app>, <cluster>, <env>
	Patterns []string `json:"patterns" yaml:"patterns"`

	// MaxChangedFiles limits the number of files that can be modified in this layout
	MaxChangedFiles int `json:"maxChangedFiles" yaml:"maxChangedFiles"`

	// RequiredFiles are files that must be present for this layout
	RequiredFiles []string `json:"requiredFiles,omitempty" yaml:"requiredFiles,omitempty"`

	// ForbiddenFiles are files that must not be present for this layout
	ForbiddenFiles []string `json:"forbiddenFiles,omitempty" yaml:"forbiddenFiles,omitempty"`

	// Description provides human-readable explanation of this layout
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
}

LayoutDefinition defines a specific layout pattern and its constraints.

type LayoutType

type LayoutType = domainQual.LayoutType

LayoutType is a type alias for the domain LayoutType. This maintains backward compatibility while using the domain model.

type LayoutValidator

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

LayoutValidator validates PR files against configured layout patterns.

func NewLayoutValidator

func NewLayoutValidator(config *LayoutConfig, logger Logger) *LayoutValidator

NewLayoutValidator creates a new layout validator with the given configuration.

func (*LayoutValidator) Name

func (lv *LayoutValidator) Name() string

Name returns the name of this validator.

func (*LayoutValidator) Validate

func (lv *LayoutValidator) Validate(ctx context.Context, pr github.PullRequest) (Result, error)

Validate checks if the PR files match any of the configured layout patterns.

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 validators.

type MatchResult

type MatchResult struct {
	// Matched indicates whether the pattern was matched
	Matched bool

	// Pattern is the pattern that was matched
	Pattern string

	// LayoutType is the layout type this pattern belongs to
	LayoutType LayoutType

	// MatchedFiles are the files that matched the pattern
	MatchedFiles []string

	// ExtractedVariables contains extracted placeholder values (e.g., app name)
	ExtractedVariables map[string]string
}

MatchResult represents the result of pattern matching for layout detection.

type MergeableValidator

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

MergeableValidator validates that a PR is in a mergeable state according to GitHub.

func NewMergeableValidator

func NewMergeableValidator(logger Logger) *MergeableValidator

NewMergeableValidator creates a new mergeable validator.

func (*MergeableValidator) Name

func (mv *MergeableValidator) Name() string

Name returns the name of this validator.

func (*MergeableValidator) Validate

func (mv *MergeableValidator) Validate(ctx context.Context, pr github.PullRequest) (Result, error)

Validate checks if the PR is in a mergeable state.

type QualificationConfig

type QualificationConfig struct {
	// Validators contains configuration for each validator
	Validators []ValidatorConfig

	// Strategy determines how multiple validators are combined
	Strategy CompositeStrategy

	// StopOnFirstFailure determines whether to halt on the first validation failure
	StopOnFirstFailure bool

	// DefaultTimeout is the timeout for individual validator operations
	DefaultTimeout string
}

QualificationConfig holds the complete qualification configuration.

func DefaultQualificationConfig

func DefaultQualificationConfig() *QualificationConfig

DefaultQualificationConfig returns a configuration with sensible defaults.

type QualificationEngine

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

QualificationEngine provides high-level qualification functionality.

func NewQualificationEngine

func NewQualificationEngine(validator Validator, config *QualificationConfig, logger Logger) *QualificationEngine

NewQualificationEngine creates a new qualification engine.

func (*QualificationEngine) Qualify

Qualify performs complete PR qualification including validation and dynamic label extraction.

type QualificationResult

type QualificationResult struct {
	// Qualified indicates whether the PR passed all validations
	Qualified bool

	// LayoutType is the detected layout type
	LayoutType LayoutType

	// Results contains individual validation results
	Results []Result

	// Failures contains only the failed validation results
	Failures []Result

	// Summary provides a human-readable summary of the qualification
	Summary string

	// ExtractedLabels contains dynamic labels extracted during qualification
	ExtractedLabels map[string]string

	// ExtractedMetadata contains raw metadata extracted during qualification
	ExtractedMetadata map[string]string

	// ProcessingTime is how long qualification took
	ProcessingTime time.Duration
}

QualificationResult represents the complete result of PR qualification.

func (*QualificationResult) GetFailuresByValidator

func (qr *QualificationResult) GetFailuresByValidator() map[string][]Result

GetFailuresByValidator returns failures grouped by validator name.

func (*QualificationResult) HasErrors

func (qr *QualificationResult) HasErrors() bool

HasErrors returns true if any validation failed with error severity.

func (*QualificationResult) HasFailures

func (qr *QualificationResult) HasFailures() bool

HasFailures returns true if any validation failed.

type Registry

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

Registry manages a collection of validators and provides factory methods.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new validator registry.

func (*Registry) CreateComposite

func (r *Registry) CreateComposite(names []string, strategy CompositeStrategy) (*CompositeValidator, error)

CreateComposite creates a composite validator from a list of validator names. Returns an error if any validator name is not found in the registry.

func (*Registry) Get

func (r *Registry) Get(name string) Validator

Get retrieves a validator by name. Returns nil if the validator is not found.

func (*Registry) List

func (r *Registry) List() []string

List returns the names of all registered validators.

func (*Registry) Register

func (r *Registry) Register(validator Validator) error

Register adds a validator to the registry. Returns an error if a validator with the same name is already registered.

type Result

type Result = domainQual.Result

Result is a type alias for the domain Result type. This maintains backward compatibility while using the domain model.

type Severity

type Severity = domainQual.Severity

Severity is a type alias for the domain Severity type. This maintains backward compatibility while using the domain model.

type ValidationError

type ValidationError struct {
	ValidatorName string
	Cause         error
}

ValidationError represents an error that occurred during validation.

func NewValidationError

func NewValidationError(validatorName string, cause error) *ValidationError

NewValidationError creates a new validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap allows error unwrapping.

type Validator

type Validator interface {
	// Name returns the unique name of this validator (used for configuration and logging)
	Name() string

	// Validate performs the validation check on a pull request.
	// Returns a Result indicating success/failure with detailed information.
	Validate(ctx context.Context, pr github.PullRequest) (Result, error)
}

Validator defines the interface for PR qualification validators. Each validator implements a specific check (layout, mergeable, labels, etc.).

type ValidatorConfig

type ValidatorConfig struct {
	// Name is the validator name
	Name string

	// Enabled controls whether the validator is active
	Enabled bool

	// Config contains validator-specific configuration
	Config map[string]interface{}
}

ValidatorConfig holds configuration for individual validators.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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