Documentation
¶
Overview ¶
Package github provides a comprehensive client library for interacting with GitHub's API. It implements repository management, organization operations, Actions policy enforcement, and various automation features required by the gzh-cli tool.
Key features:
- Repository cloning and synchronization
- Organization and team management
- GitHub Actions policy validation and enforcement
- Webhook handling and event processing
- Pull request and issue automation
- Release management
- Dependency version policy enforcement
The package uses GitHub's REST and GraphQL APIs, providing:
- Automatic retry with exponential backoff
- Rate limit handling
- Concurrent operations with worker pools
- Comprehensive error handling
- Metrics and logging integration
Authentication is handled via personal access tokens or GitHub Apps, with support for fine-grained permissions and OAuth scopes.
Package github provides interfaces and types for GitHub API integration. It defines contracts for HTTP operations, repository management, token validation, change logging, and confirmation services used throughout the application.
Index ¶
- Constants
- Variables
- func BulkCloneMultipleOrganizations(ctx context.Context, targetBasePath string, options BulkCloneOptions) error
- func CalculateBackoff(attempt int) time.Duration
- func Clone(ctx context.Context, targetPath string, org string, repo string) error
- func Contains(list []string, element string) bool
- func CreateGitHubProvider(config *provider.ProviderConfig) (provider.GitProvider, error)
- func DeleteCloneState(org string) error
- func GetCloneState(org string) (*synclonepkg.CloneState, error)
- func GetDefaultBranch(ctx context.Context, org string, repo string) (string, error)
- func List(ctx context.Context, org string) ([]string, error)
- func ListCloneStates() ([]synclonepkg.CloneState, error)
- func RefreshAll(ctx context.Context, targetPath string, org string, strategy string) error
- func RefreshAllOptimizedStreaming(ctx context.Context, targetPath, org, strategy, token string) error
- func RefreshAllOptimizedStreamingWithCache(ctx context.Context, targetPath, org, strategy, token string) error
- func RefreshAllResumable(ctx context.Context, targetPath, org, strategy string, ...) error
- func RefreshAllWithWorkerPool(ctx context.Context, targetPath, org, strategy string, parallel int, ...) error
- func RegisterGitHubProvider(factory *provider.ProviderFactory) error
- func ShouldRetry(resp *http.Response) bool
- type APIClient
- type APIClientConfig
- type APIError
- type ActionExecutionResult
- type ActionExecutor
- type ActionFailurePolicy
- type ActionRetryPolicy
- type ActionType
- type ActionUsageInfo
- type ActionsMarketplacePolicy
- type ActionsPermissionLevel
- type ActionsPolicy
- type ActionsPolicyEnforcer
- func (ape *ActionsPolicyEnforcer) AddValidationRule(rule PolicyValidationRule)
- func (ape *ActionsPolicyEnforcer) EnforcePolicy(ctx context.Context, policyID, organization, repository string) (*PolicyEnforcementResult, error)
- func (ape *ActionsPolicyEnforcer) ValidatePolicy(ctx context.Context, policy *ActionsPolicy, ...) ([]PolicyValidationResult, error)
- type ActionsPolicyManager
- func (apm *ActionsPolicyManager) CreatePolicy(_ context.Context, policy *ActionsPolicy) error
- func (apm *ActionsPolicyManager) DeletePolicy(_ context.Context, policyID string) error
- func (apm *ActionsPolicyManager) GetPolicy(_ context.Context, policyID string) (*ActionsPolicy, error)
- func (apm *ActionsPolicyManager) ListPolicies(_ context.Context, organization string) ([]*ActionsPolicy, error)
- func (apm *ActionsPolicyManager) UpdatePolicy(_ context.Context, policyID string, updates *ActionsPolicy) error
- type ActionsPolicyViolation
- type ActionsPolicyViolationType
- type ActionsSecuritySettings
- type ActionsTokenPermission
- type AlertThresholds
- type AllowDeletions
- type AllowForcePushes
- type AllowedActionsValidationRule
- type ApplyPoliciesRequest
- type ApplyPoliciesResult
- type ApprovalCondition
- type ApprovalEscalationRule
- type ApprovalRequirements
- type ApprovalRule
- type ApprovalStep
- type ApprovalWorkflow
- type AutoApprovalAction
- type AutoApprovalCondition
- type AutoApprovalRule
- type AutomatedTestingConfig
- type AutomationAction
- type AutomationConditions
- type AutomationEngine
- func (ae *AutomationEngine) GetActiveExecutions() map[string]*AutomationRuleExecution
- func (ae *AutomationEngine) GetMetrics() *EngineMetrics
- func (ae *AutomationEngine) ProcessEvent(ctx context.Context, event *GitHubEvent) error
- func (ae *AutomationEngine) Start(ctx context.Context) error
- func (ae *AutomationEngine) Stop(ctx context.Context) error
- type AutomationEngineConfig
- type AutomationEventProcessor
- type AutomationExecutionContext
- type AutomationRule
- type AutomationRuleExecution
- type AutomationRuleMetadata
- type AutomationRuleService
- type AutomationRuleSet
- type AutomationRuleTemplate
- type AutomationSchedule
- type BenchmarkResult
- type BlackoutPeriod
- type BranchProtection
- type BranchProtectionConfig
- type BranchProtectionData
- type BranchRestrictions
- type BreakingChangeAnalysisResult
- type BreakingChangeDetection
- type BreakingChangePolicy
- type BulkApplyOptions
- type BulkApplyResult
- type BulkCloneOptions
- type BulkCloneRequest
- type BulkCloneResult
- type BulkOperationProgress
- type BulkOperationStatus
- type BulkOperationType
- type BulkOperationsConfig
- type BulkOperationsManager
- type BulkPolicyOperation
- type BulkUpdateApprovalRule
- type BulkWebhookDeleteRequest
- type BulkWebhookRequest
- type BulkWebhookResult
- type BulkWebhookUpdateRequest
- type BusinessHours
- type CVERecord
- type CVETimeline
- type CVSSScore
- type CacheConfiguration
- type CachedGitHubClient
- func (c *CachedGitHubClient) GetCacheStats() map[string]interface{}
- func (c *CachedGitHubClient) GetDefaultBranchWithCache(ctx context.Context, org, repo string) (string, error)
- func (c *CachedGitHubClient) InvalidateOrgCache(ctx context.Context, org string) int
- func (c *CachedGitHubClient) InvalidateRepoCache(ctx context.Context, org, repo string) int
- func (c *CachedGitHubClient) ListRepositoriesWithCache(ctx context.Context, org string) ([]string, error)
- type CachedRepositoryConfig
- type CachedSyncCloneManager
- type ChangeFilter
- type ChangeLog
- func (cl *ChangeLog) GetChange(ctx context.Context, id string) (*ChangeRecord, error)
- func (cl *ChangeLog) ListChanges(ctx context.Context, filter ChangeFilter) ([]*ChangeRecord, error)
- func (cl *ChangeLog) RecordChange(ctx context.Context, change *ChangeRecord) error
- func (cl *ChangeLog) RecordRepositoryUpdate(ctx context.Context, owner, repo string, before, after *Repository, ...) error
- func (cl *ChangeLog) Rollback(ctx context.Context, request *RollbackRequest) (*RollbackResult, error)
- type ChangeLogger
- func (cl *ChangeLogger) CreateOperationContext(requestID, operation string) *operationContext
- func (cl *ChangeLogger) GetLogSummary(ctx context.Context, since time.Time) (*LogSummary, error)
- func (cl *ChangeLogger) LogBulkOperation(ctx context.Context, opCtx *operationContext, level LogLevel, operation string, ...) error
- func (cl *ChangeLogger) LogOperation(ctx context.Context, opCtx *operationContext, level LogLevel, ...) error
- func (cl *ChangeLogger) LogRepositoryChange(ctx context.Context, opCtx *operationContext, changeRecord *ChangeRecord, ...) error
- type ChangeLoggerInterface
- type ChangeRecord
- type ChangeStore
- type ChangeType
- type ChannelType
- type CloneError
- type CloneService
- type CloneServiceConfig
- type CloneStats
- type CommunicationPlan
- type CompatibilityAnalysisResult
- type CompatibilityCheckConfig
- type CompatibilityIssue
- type CompatibilityMatrixEntry
- type CompatibilityTestResult
- type ComplianceConfig
- type ComplianceFramework
- type ComplianceReport
- type ComplianceViolation
- type ConditionEvaluator
- type ConditionExplanation
- type ConditionOperator
- type ConditionType
- type ConditionValidationError
- type ConditionValidationResult
- type ConditionValidationWarning
- type ConfigMetadata
- type ConfigStorage
- type ConfigurationChange
- type ConfirmationModeType
- type ConfirmationPrompt
- type ConfirmationPromptRecord
- type ConfirmationRequest
- type ConfirmationResult
- type ConfirmationServiceInterface
- type ConflictDetectionConfig
- type ConflictResolution
- type ConstraintEvaluationResult
- type ConstraintPriority
- type CursorPagination
- type CustomMetric
- type CustomTestSuite
- type CustomValidationRule
- type DataMigrationHandling
- type DataPoint
- type DefaultPermissions
- type DependabotAllowedUpdate
- type DependabotCommitMessage
- type DependabotConfig
- type DependabotConfigManager
- func (dm *DependabotConfigManager) CreateDefaultConfig(ctx context.Context, organization, repository string, ecosystems []string) (*DependabotConfig, error)
- func (dm *DependabotConfigManager) DetectEcosystems(ctx context.Context, organization, repository string) ([]string, error)
- func (dm *DependabotConfigManager) GetDependabotConfig(ctx context.Context, organization, repository string) (*DependabotConfig, error)
- func (dm *DependabotConfigManager) GetDependabotStatus(ctx context.Context, organization, repository string) (*DependabotStatus, error)
- func (dm *DependabotConfigManager) UpdateDependabotConfig(ctx context.Context, organization, repository string, config *DependabotConfig) error
- func (dm *DependabotConfigManager) ValidateConfig(config *DependabotConfig) error
- type DependabotConfigSummary
- type DependabotError
- type DependabotErrorType
- type DependabotGroup
- type DependabotGroupAppliesTo
- type DependabotIgnoredUpdate
- type DependabotPolicyConfig
- type DependabotPolicyManager
- func (pm *DependabotPolicyManager) ApplyPolicyToOrganization(ctx context.Context, policyID, organization string) (*BulkPolicyOperation, error)
- func (pm *DependabotPolicyManager) CreatePolicy(_ context.Context, policy *DependabotPolicyConfig) error
- func (pm *DependabotPolicyManager) DeletePolicy(ctx context.Context, policyID string) error
- func (pm *DependabotPolicyManager) EvaluateRepositoryCompliance(ctx context.Context, policyID, organization, repository string) (*PolicyEvaluationResult, error)
- func (pm *DependabotPolicyManager) GenerateOrganizationReport(ctx context.Context, policyID, organization string) (*OrganizationPolicyReport, error)
- func (pm *DependabotPolicyManager) GetPolicy(_ context.Context, policyID string) (*DependabotPolicyConfig, error)
- func (pm *DependabotPolicyManager) UpdatePolicy(_ context.Context, policy *DependabotPolicyConfig) error
- type DependabotPolicyViolation
- type DependabotPolicyViolationType
- type DependabotRegistry
- type DependabotRepositoryOperationResult
- type DependabotSchedule
- type DependabotStatus
- type DependabotUpdate
- type DependabotUpdateRule
- type DependabotUpdateStatus
- type DependabotViolationStatistics
- type DependencyRiskAssessment
- type DependencyUpdate
- type DependencyUpdateRejection
- type DependencyUpdateStrategy
- type DependencyVersionAnalysis
- type DependencyVersionPolicy
- type DependencyVersionPolicyManager
- func (dvm *DependencyVersionPolicyManager) AnalyzeDependencyVersionUpdate(ctx context.Context, policyID string, ...) (*DependencyVersionAnalysis, error)
- func (dvm *DependencyVersionPolicyManager) ApplyVersionConstraints(ctx context.Context, policyID string, updates []DependencyUpdate) (*VersionConstraintApplicationResult, error)
- func (dvm *DependencyVersionPolicyManager) CreateDependencyVersionPolicy(ctx context.Context, policy *DependencyVersionPolicy) error
- type DeprecationPolicy
- type DetectedChange
- type DetectionMethod
- type DetectionRule
- type EcosystemPolicy
- type EcosystemStats
- type EcosystemVersionPolicy
- type EmergencyApprovalRule
- type EmergencyOverride
- type EngineMetrics
- type EnvironmentBranchPolicy
- type EnvironmentInfo
- type EnvironmentPolicy
- type EscalationAction
- type EscalationCondition
- type EscalationRule
- type EscalationTarget
- type EvaluationContext
- type EvaluationExplanation
- type EvaluationResult
- type EventAction
- type EventFilter
- type EventHandler
- type EventMetrics
- type EventProcessingResult
- type EventProcessor
- type EventStorage
- type EventType
- type EventWebhookServer
- type ExclusionType
- type ExecutionFilter
- type ExecutionStatus
- type ExecutionTask
- type ExecutionTriggerType
- type FileStore
- func (fs *FileStore) Delete(ctx context.Context, id string) error
- func (fs *FileStore) Get(ctx context.Context, id string) (*ChangeRecord, error)
- func (fs *FileStore) GetStats(ctx context.Context) (map[string]interface{}, error)
- func (fs *FileStore) GetStorePath() string
- func (fs *FileStore) List(ctx context.Context, filter ChangeFilter) ([]*ChangeRecord, error)
- func (fs *FileStore) Store(ctx context.Context, record *ChangeRecord) error
- type FileSystemInterface
- type GitCommandInterface
- type GitHubAPIClient
- func (c *GitHubAPIClient) GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)
- func (c *GitHubAPIClient) GetRateLimit(ctx context.Context) (*RateLimit, error)
- func (c *GitHubAPIClient) GetRepository(ctx context.Context, owner, repo string) (*RepositoryInfo, error)
- func (c *GitHubAPIClient) GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
- func (c *GitHubAPIClient) ListOrganizationRepositories(ctx context.Context, org string) ([]RepositoryInfo, error)
- func (c *GitHubAPIClient) SetToken(ctx context.Context, token string) error
- func (c *GitHubAPIClient) UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
- type GitHubAPIClientAdapter
- func (a *GitHubAPIClientAdapter) GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)
- func (a *GitHubAPIClientAdapter) GetRateLimit(ctx context.Context) (*RateLimit, error)
- func (a *GitHubAPIClientAdapter) GetRepository(ctx context.Context, owner, repo string) (*RepositoryInfo, error)
- func (a *GitHubAPIClientAdapter) GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
- func (a *GitHubAPIClientAdapter) ListOrganizationRepositories(ctx context.Context, org string) ([]RepositoryInfo, error)
- func (a *GitHubAPIClientAdapter) SetToken(ctx context.Context, token string) error
- func (a *GitHubAPIClientAdapter) UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
- type GitHubCloneService
- func (s *GitHubCloneService) CloneOrganization(ctx context.Context, orgName, targetPath, strategy string) error
- func (s *GitHubCloneService) CloneRepository(ctx context.Context, repo RepositoryInfo, targetPath, strategy string) error
- func (s *GitHubCloneService) GetSupportedStrategies(ctx context.Context) ([]string, error)
- func (s *GitHubCloneService) RefreshAll(ctx context.Context, targetPath, orgName, strategy string) error
- func (s *GitHubCloneService) SetStrategy(ctx context.Context, strategy string) error
- type GitHubCloner
- type GitHubEvent
- type GitHubFactoryConfig
- type GitHubManager
- type GitHubOrganization
- type GitHubProvider
- func (g *GitHubProvider) ArchiveRepository(ctx context.Context, id string) error
- func (g *GitHubProvider) Authenticate(ctx context.Context, creds provider.Credentials) error
- func (g *GitHubProvider) CloneRepository(ctx context.Context, repo provider.Repository, target string, ...) error
- func (g *GitHubProvider) CreateRelease(ctx context.Context, repoID string, req provider.CreateReleaseRequest) (*provider.Release, error)
- func (g *GitHubProvider) CreateRepository(ctx context.Context, req provider.CreateRepoRequest) (*provider.Repository, error)
- func (g *GitHubProvider) CreateWebhook(ctx context.Context, repoID string, webhook provider.CreateWebhookRequest) (*provider.Webhook, error)
- func (g *GitHubProvider) DeleteRelease(ctx context.Context, repoID, releaseID string) error
- func (g *GitHubProvider) DeleteReleaseAsset(ctx context.Context, repoID, assetID string) error
- func (g *GitHubProvider) DeleteRepository(ctx context.Context, id string) error
- func (g *GitHubProvider) DeleteWebhook(ctx context.Context, repoID, webhookID string) error
- func (g *GitHubProvider) DownloadReleaseAsset(ctx context.Context, repoID, assetID string) ([]byte, error)
- func (g *GitHubProvider) ForkRepository(ctx context.Context, id string, opts provider.ForkOptions) (*provider.Repository, error)
- func (g *GitHubProvider) GetCapabilities() []provider.Capability
- func (g *GitHubProvider) GetEvent(ctx context.Context, eventID string) (*provider.Event, error)
- func (g *GitHubProvider) GetMetrics(ctx context.Context) (*provider.ProviderMetrics, error)
- func (g *GitHubProvider) GetRateLimit(ctx context.Context) (*provider.RateLimit, error)
- func (g *GitHubProvider) GetRelease(ctx context.Context, repoID, releaseID string) (*provider.Release, error)
- func (g *GitHubProvider) GetReleaseByTag(ctx context.Context, repoID, tagName string) (*provider.Release, error)
- func (g *GitHubProvider) GetRepository(ctx context.Context, id string) (*provider.Repository, error)
- func (g *GitHubProvider) GetWebhook(ctx context.Context, repoID, webhookID string) (*provider.Webhook, error)
- func (g *GitHubProvider) HealthCheck(ctx context.Context) (*provider.HealthStatus, error)
- func (g *GitHubProvider) ListEvents(ctx context.Context, opts provider.EventListOptions) ([]provider.Event, error)
- func (g *GitHubProvider) ListReleaseAssets(ctx context.Context, repoID, releaseID string) ([]provider.Asset, error)
- func (g *GitHubProvider) ListReleases(ctx context.Context, repoID string, opts provider.ListReleasesOptions) (*provider.ReleaseList, error)
- func (g *GitHubProvider) ListRepositories(ctx context.Context, opts provider.ListOptions) (*provider.RepositoryList, error)
- func (g *GitHubProvider) ListWebhooks(ctx context.Context, repoID string) ([]provider.Webhook, error)
- func (g *GitHubProvider) ProcessEvent(ctx context.Context, event provider.Event) error
- func (g *GitHubProvider) RegisterEventHandler(eventType string, handler provider.EventHandler) error
- func (g *GitHubProvider) SearchRepositories(ctx context.Context, query provider.SearchQuery) (*provider.SearchResult, error)
- func (g *GitHubProvider) StreamEvents(ctx context.Context, opts provider.StreamOptions) (<-chan provider.Event, error)
- func (g *GitHubProvider) TestWebhook(ctx context.Context, repoID, webhookID string) (*provider.WebhookTestResult, error)
- func (g *GitHubProvider) UnarchiveRepository(ctx context.Context, id string) error
- func (g *GitHubProvider) UpdateRelease(ctx context.Context, repoID, releaseID string, ...) (*provider.Release, error)
- func (g *GitHubProvider) UpdateRepository(ctx context.Context, id string, updates provider.UpdateRepoRequest) (*provider.Repository, error)
- func (g *GitHubProvider) UpdateWebhook(ctx context.Context, repoID, webhookID string, ...) (*provider.Webhook, error)
- func (g *GitHubProvider) UploadReleaseAsset(ctx context.Context, repoID string, req provider.UploadAssetRequest) (*provider.Asset, error)
- func (g *GitHubProvider) ValidateToken(ctx context.Context) (*provider.TokenInfo, error)
- func (g *GitHubProvider) ValidateWebhookURL(ctx context.Context, url string) error
- type GitHubProviderFactory
- type GitHubRepository
- type GitHubService
- type GitHubServiceConfig
- type GitHubServiceContainer
- type GitHubTokenValidator
- func (v *GitHubTokenValidator) GetRequiredScopes(ctx context.Context, operation string) ([]string, error)
- func (v *GitHubTokenValidator) ValidateForOperation(ctx context.Context, token, operation string) error
- func (v *GitHubTokenValidator) ValidateForRepository(ctx context.Context, token, owner, repo string) error
- func (v *GitHubTokenValidator) ValidateToken(ctx context.Context, token string) (*TokenInfoRecord, error)
- type GitHubUser
- type HTTPClient
- type HTTPClientAdapter
- func (a *HTTPClientAdapter) Delete(ctx context.Context, url string) (*http.Response, error)
- func (a *HTTPClientAdapter) Do(ctx context.Context, req *http.Request) (*http.Response, error)
- func (a *HTTPClientAdapter) Get(ctx context.Context, url string) (*http.Response, error)
- func (a *HTTPClientAdapter) Patch(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
- func (a *HTTPClientAdapter) Post(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
- func (a *HTTPClientAdapter) Put(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
- type HTTPClientInterface
- type HealthCheck
- type ImpactLevel
- type IntegrationTestingConfig
- type JSONPathValidationResult
- type Job
- type JobAuditInfo
- type LicenseCompatibilityResult
- type LicenseRestriction
- type ListOptions
- type LogFilters
- type LogFormat
- type LogLevel
- type LogLevelType
- type LogOperationRecord
- type LogSummary
- type Logger
- type LoggerOptions
- type ManualRollbackProcedure
- type ManualTestingItem
- type MatchOperator
- type MatrixTestingConfig
- type MemoryMonitor
- type MemoryPool
- type MemoryPressureLevel
- type MemoryStats
- type MemoryWatcher
- type MetricsTrackingConfig
- type MigrationRequest
- type MigrationResult
- type MitigationStrategy
- type NotificationChannel
- type NotificationConfig
- type NotificationRecipient
- type NotificationSettings
- type OperationRecord
- type OperationResultStatus
- type OptimizedCloneConfig
- type OptimizedSyncCloneManager
- type OrganizationInfo
- type OrganizationMetrics
- type OrganizationPolicyReport
- type OrganizationPolicySummary
- type OrganizationWebhookConfig
- type OrganizationWebhookSettings
- type PackageInfo
- type PayloadMatchExplanation
- type PayloadMatchResult
- type PayloadMatcher
- type PerformanceImpactAnalysis
- type PerformanceRequirements
- type PermissionLevel
- type PermissionLevelValidationRule
- type PermissionsConfig
- type PlannedAction
- type PolicyApplicationPreview
- type PolicyApplicationResult
- type PolicyApplicationSummary
- type PolicyCache
- type PolicyChange
- type PolicyConflict
- type PolicyEnforcementResult
- type PolicyEvaluationResult
- type PolicyRecommendation
- type PolicyRecommendationType
- type PolicySeverity
- type PolicyTrendAnalysis
- type PolicyValidationResult
- type PolicyValidationRule
- type PolicyViolation
- type PolicyViolationSeverity
- type PolicyViolationStatus
- type PolicyViolationType
- type ProductInfo
- type ProtectionRule
- type QualityGate
- type RateLimit
- type RateLimitConfig
- type RateLimitInfo
- type RateLimiter
- type RecommendationImpact
- type RecommendationPriority
- type RecommendedAction
- type Reference
- type RegexValidationResult
- type RegressionTestingConfig
- type ReleaseSchedule
- type ReleaseWindow
- type RepoConfigClient
- func (c *RepoConfigClient) ApplyConfigurationToOrganization(ctx context.Context, org string, config *RepositoryConfig, ...) (*BulkApplyResult, error)
- func (c *RepoConfigClient) CollectRepositoryStates(ctx context.Context, org string) (map[string]RepositoryStateData, error)
- func (c *RepoConfigClient) DeleteBranchProtection(ctx context.Context, owner, repo, branch string) error
- func (c *RepoConfigClient) GetBranchProtection(ctx context.Context, owner, repo, branch string) (*BranchProtection, error)
- func (c *RepoConfigClient) GetRateLimitStatus() (int, int, time.Time)
- func (c *RepoConfigClient) GetRepository(ctx context.Context, owner, repo string) (*Repository, error)
- func (c *RepoConfigClient) GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
- func (c *RepoConfigClient) GetRepositoryPermissions(ctx context.Context, owner, repo string) (map[string]string, map[string]string, error)
- func (c *RepoConfigClient) ListRepositories(ctx context.Context, org string, options *ListOptions) ([]*Repository, error)
- func (c *RepoConfigClient) SetLogger(logger *ChangeLogger)
- func (c *RepoConfigClient) SetTimeout(timeout time.Duration)
- func (c *RepoConfigClient) UpdateBranchProtection(ctx context.Context, owner, repo, branch string, protection *BranchProtection) (*BranchProtection, error)
- func (c *RepoConfigClient) UpdateBranchProtectionConfig(ctx context.Context, owner, repo, branch string, ...) error
- func (c *RepoConfigClient) UpdateRepository(ctx context.Context, owner, repo string, update *RepositoryUpdate) (*Repository, error)
- func (c *RepoConfigClient) UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
- func (c *RepoConfigClient) UpdateRepositoryConfigurationWithConfirmation(ctx context.Context, owner, repo string, config *RepositoryConfig, ...) error
- func (c *RepoConfigClient) UpdateRepositoryPermissions(ctx context.Context, owner, repo string, perms PermissionsConfig) error
- type RepoConfigSettings
- type RepoInfo
- type Repository
- type RepositoryActionsState
- type RepositoryConfig
- type RepositoryEvaluationExplanation
- type RepositoryFilters
- type RepositoryInfo
- type RepositoryOperationResult
- type RepositoryStateData
- type RepositoryStream
- type RepositoryUpdate
- type RepositoryWebhookInfo
- type RequestMetrics
- type RequiredConversationResolution
- type RequiredPermission
- type RequiredPullRequestReviews
- type RequiredStatusChecks
- type Requirement
- type ResilientGitHubClient
- func (c *ResilientGitHubClient) Close()
- func (c *ResilientGitHubClient) GetDefaultBranch(ctx context.Context, org, repo string) (string, error)
- func (c *ResilientGitHubClient) GetRateLimit(ctx context.Context) (*RateLimitInfo, error)
- func (c *ResilientGitHubClient) GetStats() map[string]interface{}
- func (c *ResilientGitHubClient) ListRepositories(ctx context.Context, org string) ([]string, error)
- func (c *ResilientGitHubClient) SetBaseURL(baseURL string)
- func (c *ResilientGitHubClient) SetToken(token string)
- type ResponseTimeConfig
- type ResumableCloneManager
- type RetryableError
- type ReviewNote
- type RiskAssessment
- type RiskFactor
- type RiskLevel
- type RiskLevelType
- type RollbackNotificationPlan
- type RollbackPlan
- type RollbackPolicy
- type RollbackRequest
- type RollbackResult
- type RollbackStep
- type RollbackTrigger
- type RuleFilter
- type RuleManager
- func (rm *RuleManager) CancelExecution(ctx context.Context, executionID string) error
- func (rm *RuleManager) CreateRule(ctx context.Context, rule *AutomationRule) error
- func (rm *RuleManager) CreateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
- func (rm *RuleManager) CreateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
- func (rm *RuleManager) DeleteRule(ctx context.Context, org, ruleID string) error
- func (rm *RuleManager) DeleteRuleSet(ctx context.Context, org, setID string) error
- func (rm *RuleManager) DeleteTemplate(ctx context.Context, templateID string) error
- func (rm *RuleManager) DisableRule(ctx context.Context, org, ruleID string) error
- func (rm *RuleManager) DryRunRule(ctx context.Context, ruleID string, event *GitHubEvent) (*RuleTestResult, error)
- func (rm *RuleManager) EnableRule(ctx context.Context, org, ruleID string) error
- func (rm *RuleManager) EvaluateConditions(ctx context.Context, rule *AutomationRule, event *GitHubEvent) (bool, error)
- func (rm *RuleManager) ExecuteRule(ctx context.Context, rule *AutomationRule, ...) (*AutomationRuleExecution, error)
- func (rm *RuleManager) GetExecution(ctx context.Context, executionID string) (*AutomationRuleExecution, error)
- func (rm *RuleManager) GetRule(ctx context.Context, org, ruleID string) (*AutomationRule, error)
- func (rm *RuleManager) GetRuleSet(ctx context.Context, org, setID string) (*AutomationRuleSet, error)
- func (rm *RuleManager) GetTemplate(ctx context.Context, templateID string) (*AutomationRuleTemplate, error)
- func (rm *RuleManager) InstantiateTemplate(ctx context.Context, templateID string, variables map[string]interface{}) (*AutomationRule, error)
- func (rm *RuleManager) ListExecutions(ctx context.Context, org string, filter *ExecutionFilter) ([]*AutomationRuleExecution, error)
- func (rm *RuleManager) ListRuleSets(ctx context.Context, org string) ([]*AutomationRuleSet, error)
- func (rm *RuleManager) ListRules(ctx context.Context, org string, filter *RuleFilter) ([]*AutomationRule, error)
- func (rm *RuleManager) ListTemplates(ctx context.Context, category string) ([]*AutomationRuleTemplate, error)
- func (rm *RuleManager) TestRule(ctx context.Context, rule *AutomationRule, testEvent *GitHubEvent) (*RuleTestResult, error)
- func (rm *RuleManager) UpdateRule(ctx context.Context, rule *AutomationRule) error
- func (rm *RuleManager) UpdateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
- func (rm *RuleManager) UpdateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
- func (rm *RuleManager) ValidateRule(ctx context.Context, rule *AutomationRule) (*RuleValidationResult, error)
- type RuleStorage
- type RuleTestResult
- type RuleValidationError
- type RuleValidationResult
- type RuleValidationWarning
- type RunnerInfo
- type RunnerPolicy
- type RunnerPolicyValidationRule
- type RunnerType
- type ScheduleType
- type SecretInfo
- type SecretPolicyValidationRule
- type SecretRotationPolicy
- type SecretVisibility
- type SecretsPolicy
- type SecurityAdvisoryInfo
- type SecurityImpactAnalysis
- type SecurityIssueSeverity
- type SecurityPolicySettings
- type SecurityRiskLevel
- type SecuritySettingsValidationRule
- type SecurityUpdateDecision
- type SecurityUpdatePolicy
- type SecurityUpdatePolicyManager
- func (sm *SecurityUpdatePolicyManager) CreateSecurityPolicy(ctx context.Context, policy *SecurityUpdatePolicy) error
- func (sm *SecurityUpdatePolicyManager) EvaluateSecurityUpdate(ctx context.Context, policyID string, update *SecurityUpdateStatus) (*SecurityUpdateDecision, error)
- func (sm *SecurityUpdatePolicyManager) ProcessSecurityUpdates(ctx context.Context, organization string) (*SecurityUpdateProcessResult, error)
- type SecurityUpdateProcessResult
- type SecurityUpdateStatus
- type SelfHostedRunnerPolicy
- type SemverParser
- type SensitiveChange
- type SeverityThreshold
- type SeverityThresholdConfig
- type SimpleCloneService
- func (s *SimpleCloneService) CloneOrganization(ctx context.Context, orgName, targetPath, strategy string) error
- func (s *SimpleCloneService) CloneRepository(ctx context.Context, repo RepositoryInfo, targetPath, strategy string) error
- func (s *SimpleCloneService) GetSupportedStrategies(ctx context.Context) ([]string, error)
- func (s *SimpleCloneService) RefreshAll(ctx context.Context, targetPath, orgName, strategy string) error
- func (s *SimpleCloneService) SetStrategy(ctx context.Context, strategy string) error
- type Step
- type StepAuditInfo
- type StreamMetadata
- type StreamingClient
- type StreamingConfig
- type StreamingRateLimiter
- type StreamingRepository
- type SyncCloneStats
- type SyncResult
- type TeamPermission
- type TemplateExample
- type TemplateStorage
- type TemplateVariable
- type TestDataRequirements
- type TestEnvironment
- type TestResults
- type TestSuiteConfiguration
- type TestingRecommendation
- type TestingRequirements
- type ThresholdConfig
- type TimeEvaluationExplanation
- type TimeRange
- type TimelinePhase
- type TokenAwareGitHubClient
- func (c *TokenAwareGitHubClient) GetCurrentToken() (string, error)
- func (c *TokenAwareGitHubClient) GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)
- func (c *TokenAwareGitHubClient) GetOrganization(ctx context.Context, org string) (*GitHubOrganization, error)
- func (c *TokenAwareGitHubClient) GetRateLimit(ctx context.Context) (*RateLimitInfo, error)
- func (c *TokenAwareGitHubClient) GetRepository(ctx context.Context, owner, repo string) (*GitHubRepository, error)
- func (c *TokenAwareGitHubClient) GetTokenStatus() (map[string]interface{}, error)
- func (c *TokenAwareGitHubClient) GetUser(ctx context.Context) (*GitHubUser, error)
- func (c *TokenAwareGitHubClient) ListRepositories(ctx context.Context, owner string, page, perPage int) ([]*GitHubRepository, error)
- func (c *TokenAwareGitHubClient) RefreshToken(ctx context.Context) error
- func (c *TokenAwareGitHubClient) Start(ctx context.Context) error
- func (c *TokenAwareGitHubClient) Stop()
- func (c *TokenAwareGitHubClient) ValidateTokenPermissions(ctx context.Context, requiredScopes []string) error
- type TokenAwareGitHubClientConfig
- type TokenInfo
- type TokenInfoRecord
- type TokenRateLimitInfo
- type TokenValidator
- func (tv *TokenValidator) GetPermissionHelp() map[string]string
- func (tv *TokenValidator) ValidateForOperation(ctx context.Context, operation string) (*ValidationResult, error)
- func (tv *TokenValidator) ValidateForRepository(ctx context.Context, owner, repo string, operation string) (*ValidationResult, error)
- func (tv *TokenValidator) ValidateToken(ctx context.Context) (*ValidationResult, error)
- type TokenValidatorInterface
- type TrendData
- type TrendDirection
- type TrendForecast
- type UpdateFrequency
- type UpdatePriority
- type UpdateStatus
- type UpdateTimeline
- type User
- type UserInfo
- type UserPermission
- type UserTeamRestrictions
- type ValidationConfig
- type ValidationResult
- type ValidatorRateLimitInfo
- type VendorInfo
- type VersionApprovalRule
- type VersionConstraintApplicationResult
- type VersionConstraintCheckResult
- type VersionConstraintEngine
- type VersionConstraintException
- type VersionConstraintRule
- type VersionNotificationChannel
- type VersionPolicyNotificationConfig
- type VersionRange
- type VersionUpdateApprovalRequirements
- type ViolationStatistics
- type VulnerabilityDatabase
- type VulnerabilityExclusion
- type VulnerabilityRecord
- type VulnerabilitySeverity
- type WebhookAction
- type WebhookAlert
- type WebhookAlertSeverity
- type WebhookAlertType
- type WebhookConditions
- type WebhookConfig
- type WebhookConfigTemplate
- type WebhookConfigurationService
- type WebhookCreateRequest
- type WebhookDefaults
- type WebhookDelivery
- type WebhookDiscrepancy
- type WebhookHealthCheck
- type WebhookHealthStatus
- type WebhookInfo
- type WebhookInventory
- type WebhookInventorySummary
- type WebhookListOptions
- type WebhookMetrics
- type WebhookMigrationResult
- type WebhookMonitor
- func (wm *WebhookMonitor) AcknowledgeAlert(alertID string) error
- func (wm *WebhookMonitor) AddWebhook(webhook *WebhookStatus)
- func (wm *WebhookMonitor) GetActiveAlerts() []WebhookAlert
- func (wm *WebhookMonitor) GetAllWebhookStatuses() map[string]*WebhookStatus
- func (wm *WebhookMonitor) GetMetrics() *WebhookMetrics
- func (wm *WebhookMonitor) GetWebhookStatus(webhookID string) (*WebhookStatus, error)
- func (wm *WebhookMonitor) Start(ctx context.Context) error
- func (wm *WebhookMonitor) Stop(ctx context.Context) error
- type WebhookMonitorConfig
- type WebhookOperationResult
- type WebhookPolicy
- type WebhookPolicyRule
- type WebhookSelector
- type WebhookService
- type WebhookStatus
- type WebhookStatusMetrics
- type WebhookTemplate
- type WebhookTestResult
- type WebhookUpdateRequest
- type WebhookValidationError
- type WebhookValidationResult
- type WebhookValidationWarning
- type WindowNotificationSettings
- type WorkflowAuditResult
- type WorkflowAuditSummary
- type WorkflowAuditor
- type WorkflowFile
- type WorkflowFileAudit
- type WorkflowInfo
- type WorkflowIssueType
- type WorkflowPermissionUsage
- type WorkflowPermissions
- type WorkflowPermissionsValidationRule
- type WorkflowSecurityIssue
Examples ¶
Constants ¶
const ( EcosystemNPM = "npm" EcosystemPip = "pip" EcosystemBundler = "bundler" EcosystemGradle = "gradle" EcosystemMaven = "maven" EcosystemComposer = "composer" EcosystemNuGet = "nuget" EcosystemCargoRust = "cargo" EcosystemGoModules = "gomod" EcosystemDockerfile = "docker" EcosystemGitSubmodule = "gitsubmodule" EcosystemGitHubActions = "github-actions" EcosystemTerraform = "terraform" EcosystemElm = "elm" EcosystemMix = "mix" EcosystemPub = "pub" EcosystemSwift = "swift" )
Supported package ecosystems.
const ( IntervalDaily = "daily" IntervalWeekly = "weekly" IntervalMonthly = "monthly" )
Update intervals.
const ( UpdateTypeAll = "all" UpdateTypeSecurity = "security" UpdateTypeVersionUpdate = "version-update:semver-major" UpdateTypeVersionMinor = "version-update:semver-minor" UpdateTypeVersionPatch = "version-update:semver-patch" )
Update types.
const ( VersioningStrategyAuto = "auto" VersioningStrategyLockfileOnly = "lockfile-only" VersioningStrategyWiden = "widen" VersioningStrategyIncrease = "increase" VersioningStrategyIncreaseIfNecessary = "increase-if-necessary" )
Versioning strategies.
Variables ¶
var OperationRequirements = map[string][]RequiredPermission{ "repository_read": { {Scope: "repo", Level: PermissionRead, Description: "Read repository information", Optional: false}, }, "repository_write": { {Scope: "repo", Level: PermissionWrite, Description: "Modify repository settings", Optional: false}, }, "organization_read": { {Scope: "read:org", Level: PermissionRead, Description: "Read organization information", Optional: false}, }, "organization_admin": { {Scope: "admin:org", Level: PermissionAdmin, Description: "Administer organization", Optional: false}, }, "bulk_operations": { {Scope: "repo", Level: PermissionWrite, Description: "Modify multiple repositories", Optional: false}, {Scope: "admin:org", Level: PermissionAdmin, Description: "Access organization repositories", Optional: false}, }, }
OperationRequirements defines required permissions for different operations.
Functions ¶
func BulkCloneMultipleOrganizations ¶
func BulkCloneMultipleOrganizations(ctx context.Context, targetBasePath string, options BulkCloneOptions, ) error
BulkCloneMultipleOrganizations clones repositories from multiple organizations using worker pools.
func CalculateBackoff ¶
CalculateBackoff calculates exponential backoff with jitter.
func Clone ¶
Clone downloads a GitHub repository to the specified local path. It performs a git clone operation using the repository's HTTPS URL. The repository is cloned into a subdirectory named after the repository within the targetPath directory.
Parameters:
- ctx: Context for operation cancellation and timeout control
- targetPath: Local directory path where the repository will be cloned
- org: GitHub organization or user name
- repo: Repository name
Returns an error if the clone operation fails due to network issues, authentication problems, or local file system errors.
Example ¶
ExampleClone demonstrates how to clone a GitHub repository to a local directory.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/Gizzahub/gzh-cli/pkg/github"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// Create a temporary directory for cloning
tempDir := "/tmp/github-clone-example"
_ = os.MkdirAll(tempDir, 0o755)
defer func() { _ = os.RemoveAll(tempDir) }()
// Clone a repository
err := github.Clone(ctx, tempDir, "octocat", "Hello-World")
if err != nil {
log.Printf("Error cloning repository: %v", err)
return
}
fmt.Println("Repository cloned successfully")
}
Output: Repository cloned successfully
func CreateGitHubProvider ¶
func CreateGitHubProvider(config *provider.ProviderConfig) (provider.GitProvider, error)
CreateGitHubProvider creates a new GitHub provider instance from configuration.
func DeleteCloneState ¶
DeleteCloneState removes the state file for an organization.
func GetCloneState ¶
func GetCloneState(org string) (*synclonepkg.CloneState, error)
GetCloneState returns the current clone state for an organization.
func GetDefaultBranch ¶
GetDefaultBranch retrieves the default branch name for a GitHub repository. It makes an authenticated HTTP GET request to the GitHub API to fetch repository information.
Parameters:
- ctx: Context for request cancellation and timeout control
- org: GitHub organization or user name
- repo: Repository name
Returns the default branch name (e.g., "main", "master") or an error if the repository doesn't exist, access is denied, or the API request fails.
Example ¶
ExampleGetDefaultBranch demonstrates how to retrieve the default branch of a GitHub repository.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/Gizzahub/gzh-cli/pkg/github"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Get default branch for a repository
branch, err := github.GetDefaultBranch(ctx, "octocat", "Hello-World")
if err != nil {
log.Printf("Error getting default branch: %v", err)
return
}
fmt.Printf("Default branch: %s", branch)
}
Output: Default branch: master
func List ¶
List retrieves all repository names for a GitHub organization. This is a convenience function that returns only repository names for backward compatibility.
Parameters:
- ctx: Context for request cancellation and timeout control
- org: GitHub organization name
Returns a slice of repository names or an error if the organization doesn't exist, access is denied, or the API request fails.
Example ¶
ExampleList demonstrates how to list all repositories in a GitHub organization.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/Gizzahub/gzh-cli/pkg/github"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// List all repositories in an organization
repos, err := github.List(ctx, "github")
if err != nil {
log.Printf("Error listing repositories: %v", err)
return
}
fmt.Printf("Found %d repositories", len(repos))
if len(repos) > 0 {
fmt.Printf("\nFirst repository: %s", repos[0])
}
}
Output: Found repositories in organization
func ListCloneStates ¶
func ListCloneStates() ([]synclonepkg.CloneState, error)
ListCloneStates returns all saved clone states.
func RefreshAll ¶
RefreshAll synchronizes the repositories in the targetPath with the repositories in the given organization. strategy can be "reset" (default), "pull", or "fetch"
Note: For better performance with large numbers of repositories, consider using RefreshAllOptimizedStreaming for organizations with >1000 repositories, which provides streaming API, memory management, and better resource control.
func RefreshAllOptimizedStreaming ¶
func RefreshAllOptimizedStreaming(ctx context.Context, targetPath, org, strategy, token string) error
RefreshAllOptimizedStreaming performs optimized bulk repository refresh using streaming API and memory management This is the recommended method for large-scale organization cloning (>1000 repositories).
func RefreshAllOptimizedStreamingWithCache ¶
func RefreshAllOptimizedStreamingWithCache(ctx context.Context, targetPath, org, strategy, token string) error
RefreshAllOptimizedStreamingWithCache is the cached version of the streaming API - DISABLED (cache package removed) Simple implementation without external cache dependency.
func RefreshAllResumable ¶
func RefreshAllResumable(ctx context.Context, targetPath, org, strategy string, parallel, maxRetries int, resume bool, progressMode string) error
RefreshAllResumable is a convenience function for resumable cloning.
func RefreshAllWithWorkerPool ¶
func RefreshAllWithWorkerPool(ctx context.Context, targetPath, org, strategy string, parallel int, maxRetries int) error
RefreshAllWithWorkerPoolWrapper provides a drop-in replacement for the original RefreshAll.
func RegisterGitHubProvider ¶
func RegisterGitHubProvider(factory *provider.ProviderFactory) error
RegisterGitHubProvider registers the GitHub provider with a factory.
func ShouldRetry ¶
ShouldRetry determines if a response indicates we should retry.
Types ¶
type APIClient ¶
type APIClient interface {
// Repository operations
GetRepository(ctx context.Context, owner, repo string) (*RepositoryInfo, error)
ListOrganizationRepositories(ctx context.Context, org string) ([]RepositoryInfo, error)
GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)
// Authentication and rate limiting
SetToken(ctx context.Context, token string) error
GetRateLimit(ctx context.Context) (*RateLimit, error)
// Repository configuration
GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
}
APIClient defines the interface for GitHub API operations.
func NewAPIClient ¶
func NewAPIClient(config *APIClientConfig, httpClient HTTPClientInterface, logger Logger) APIClient
NewAPIClient creates a new GitHub API client with dependencies.
type APIClientConfig ¶
type APIClientConfig struct {
BaseURL string
Token string
Timeout time.Duration
UserAgent string
RetryCount int
}
APIClientConfig holds configuration for GitHub API client.
func DefaultAPIClientConfig ¶
func DefaultAPIClientConfig() *APIClientConfig
DefaultAPIClientConfig returns default configuration.
type APIError ¶
type APIError struct {
Message string `json:"message"`
DocumentationURL string `json:"documentation_url"`
StatusCode int `json:"-"`
}
APIError represents a GitHub API error response.
type ActionExecutionResult ¶
type ActionExecutionResult struct {
ActionID string `json:"actionId"`
ActionType ActionType `json:"actionType"`
Status ExecutionStatus `json:"status"`
StartedAt time.Time `json:"startedAt"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
Result map[string]interface{} `json:"result,omitempty"`
Error string `json:"error,omitempty"`
RetryCount int `json:"retryCount,omitempty"`
}
ActionExecutionResult represents the result of executing a single action.
type ActionExecutor ¶
type ActionExecutor interface {
ExecuteAction(ctx context.Context, action *AutomationAction, context *AutomationExecutionContext) (*ActionExecutionResult, error)
ValidateAction(ctx context.Context, action *AutomationAction) error
GetSupportedActions() []ActionType
}
ActionExecutor defines the interface for executing automation actions.
type ActionFailurePolicy ¶
type ActionFailurePolicy string
ActionFailurePolicy defines what to do when an action fails.
const ( ActionFailurePolicyStop ActionFailurePolicy = "stop" // Stop processing remaining actions ActionFailurePolicyContinue ActionFailurePolicy = "continue" // Continue with remaining actions ActionFailurePolicyRetry ActionFailurePolicy = "retry" // Retry the failed action ActionFailurePolicySkip ActionFailurePolicy = "skip" // Skip and mark as failed )
type ActionRetryPolicy ¶
type ActionRetryPolicy struct {
MaxRetries int `json:"maxRetries" yaml:"maxRetries"`
RetryInterval time.Duration `json:"retryInterval" yaml:"retryInterval"`
BackoffFactor float64 `json:"backoffFactor,omitempty" yaml:"backoffFactor,omitempty"`
MaxInterval time.Duration `json:"maxInterval,omitempty" yaml:"maxInterval,omitempty"`
}
ActionRetryPolicy defines retry behavior for failed actions.
type ActionType ¶
type ActionType string
ActionType defines the type of action to be executed.
const ( // Webhook actions. ActionTypeWebhook ActionType = "webhook" ActionTypeHTTPRequest ActionType = "http_request" // GitHub API actions. ActionTypeCreateIssue ActionType = "create_issue" ActionTypeCreatePR ActionType = "create_pr" ActionTypeAddLabel ActionType = "add_label" ActionTypeRemoveLabel ActionType = "remove_label" ActionTypeAssignReviewer ActionType = "assign_reviewer" ActionTypeMergePR ActionType = "merge_pr" ActionTypeClosePR ActionType = "close_pr" ActionTypeCloseIssue ActionType = "close_issue" // Repository actions. ActionTypeCreateBranch ActionType = "create_branch" ActionTypeDeleteBranch ActionType = "delete_branch" ActionTypeProtectBranch ActionType = "protect_branch" ActionTypeCreateTag ActionType = "create_tag" ActionTypeCreateRelease ActionType = "create_release" // Notification actions. ActionTypeSlackMessage ActionType = "slack_message" ActionTypeTeamsMessage ActionType = "teams_message" ActionTypeEmail ActionType = "email" ActionTypeSMS ActionType = "sms" // Workflow actions. ActionTypeTriggerWorkflow ActionType = "trigger_workflow" ActionTypeRunScript ActionType = "run_script" ActionTypeDeployment ActionType = "deployment" // Custom actions. ActionTypeCustom ActionType = "custom" )
const ( ActionTypeSecurityApprove ActionType = "security_approve" ActionTypeSecurityMerge ActionType = "security_merge" ActionTypeSecurityNotify ActionType = "security_notify" ActionTypeSecurityTest ActionType = "security_test" ActionTypeSecurityCreateTicket ActionType = "security_create_ticket" ActionTypeSecuritySchedule ActionType = "security_schedule" )
Security-specific action types (extending ActionType from automation_rule.go).
type ActionUsageInfo ¶
type ActionUsageInfo struct {
ActionName string `json:"action_name"`
Version string `json:"version"`
UsageCount int `json:"usage_count"`
WorkflowFiles []string `json:"workflow_files"`
SecurityRisk SecurityRiskLevel `json:"security_risk"`
IsVerified bool `json:"is_verified"`
IsDeprecated bool `json:"is_deprecated"`
}
ActionUsageInfo represents information about action usage.
type ActionsMarketplacePolicy ¶
type ActionsMarketplacePolicy string
ActionsMarketplacePolicy defines the policy for marketplace actions.
const ( MarketplacePolicyDisabled ActionsMarketplacePolicy = "disabled" MarketplacePolicyVerifiedOnly ActionsMarketplacePolicy = "verified_only" MarketplacePolicyAll ActionsMarketplacePolicy = "all" MarketplacePolicySelected ActionsMarketplacePolicy = "selected" )
type ActionsPermissionLevel ¶
type ActionsPermissionLevel string
ActionsPermissionLevel defines the permission level for GitHub Actions.
const ( // ActionsPermissionDisabled disables GitHub Actions for the repository/organization. ActionsPermissionDisabled ActionsPermissionLevel = "disabled" // ActionsPermissionAll allows all GitHub Actions to run. ActionsPermissionAll ActionsPermissionLevel = "all" // ActionsPermissionLocalOnly allows only local actions and workflows to run. ActionsPermissionLocalOnly ActionsPermissionLevel = "local_only" // ActionsPermissionSelectedActions allows only selected actions to run. ActionsPermissionSelectedActions ActionsPermissionLevel = "selected" )
type ActionsPolicy ¶
type ActionsPolicy struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Organization string `json:"organization" yaml:"organization"`
Repository string `json:"repository,omitempty" yaml:"repository,omitempty"`
PermissionLevel ActionsPermissionLevel `json:"permissionLevel" yaml:"permissionLevel"`
AllowedActions []string `json:"allowedActions,omitempty" yaml:"allowedActions,omitempty"`
AllowedActionsPatterns []string `json:"allowedActionsPatterns,omitempty" yaml:"allowedActionsPatterns,omitempty"`
WorkflowPermissions WorkflowPermissions `json:"workflowPermissions" yaml:"workflowPermissions"`
SecuritySettings ActionsSecuritySettings `json:"securitySettings" yaml:"securitySettings"`
SecretsPolicy SecretsPolicy `json:"secretsPolicy" yaml:"secretsPolicy"`
Variables map[string]string `json:"variables,omitempty" yaml:"variables,omitempty"`
Environments []EnvironmentPolicy `json:"environments,omitempty" yaml:"environments,omitempty"`
Runners RunnerPolicy `json:"runners" yaml:"runners"`
CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
CreatedBy string `json:"createdBy" yaml:"createdBy"`
UpdatedBy string `json:"updatedBy" yaml:"updatedBy"`
Version int `json:"version" yaml:"version"`
Enabled bool `json:"enabled" yaml:"enabled"`
Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"`
}
ActionsPolicy represents a GitHub Actions permission policy.
func GetDefaultActionsPolicy ¶
func GetDefaultActionsPolicy() *ActionsPolicy
GetDefaultActionsPolicy returns a default Actions policy template.
type ActionsPolicyEnforcer ¶
type ActionsPolicyEnforcer struct {
// contains filtered or unexported fields
}
ActionsPolicyEnforcer handles the enforcement and validation of Actions policies.
func NewActionsPolicyEnforcer ¶
func NewActionsPolicyEnforcer(logger Logger, apiClient APIClient, policyManager *ActionsPolicyManager) *ActionsPolicyEnforcer
NewActionsPolicyEnforcer creates a new Actions policy enforcer that validates and enforces GitHub Actions policies across repositories. It registers default validation rules and provides methods to scan workflows for compliance.
func (*ActionsPolicyEnforcer) AddValidationRule ¶
func (ape *ActionsPolicyEnforcer) AddValidationRule(rule PolicyValidationRule)
AddValidationRule adds a custom validation rule.
func (*ActionsPolicyEnforcer) EnforcePolicy ¶
func (ape *ActionsPolicyEnforcer) EnforcePolicy(ctx context.Context, policyID, organization, repository string) (*PolicyEnforcementResult, error)
EnforcePolicy applies an Actions policy to a repository.
func (*ActionsPolicyEnforcer) ValidatePolicy ¶
func (ape *ActionsPolicyEnforcer) ValidatePolicy(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) ([]PolicyValidationResult, error)
ValidatePolicy validates a policy against current repository state.
type ActionsPolicyManager ¶
type ActionsPolicyManager struct {
// contains filtered or unexported fields
}
ActionsPolicyManager manages GitHub Actions policies.
func NewActionsPolicyManager ¶
func NewActionsPolicyManager(logger Logger, apiClient APIClient) *ActionsPolicyManager
NewActionsPolicyManager creates a new Actions policy manager.
func (*ActionsPolicyManager) CreatePolicy ¶
func (apm *ActionsPolicyManager) CreatePolicy(_ context.Context, policy *ActionsPolicy) error
CreatePolicy creates a new Actions policy.
func (*ActionsPolicyManager) DeletePolicy ¶
func (apm *ActionsPolicyManager) DeletePolicy(_ context.Context, policyID string) error
DeletePolicy deletes a policy.
func (*ActionsPolicyManager) GetPolicy ¶
func (apm *ActionsPolicyManager) GetPolicy(_ context.Context, policyID string) (*ActionsPolicy, error)
GetPolicy retrieves a policy by ID.
func (*ActionsPolicyManager) ListPolicies ¶
func (apm *ActionsPolicyManager) ListPolicies(_ context.Context, organization string) ([]*ActionsPolicy, error)
ListPolicies lists all policies, optionally filtered by organization.
func (*ActionsPolicyManager) UpdatePolicy ¶
func (apm *ActionsPolicyManager) UpdatePolicy(_ context.Context, policyID string, updates *ActionsPolicy) error
UpdatePolicy updates an existing Actions policy.
type ActionsPolicyViolation ¶
type ActionsPolicyViolation struct {
ID string `json:"id"`
PolicyID string `json:"policyId"`
ViolationType ActionsPolicyViolationType `json:"violationType"`
Severity PolicyViolationSeverity `json:"severity"`
Resource string `json:"resource"`
Description string `json:"description"`
Details map[string]interface{} `json:"details,omitempty"`
DetectedAt time.Time `json:"detectedAt"`
ResolvedAt *time.Time `json:"resolvedAt,omitempty"`
Status PolicyViolationStatus `json:"status"`
}
ActionsPolicyViolation represents a policy violation.
type ActionsPolicyViolationType ¶
type ActionsPolicyViolationType string
ActionsPolicyViolationType defines types of policy violations.
const ( ViolationTypeExcessivePermissions ActionsPolicyViolationType = "excessive_permissions" ViolationTypeSecretMisuse ActionsPolicyViolationType = "secret_misuse" ViolationTypeRunnerPolicyBreach ActionsPolicyViolationType = "runner_policy_breach" ViolationTypeEnvironmentBreach ActionsPolicyViolationType = "environment_breach" ViolationTypeWorkflowPermissionBreach ActionsPolicyViolationType = "workflow_permission_breach" ViolationTypeSecuritySettingsBreach ActionsPolicyViolationType = "security_settings_breach" )
type ActionsSecuritySettings ¶
type ActionsSecuritySettings struct {
RequireCodeScanningApproval bool `json:"requireCodeScanningApproval" yaml:"requireCodeScanningApproval"`
RequireSecretScanningApproval bool `json:"requireSecretScanningApproval" yaml:"requireSecretScanningApproval"`
AllowForkPRs bool `json:"allowForkPRs" yaml:"allowForkPrs"`
RequireApprovalForForkPRs bool `json:"requireApprovalForForkPRs" yaml:"requireApprovalForForkPrs"`
AllowPrivateRepoForkRun bool `json:"allowPrivateRepoForkRun" yaml:"allowPrivateRepoForkRun"`
RequireApprovalForPrivateFork bool `json:"requireApprovalForPrivateFork" yaml:"requireApprovalForPrivateFork"`
RestrictedActionsPatterns []string `json:"restrictedActionsPatterns,omitempty" yaml:"restrictedActionsPatterns,omitempty"`
AllowGitHubOwnedActions bool `json:"allowGitHubOwnedActions" yaml:"allowGithubOwnedActions"`
AllowVerifiedPartnerActions bool `json:"allowVerifiedPartnerActions" yaml:"allowVerifiedPartnerActions"`
AllowMarketplaceActions ActionsMarketplacePolicy `json:"allowMarketplaceActions" yaml:"allowMarketplaceActions"`
RequireSignedCommits bool `json:"requireSignedCommits" yaml:"requireSignedCommits"`
EnforceAdminsOnBranches bool `json:"enforceAdminsOnBranches" yaml:"enforceAdminsOnBranches"`
OIDCCustomClaims map[string]string `json:"oidcCustomClaims,omitempty" yaml:"oidcCustomClaims,omitempty"`
}
ActionsSecuritySettings defines security-related settings for Actions.
type ActionsTokenPermission ¶
type ActionsTokenPermission string
ActionsTokenPermission defines the permission level for a specific scope.
const ( TokenPermissionNone ActionsTokenPermission = "none" TokenPermissionRead ActionsTokenPermission = "read" TokenPermissionWrite ActionsTokenPermission = "write" )
type AlertThresholds ¶
type AlertThresholds struct {
ErrorRate float64 `json:"error_rate" yaml:"error_rate"` // Percentage
ResponseTime time.Duration `json:"response_time" yaml:"response_time"` // Maximum acceptable response time
FailureCount int `json:"failure_count" yaml:"failure_count"` // Consecutive failures
DeliveryFailureAge time.Duration `json:"delivery_failure_age" yaml:"delivery_failure_age"` // Age of oldest delivery failure
}
AlertThresholds defines thresholds for different alert levels.
type AllowDeletions ¶
type AllowDeletions struct {
Enabled bool `json:"enabled"`
}
type AllowForcePushes ¶
type AllowForcePushes struct {
Enabled bool `json:"enabled"`
}
Additional branch protection settings.
type AllowedActionsValidationRule ¶
type AllowedActionsValidationRule struct{}
AllowedActionsValidationRule validates allowed actions compliance.
func (*AllowedActionsValidationRule) GetDescription ¶
func (r *AllowedActionsValidationRule) GetDescription() string
func (*AllowedActionsValidationRule) GetRuleID ¶
func (r *AllowedActionsValidationRule) GetRuleID() string
func (*AllowedActionsValidationRule) Validate ¶
func (r *AllowedActionsValidationRule) Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
type ApplyPoliciesRequest ¶
type ApplyPoliciesRequest struct {
Organization string `json:"organization"`
PolicyIDs []string `json:"policy_ids,omitempty"` // if empty, apply all enabled policies
RepositoryNames []string `json:"repository_names,omitempty"` // if empty, apply to all repos
DryRun bool `json:"dry_run"`
Force bool `json:"force"` // Override conflict resolution
}
ApplyPoliciesRequest represents a request to apply webhook policies.
type ApplyPoliciesResult ¶
type ApplyPoliciesResult struct {
Organization string `json:"organization"`
TotalRepositories int `json:"total_repositories"`
ProcessedRepositories int `json:"processed_repositories"`
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
SkippedCount int `json:"skipped_count"`
Results []PolicyApplicationResult `json:"results"`
ExecutionTime string `json:"execution_time"`
Summary PolicyApplicationSummary `json:"summary"`
}
ApplyPoliciesResult represents the result of applying policies.
type ApprovalCondition ¶
type ApprovalCondition struct {
Type ConditionType `json:"type"`
Field string `json:"field"`
Operator string `json:"operator"`
Value interface{} `json:"value"`
Negated bool `json:"negated,omitempty"`
}
ApprovalCondition defines conditions for auto-approval.
type ApprovalEscalationRule ¶
type ApprovalRequirements ¶
type ApprovalRequirements struct {
MajorUpdates ApprovalRule `json:"major_updates"`
MinorUpdates ApprovalRule `json:"minor_updates"`
PatchUpdates ApprovalRule `json:"patch_updates"`
SecurityUpdates ApprovalRule `json:"security_updates"`
}
ApprovalRequirements defines approval requirements for different update types.
type ApprovalRule ¶
type ApprovalRule struct {
RequiredReviewers int `json:"required_reviewers"`
RequiredApprovals int `json:"required_approvals"`
DismissStaleReviews bool `json:"dismiss_stale_reviews"`
RequireCodeOwnerReview bool `json:"require_code_owner_review"`
AllowedMergeUsers []string `json:"allowed_merge_users,omitempty"`
RestrictedPaths []string `json:"restricted_paths,omitempty"`
}
ApprovalRule defines approval requirements for a specific update type.
type ApprovalStep ¶
type ApprovalWorkflow ¶
type ApprovalWorkflow struct {
Required bool `json:"required"`
Steps []ApprovalStep `json:"steps"`
EstimatedTime time.Duration `json:"estimated_time"`
AutoApprovalEligible bool `json:"auto_approval_eligible"`
}
type AutoApprovalAction ¶
type AutoApprovalAction struct {
Type ActionType `json:"type"`
Parameters map[string]string `json:"parameters,omitempty"`
DelayAfter time.Duration `json:"delay_after,omitempty"`
}
AutoApprovalAction defines actions to take when auto-approving.
type AutoApprovalCondition ¶
type AutoApprovalRule ¶
type AutoApprovalRule struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Conditions []ApprovalCondition `json:"conditions"`
Actions []AutoApprovalAction `json:"actions"`
MaxSeverity VulnerabilitySeverity `json:"max_severity"`
RequiredChecks []string `json:"required_checks"`
TestingRequired bool `json:"testing_required"`
MinTestCoverage float64 `json:"min_test_coverage,omitempty"`
BusinessHoursOnly bool `json:"business_hours_only"`
CooldownPeriod time.Duration `json:"cooldown_period"`
}
AutoApprovalRule defines when security updates can be automatically approved.
type AutomatedTestingConfig ¶
type AutomatedTestingConfig struct {
Enabled bool `json:"enabled"`
TriggerOnUpdate bool `json:"trigger_on_update"`
ParallelExecution bool `json:"parallel_execution"`
MaxConcurrentTests int `json:"max_concurrent_tests"`
TestEnvironments []string `json:"test_environments"`
NotificationOnFailure bool `json:"notification_on_failure"`
AutoRetryOnFailure bool `json:"auto_retry_on_failure"`
MaxRetries int `json:"max_retries"`
TestResultsRetention time.Duration `json:"test_results_retention"`
}
type AutomationAction ¶
type AutomationAction struct {
ID string `json:"id" yaml:"id"`
Type ActionType `json:"type" yaml:"type"`
Name string `json:"name" yaml:"name"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Enabled bool `json:"enabled" yaml:"enabled"`
Parameters map[string]interface{} `json:"parameters" yaml:"parameters"`
Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
RetryPolicy *ActionRetryPolicy `json:"retryPolicy,omitempty" yaml:"retryPolicy,omitempty"`
OnFailure ActionFailurePolicy `json:"onFailure,omitempty" yaml:"onFailure,omitempty"`
}
AutomationAction defines an action to be executed when conditions are met.
type AutomationConditions ¶
type AutomationConditions struct {
// Event-based conditions
EventTypes []EventType `json:"eventTypes,omitempty" yaml:"eventTypes,omitempty"`
Actions []EventAction `json:"actions,omitempty" yaml:"actions,omitempty"`
Organization string `json:"organization,omitempty" yaml:"organization,omitempty"`
Repository string `json:"repository,omitempty" yaml:"repository,omitempty"`
Sender string `json:"sender,omitempty" yaml:"sender,omitempty"`
// Repository-based conditions
RepositoryPatterns []string `json:"repositoryPatterns,omitempty" yaml:"repositoryPatterns,omitempty"`
Languages []string `json:"languages,omitempty" yaml:"languages,omitempty"`
Topics []string `json:"topics,omitempty" yaml:"topics,omitempty"`
Visibility []string `json:"visibility,omitempty" yaml:"visibility,omitempty"` // public, private, internal
IsArchived *bool `json:"isArchived,omitempty" yaml:"isArchived,omitempty"`
IsTemplate *bool `json:"isTemplate,omitempty" yaml:"isTemplate,omitempty"`
// Content-based conditions
BranchPatterns []string `json:"branchPatterns,omitempty" yaml:"branchPatterns,omitempty"`
FilePatterns []string `json:"filePatterns,omitempty" yaml:"filePatterns,omitempty"`
PathPatterns []string `json:"pathPatterns,omitempty" yaml:"pathPatterns,omitempty"`
// Time-based conditions
TimeRange *TimeRange `json:"timeRange,omitempty" yaml:"timeRange,omitempty"`
DaysOfWeek []int `json:"daysOfWeek,omitempty" yaml:"daysOfWeek,omitempty"` // 0=Sunday, 1=Monday, etc.
HoursOfDay []int `json:"hoursOfDay,omitempty" yaml:"hoursOfDay,omitempty"` // 0-23
BusinessHours bool `json:"businessHours,omitempty" yaml:"businessHours,omitempty"` // 9-17 weekdays
// Advanced conditions
CustomFilters map[string]interface{} `json:"customFilters,omitempty" yaml:"customFilters,omitempty"`
PayloadMatch []PayloadMatcher `json:"payloadMatch,omitempty" yaml:"payloadMatch,omitempty"`
// Logical operators
LogicalOperator ConditionOperator `json:"logicalOperator,omitempty" yaml:"logicalOperator,omitempty"`
SubConditions []AutomationConditions `json:"subConditions,omitempty" yaml:"subConditions,omitempty"`
}
AutomationConditions defines the conditions that must be met for a rule to trigger.
type AutomationEngine ¶
type AutomationEngine struct {
// contains filtered or unexported fields
}
AutomationEngine is the main engine that processes GitHub events and executes automation rules.
func NewAutomationEngine ¶
func NewAutomationEngine( logger Logger, apiClient APIClient, ruleManager *RuleManager, conditionEvaluator ConditionEvaluator, actionExecutor ActionExecutor, eventProcessor EventProcessor, config *AutomationEngineConfig, ) *AutomationEngine
NewAutomationEngine creates a new automation engine.
func (*AutomationEngine) GetActiveExecutions ¶
func (ae *AutomationEngine) GetActiveExecutions() map[string]*AutomationRuleExecution
GetActiveExecutions returns currently active executions.
func (*AutomationEngine) GetMetrics ¶
func (ae *AutomationEngine) GetMetrics() *EngineMetrics
GetMetrics returns current engine metrics.
func (*AutomationEngine) ProcessEvent ¶
func (ae *AutomationEngine) ProcessEvent(ctx context.Context, event *GitHubEvent) error
ProcessEvent processes a GitHub event through the automation engine.
type AutomationEngineConfig ¶
type AutomationEngineConfig struct {
// Worker configuration
MaxWorkers int `json:"maxWorkers" yaml:"maxWorkers"`
EventBufferSize int `json:"eventBufferSize" yaml:"eventBufferSize"`
ExecutionTimeout time.Duration `json:"executionTimeout" yaml:"executionTimeout"`
// Rate limiting
EventsPerSecond int `json:"eventsPerSecond" yaml:"eventsPerSecond"`
ExecutionsPerMinute int `json:"executionsPerMinute" yaml:"executionsPerMinute"`
// Feature flags
EnableAsyncExecution bool `json:"enableAsyncExecution" yaml:"enableAsyncExecution"`
EnableRuleFiltering bool `json:"enableRuleFiltering" yaml:"enableRuleFiltering"`
EnableMetrics bool `json:"enableMetrics" yaml:"enableMetrics"`
// Error handling
MaxRetries int `json:"maxRetries" yaml:"maxRetries"`
RetryBackoffFactor float64 `json:"retryBackoffFactor" yaml:"retryBackoffFactor"`
ErrorThreshold int `json:"errorThreshold" yaml:"errorThreshold"`
// Filtering
ExcludedEventTypes []EventType `json:"excludedEventTypes" yaml:"excludedEventTypes"`
IncludedEventTypes []EventType `json:"includedEventTypes" yaml:"includedEventTypes"`
Organizations []string `json:"organizations" yaml:"organizations"`
}
AutomationEngineConfig holds configuration for the automation engine.
type AutomationEventProcessor ¶
type AutomationEventProcessor interface {
ProcessEvent(ctx context.Context, event *GitHubEvent) error
FilterEvent(event *GitHubEvent) bool
ValidateEvent(ctx context.Context, event *GitHubEvent) error
}
AutomationEventProcessor defines the interface for processing GitHub events in automation.
type AutomationExecutionContext ¶
type AutomationExecutionContext struct {
Event *GitHubEvent `json:"event,omitempty"`
Repository *RepositoryInfo `json:"repository,omitempty"`
Organization string `json:"organization,omitempty"`
User string `json:"user,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
Environment string `json:"environment,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
AutomationExecutionContext provides context for rule execution.
type AutomationRule ¶
type AutomationRule struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Organization string `json:"organization" yaml:"organization"`
Enabled bool `json:"enabled" yaml:"enabled"`
Priority int `json:"priority" yaml:"priority"` // Higher number = higher priority
Conditions AutomationConditions `json:"conditions" yaml:"conditions"`
Actions []AutomationAction `json:"actions" yaml:"actions"`
Schedule *AutomationSchedule `json:"schedule,omitempty" yaml:"schedule,omitempty"`
Metadata AutomationRuleMetadata `json:"metadata" yaml:"metadata"`
CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
CreatedBy string `json:"createdBy" yaml:"createdBy"`
Tags map[string]string `json:"tags,omitempty" yaml:"tags,omitempty"`
}
AutomationRule represents a complete automation rule for GitHub events.
type AutomationRuleExecution ¶
type AutomationRuleExecution struct {
ID string `json:"id"`
RuleID string `json:"ruleId"`
TriggerEventID string `json:"triggerEventId,omitempty"`
StartedAt time.Time `json:"startedAt"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
Status ExecutionStatus `json:"status"`
TriggerType ExecutionTriggerType `json:"triggerType"`
Context AutomationExecutionContext `json:"context"`
Actions []ActionExecutionResult `json:"actions"`
Error string `json:"error,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
AutomationRuleExecution represents an execution instance of an automation rule.
type AutomationRuleMetadata ¶
type AutomationRuleMetadata struct {
Version string `json:"version" yaml:"version"`
Category string `json:"category,omitempty" yaml:"category,omitempty"`
Environment string `json:"environment,omitempty" yaml:"environment,omitempty"`
Owner string `json:"owner,omitempty" yaml:"owner,omitempty"`
Team string `json:"team,omitempty" yaml:"team,omitempty"`
Documentation string `json:"documentation,omitempty" yaml:"documentation,omitempty"`
ExamplePayload json.RawMessage `json:"examplePayload,omitempty" yaml:"examplePayload,omitempty"`
CustomMetadata map[string]string `json:"customMetadata,omitempty" yaml:"customMetadata,omitempty"`
}
AutomationRuleMetadata contains metadata about the rule.
type AutomationRuleService ¶
type AutomationRuleService interface {
// Rule Management
CreateRule(ctx context.Context, rule *AutomationRule) error
GetRule(ctx context.Context, org, ruleID string) (*AutomationRule, error)
ListRules(ctx context.Context, org string, filter *RuleFilter) ([]*AutomationRule, error)
UpdateRule(ctx context.Context, rule *AutomationRule) error
DeleteRule(ctx context.Context, org, ruleID string) error
EnableRule(ctx context.Context, org, ruleID string) error
DisableRule(ctx context.Context, org, ruleID string) error
// Rule Evaluation
EvaluateConditions(ctx context.Context, rule *AutomationRule, event *GitHubEvent) (bool, error)
ExecuteRule(ctx context.Context, rule *AutomationRule, context *AutomationExecutionContext) (*AutomationRuleExecution, error)
// Rule Sets
CreateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
GetRuleSet(ctx context.Context, org, setID string) (*AutomationRuleSet, error)
ListRuleSets(ctx context.Context, org string) ([]*AutomationRuleSet, error)
UpdateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
DeleteRuleSet(ctx context.Context, org, setID string) error
// Templates
CreateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
GetTemplate(ctx context.Context, templateID string) (*AutomationRuleTemplate, error)
ListTemplates(ctx context.Context, category string) ([]*AutomationRuleTemplate, error)
UpdateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
DeleteTemplate(ctx context.Context, templateID string) error
InstantiateTemplate(ctx context.Context, templateID string, variables map[string]interface{}) (*AutomationRule, error)
// Execution History
GetExecution(ctx context.Context, executionID string) (*AutomationRuleExecution, error)
ListExecutions(ctx context.Context, org string, filter *ExecutionFilter) ([]*AutomationRuleExecution, error)
CancelExecution(ctx context.Context, executionID string) error
// Validation and Testing
ValidateRule(ctx context.Context, rule *AutomationRule) (*RuleValidationResult, error)
TestRule(ctx context.Context, rule *AutomationRule, testEvent *GitHubEvent) (*RuleTestResult, error)
DryRunRule(ctx context.Context, ruleID string, event *GitHubEvent) (*RuleTestResult, error)
}
AutomationRuleService defines the interface for managing automation rules.
type AutomationRuleSet ¶
type AutomationRuleSet struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Organization string `json:"organization" yaml:"organization"`
Rules []AutomationRule `json:"rules" yaml:"rules"`
Enabled bool `json:"enabled" yaml:"enabled"`
Tags map[string]string `json:"tags,omitempty" yaml:"tags,omitempty"`
CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
CreatedBy string `json:"createdBy" yaml:"createdBy"`
}
AutomationRuleSet represents a collection of related automation rules.
type AutomationRuleTemplate ¶
type AutomationRuleTemplate struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Category string `json:"category" yaml:"category"`
Template AutomationRule `json:"template" yaml:"template"`
Variables []TemplateVariable `json:"variables" yaml:"variables"`
Examples []TemplateExample `json:"examples,omitempty" yaml:"examples,omitempty"`
Tags map[string]string `json:"tags,omitempty" yaml:"tags,omitempty"`
CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
UpdatedAt time.Time `json:"updatedAt" yaml:"updatedAt"`
CreatedBy string `json:"createdBy" yaml:"createdBy"`
}
AutomationRuleTemplate represents a reusable rule template.
type AutomationSchedule ¶
type AutomationSchedule struct {
Type ScheduleType `json:"type" yaml:"type"`
Expression string `json:"expression" yaml:"expression"` // Cron expression
Timezone string `json:"timezone,omitempty" yaml:"timezone,omitempty"`
StartDate *time.Time `json:"startDate,omitempty" yaml:"startDate,omitempty"`
EndDate *time.Time `json:"endDate,omitempty" yaml:"endDate,omitempty"`
}
AutomationSchedule defines when a rule should be evaluated (for scheduled rules).
type BenchmarkResult ¶
type BlackoutPeriod ¶
type BranchProtection ¶
type BranchProtection struct {
RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks,omitempty"`
EnforceAdmins bool `json:"enforce_admins"`
RequiredPullRequestReviews *RequiredPullRequestReviews `json:"required_pull_request_reviews,omitempty"`
Restrictions *BranchRestrictions `json:"restrictions,omitempty"`
AllowForcePushes *AllowForcePushes `json:"allow_force_pushes,omitempty"`
AllowDeletions *AllowDeletions `json:"allow_deletions,omitempty"`
RequiredConversationResolution *RequiredConversationResolution `json:"required_conversation_resolution,omitempty"`
}
BranchProtection represents branch protection rule configuration.
type BranchProtectionConfig ¶
type BranchProtectionConfig struct {
RequiredReviews int `json:"required_reviews"`
DismissStaleReviews bool `json:"dismiss_stale_reviews"`
RequireCodeOwnerReviews bool `json:"require_code_owner_reviews"`
RequiredStatusChecks []string `json:"required_status_checks"`
StrictStatusChecks bool `json:"strict_status_checks"`
EnforceAdmins bool `json:"enforce_admins"`
RestrictPushes bool `json:"restrict_pushes"`
AllowedUsers []string `json:"allowed_users,omitempty"`
AllowedTeams []string `json:"allowed_teams,omitempty"`
RequireConversationResolution bool `json:"require_conversation_resolution"`
AllowForcePushes bool `json:"allow_force_pushes"`
AllowDeletions bool `json:"allow_deletions"`
}
BranchProtectionConfig represents branch protection configuration.
type BranchProtectionData ¶
BranchProtectionData represents raw branch protection data.
type BranchRestrictions ¶
BranchRestrictions represents branch push restrictions.
type BreakingChangeAnalysisResult ¶
type BreakingChangeAnalysisResult struct {
HasBreakingChanges bool `json:"has_breaking_changes"`
DetectedChanges []DetectedChange `json:"detected_changes"`
ImpactAssessment string `json:"impact_assessment"`
MigrationRequired bool `json:"migration_required"`
}
type BreakingChangeDetection ¶
type BreakingChangeDetection struct {
Enabled bool `json:"enabled"`
Methods []DetectionMethod `json:"methods"`
SemverStrictMode bool `json:"semverStrictMode"`
APIChangeDetection bool `json:"apiChangeDetection"`
SchemaChangeDetection bool `json:"schemaChangeDetection"`
CustomDetectionRules []DetectionRule `json:"customDetectionRules"`
IgnorePatterns []string `json:"ignorePatterns"`
ThresholdConfiguration ThresholdConfig `json:"thresholdConfiguration"`
}
BreakingChangeDetection configures how breaking changes are detected.
type BreakingChangePolicy ¶
type BreakingChangePolicy struct {
AllowBreakingChanges bool `json:"allowBreakingChanges"`
BreakingChangeDetection BreakingChangeDetection `json:"breakingChangeDetection"`
ImpactAnalysisRequired bool `json:"impactAnalysisRequired"`
DeprecationNoticePeriod time.Duration `json:"deprecationNoticePeriod"`
MigrationGuidanceRequired bool `json:"migrationGuidanceRequired"`
BackwardCompatibilityPeriod time.Duration `json:"backwardCompatibilityPeriod"`
BreakingChangeApprovers []string `json:"breakingChangeApprovers"`
CommunicationPlan CommunicationPlan `json:"communicationPlan"`
}
BreakingChangePolicy defines how to handle breaking changes.
type BulkApplyOptions ¶
type BulkApplyOptions struct {
// DryRun performs a dry run without making actual changes
DryRun bool
// ConcurrentWorkers sets the number of concurrent workers (default: 5)
ConcurrentWorkers int
// ExcludeRepositories contains repository names to exclude from the operation
ExcludeRepositories []string
// IncludeRepositories contains repository names to include (if empty, all repos are included)
IncludeRepositories []string
// OnProgress callback function called for each repository processed
OnProgress func(repo string, current int, total int, err error)
// ConfirmationPrompt enables interactive confirmation for sensitive changes
ConfirmationPrompt *ConfirmationPrompt
}
BulkApplyOptions contains options for bulk application operations.
type BulkApplyResult ¶
type BulkApplyResult struct {
Total int
Success int
Failed int
Skipped int
Errors map[string]error
}
BulkApplyResult contains the result of bulk application operation.
type BulkCloneOptions ¶
type BulkCloneOptions struct {
// WorkerPoolConfig allows customizing worker pool behavior
WorkerPoolConfig workerpool.RepositoryPoolConfig
// Organizations to clone
Organizations []string
// Strategy for existing repositories ("reset", "pull", "fetch")
Strategy string
// ShowProgress enables progress bar
ShowProgress bool
// Verbose enables detailed output
Verbose bool
}
BulkCloneOptions represents options for bulk clone operations.
type BulkCloneRequest ¶
type BulkCloneRequest struct {
Organization string
TargetPath string
Strategy string
Repositories []string // if empty, clone all repositories
Filters *RepositoryFilters
Concurrency int
}
BulkCloneRequest represents a request for bulk repository operations.
type BulkCloneResult ¶
type BulkCloneResult struct {
TotalRepositories int
SuccessfulOperations int
FailedOperations int
SkippedRepositories int
OperationResults []RepositoryOperationResult
ExecutionTime string
}
BulkCloneResult represents the result of bulk operations.
type BulkOperationProgress ¶
type BulkOperationProgress struct {
Total int `json:"total"`
Completed int `json:"completed"`
Failed int `json:"failed"`
Skipped int `json:"skipped"`
Percentage float64 `json:"percentage"`
CurrentRepo string `json:"current_repo,omitempty"`
}
BulkOperationProgress tracks the progress of bulk operations.
type BulkOperationStatus ¶
type BulkOperationStatus string
const ( BulkOperationStatusPending BulkOperationStatus = "pending" BulkOperationStatusRunning BulkOperationStatus = "running" BulkOperationStatusCompleted BulkOperationStatus = "completed" BulkOperationStatusFailed BulkOperationStatus = "failed" BulkOperationStatusCancelled BulkOperationStatus = "cancelled" )
type BulkOperationType ¶
type BulkOperationType string
const ( BulkOperationTypeApplyPolicy BulkOperationType = "apply_policy" BulkOperationTypeValidatePolicy BulkOperationType = "validate_policy" BulkOperationTypeUpdateConfig BulkOperationType = "update_config" BulkOperationTypeEnableEcosystem BulkOperationType = "enable_ecosystem" BulkOperationTypeGenerateReport BulkOperationType = "generate_report" )
type BulkOperationsConfig ¶
type BulkOperationsConfig struct {
// WorkerPool configuration
PoolConfig workerpool.RepositoryPoolConfig
// Progress tracking
ShowProgress bool
// Verbose output
Verbose bool
}
BulkOperationsConfig represents configuration for bulk operations.
func DefaultBulkOperationsConfig ¶
func DefaultBulkOperationsConfig() BulkOperationsConfig
DefaultBulkOperationsConfig returns default configuration for bulk operations.
type BulkOperationsManager ¶
type BulkOperationsManager struct {
// contains filtered or unexported fields
}
BulkOperationsManager manages bulk repository operations using worker pools.
func NewBulkOperationsManager ¶
func NewBulkOperationsManager(config BulkOperationsConfig) *BulkOperationsManager
NewBulkOperationsManager creates a new bulk operations manager.
func (*BulkOperationsManager) RefreshAllWithWorkerPool ¶
func (b *BulkOperationsManager) RefreshAllWithWorkerPool(ctx context.Context, targetPath, org, strategy string, ) error
RefreshAllWithWorkerPool performs bulk repository refresh using worker pools.
func (*BulkOperationsManager) Start ¶
func (b *BulkOperationsManager) Start() error
Start initializes the bulk operations manager.
func (*BulkOperationsManager) Stop ¶
func (b *BulkOperationsManager) Stop()
Stop shuts down the bulk operations manager.
type BulkPolicyOperation ¶
type BulkPolicyOperation struct {
ID string `json:"id"`
Type BulkOperationType `json:"type"`
Organization string `json:"organization"`
PolicyID string `json:"policy_id"`
TargetRepos []string `json:"target_repos"`
Status BulkOperationStatus `json:"status"`
Progress BulkOperationProgress `json:"progress"`
Results []DependabotRepositoryOperationResult `json:"results"`
StartedAt time.Time `json:"started_at"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
EstimatedDuration time.Duration `json:"estimated_duration"`
}
BulkPolicyOperation represents a bulk operation on multiple repositories.
type BulkUpdateApprovalRule ¶
type BulkWebhookDeleteRequest ¶
type BulkWebhookDeleteRequest struct {
Organization string `json:"organization"`
Repositories []string `json:"repositories,omitempty"`
SelectBy WebhookSelector `json:"select_by"` // how to find webhooks to delete
Filters *RepositoryFilters `json:"filters,omitempty"`
}
BulkWebhookDeleteRequest represents a bulk webhook deletion request.
type BulkWebhookRequest ¶
type BulkWebhookRequest struct {
Organization string `json:"organization"`
Repositories []string `json:"repositories,omitempty"` // if empty, apply to all repos
Template WebhookCreateRequest `json:"template"`
Filters *RepositoryFilters `json:"filters,omitempty"`
}
BulkWebhookRequest represents a bulk webhook creation request.
type BulkWebhookResult ¶
type BulkWebhookResult struct {
TotalRepositories int `json:"total_repositories"`
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
Results []WebhookOperationResult `json:"results"`
ExecutionTime string `json:"execution_time"`
}
BulkWebhookResult represents the result of bulk webhook operations.
type BulkWebhookUpdateRequest ¶
type BulkWebhookUpdateRequest struct {
Organization string `json:"organization"`
Repositories []string `json:"repositories,omitempty"`
Template WebhookUpdateRequest `json:"template"`
Filters *RepositoryFilters `json:"filters,omitempty"`
SelectBy WebhookSelector `json:"select_by"` // how to find webhooks to update
}
BulkWebhookUpdateRequest represents a bulk webhook update request.
type BusinessHours ¶
type BusinessHours struct {
Timezone string `json:"timezone"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Weekdays []string `json:"weekdays"`
Holidays []string `json:"holidays,omitempty"`
}
BusinessHours defines when business hours are active.
type CVERecord ¶
type CVERecord struct {
ID string `json:"id"`
Description string `json:"description"`
CVSS CVSSScore `json:"cvss"`
References []Reference `json:"references"`
Vendors []VendorInfo `json:"vendors"`
Products []ProductInfo `json:"products"`
Timeline CVETimeline `json:"timeline"`
Metadata map[string]interface{} `json:"metadata"`
}
CVERecord represents a CVE record from external sources.
type CVETimeline ¶
type CVETimeline struct {
Published time.Time `json:"published"`
Modified time.Time `json:"modified"`
Reserved *time.Time `json:"reserved,omitempty"`
Rejected *time.Time `json:"rejected,omitempty"`
}
CVETimeline represents the timeline of a CVE.
type CVSSScore ¶
type CVSSScore struct {
Version string `json:"version"`
Score float64 `json:"score"`
Vector string `json:"vector"`
Severity string `json:"severity"`
BaseScore float64 `json:"base_score"`
ImpactScore float64 `json:"impact_score,omitempty"`
}
CVSSScore represents CVSS scoring information.
type CacheConfiguration ¶
type CacheConfiguration struct {
EnableLocalCache bool
// EnableRedisCache bool // Disabled - cache package removed
LocalCacheSize int
DefaultTTL time.Duration
}
CacheConfiguration provides cache configuration for GitHub operations - DISABLED (cache package removed) Simple configuration struct without external cache dependency.
func DefaultCacheConfiguration ¶
func DefaultCacheConfiguration() CacheConfiguration
DefaultCacheConfiguration returns sensible defaults for GitHub caching - DISABLED (cache package removed) Simple configuration without external cache dependency.
func (CacheConfiguration) ToCacheManagerConfig ¶
func (cc CacheConfiguration) ToCacheManagerConfig() map[string]interface{}
ToCacheManagerConfig converts to cache manager configuration - DISABLED (cache package removed) Simple configuration conversion without external cache dependency.
type CachedGitHubClient ¶
type CachedGitHubClient struct {
// contains filtered or unexported fields
}
CachedGitHubClient wraps GitHub API calls with caching - DISABLED (cache package removed) Simple in-memory cache implementation to replace deleted cache package.
Example (ErrorHandling) ¶
ExampleErrorHandling demonstrates proper error handling when working with GitHub API operations.
package main
import (
"context"
"fmt"
"time"
"github.com/Gizzahub/gzh-cli/pkg/github"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Attempt to get default branch for a non-existent repository
_, err := github.GetDefaultBranch(ctx, "nonexistent", "repository")
if err != nil {
fmt.Printf("Expected error for non-existent repository: %v\n", err)
}
// Attempt to list repositories for a non-existent organization
_, err = github.List(ctx, "definitely-does-not-exist-org-12345")
if err != nil {
fmt.Printf("Expected error for non-existent organization: %v\n", err)
}
// Attempt to clone to an invalid path
err = github.Clone(ctx, "/invalid/path/that/does/not/exist", "octocat", "Hello-World")
if err != nil {
fmt.Printf("Expected error for invalid path: %v\n", err)
}
fmt.Println("Error handling examples completed")
}
Output: Error handling examples demonstrate proper error management
Example (Workflow) ¶
ExampleWorkflow demonstrates a complete workflow of discovering and cloning repositories from a GitHub organization.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/Gizzahub/gzh-cli/pkg/github"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
orgName := "octocat"
targetDir := "/tmp/github-workflow-example"
// Step 1: Create target directory
_ = os.MkdirAll(targetDir, 0o755)
defer func() { _ = os.RemoveAll(targetDir) }()
// Step 2: List all repositories in the organization
repos, err := github.List(ctx, orgName)
if err != nil {
log.Printf("Error listing repositories: %v", err)
return
}
fmt.Printf("Found %d repositories in %s organization\n", len(repos), orgName)
// Step 3: Clone the first few repositories (limit for example)
maxRepos := 3
if len(repos) > maxRepos {
repos = repos[:maxRepos]
}
for _, repo := range repos {
fmt.Printf("Cloning %s...\n", repo)
// Get default branch first
branch, err := github.GetDefaultBranch(ctx, orgName, repo)
if err != nil {
log.Printf("Warning: Could not get default branch for %s: %v", repo, err)
} else {
fmt.Printf(" Default branch: %s\n", branch)
}
// Clone the repository
err = github.Clone(ctx, targetDir, orgName, repo)
if err != nil {
log.Printf("Error cloning %s: %v", repo, err)
continue
}
fmt.Printf(" ✓ Successfully cloned %s\n", repo)
}
fmt.Println("Workflow completed")
}
Output: Workflow demonstrates organization repository management
func NewCachedGitHubClient ¶
func NewCachedGitHubClient(token string) *CachedGitHubClient
NewCachedGitHubClient creates a new cached GitHub client - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedGitHubClient) GetCacheStats ¶
func (c *CachedGitHubClient) GetCacheStats() map[string]interface{}
GetCacheStats returns GitHub cache statistics - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedGitHubClient) GetDefaultBranchWithCache ¶
func (c *CachedGitHubClient) GetDefaultBranchWithCache(ctx context.Context, org, repo string) (string, error)
GetDefaultBranchWithCache gets repository default branch with caching - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedGitHubClient) InvalidateOrgCache ¶
func (c *CachedGitHubClient) InvalidateOrgCache(ctx context.Context, org string) int
InvalidateOrgCache invalidates all cache entries for an organization - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedGitHubClient) InvalidateRepoCache ¶
func (c *CachedGitHubClient) InvalidateRepoCache(ctx context.Context, org, repo string) int
InvalidateRepoCache invalidates cache entries for a specific repository - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedGitHubClient) ListRepositoriesWithCache ¶
func (c *CachedGitHubClient) ListRepositoriesWithCache(ctx context.Context, org string) ([]string, error)
ListRepositoriesWithCache lists repositories with caching support - DISABLED (cache package removed) Simple implementation without external cache dependency.
type CachedRepositoryConfig ¶
type CachedRepositoryConfig struct {
Repository string `json:"repository"`
Organization string `json:"organization"`
Config *DependabotConfig `json:"config"`
Status *DependabotStatus `json:"status"`
LastUpdated time.Time `json:"last_updated"`
ExpiresAt time.Time `json:"expires_at"`
}
CachedRepositoryConfig represents a cached repository configuration.
type CachedSyncCloneManager ¶
type CachedSyncCloneManager struct {
*OptimizedSyncCloneManager
// contains filtered or unexported fields
}
CachedSyncCloneManager extends OptimizedSyncCloneManager with caching.
func NewCachedSyncCloneManager ¶
func NewCachedSyncCloneManager(token string, config OptimizedCloneConfig) (*CachedSyncCloneManager, error)
NewCachedSyncCloneManager creates a new cached sync clone manager - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedSyncCloneManager) Close ¶
func (cbm *CachedSyncCloneManager) Close() error
Close cleans up cached manager resources - DISABLED (cache package removed) Simple implementation without external cache dependency.
func (*CachedSyncCloneManager) RefreshAllOptimizedWithCache ¶
func (cbm *CachedSyncCloneManager) RefreshAllOptimizedWithCache(ctx context.Context, targetPath, org, strategy string) (SyncCloneStats, error)
RefreshAllOptimizedWithCache performs optimized refresh with caching.
type ChangeFilter ¶
type ChangeFilter struct {
Organization string
Repository string
User string
Operation string
Category string
Since time.Time
Until time.Time
Limit int
Offset int
}
ChangeFilter for querying change records.
type ChangeLog ¶
type ChangeLog struct {
// contains filtered or unexported fields
}
ChangeLog manages configuration change history.
func NewChangeLog ¶
func NewChangeLog(client *RepoConfigClient, store ChangeStore) *ChangeLog
NewChangeLog creates a new change log manager.
func (*ChangeLog) ListChanges ¶
func (cl *ChangeLog) ListChanges(ctx context.Context, filter ChangeFilter) ([]*ChangeRecord, error)
ListChanges retrieves change records based on filter criteria.
func (*ChangeLog) RecordChange ¶
func (cl *ChangeLog) RecordChange(ctx context.Context, change *ChangeRecord) error
RecordChange creates and stores a change record.
func (*ChangeLog) RecordRepositoryUpdate ¶
func (cl *ChangeLog) RecordRepositoryUpdate(ctx context.Context, owner, repo string, before, after *Repository, description string) error
RecordRepositoryUpdate creates a change record for repository updates.
func (*ChangeLog) Rollback ¶
func (cl *ChangeLog) Rollback(ctx context.Context, request *RollbackRequest) (*RollbackResult, error)
Rollback performs a rollback operation to revert a previous change.
type ChangeLogger ¶
type ChangeLogger struct {
// contains filtered or unexported fields
}
ChangeLogger provides comprehensive logging for repository configuration changes.
func NewChangeLogger ¶
func NewChangeLogger(changelog *ChangeLog, options *LoggerOptions) *ChangeLogger
NewChangeLogger creates a new change logger with the specified options.
func (*ChangeLogger) CreateOperationContext ¶
func (cl *ChangeLogger) CreateOperationContext(requestID, operation string) *operationContext
CreateOperationContext creates a new operation context for logging.
func (*ChangeLogger) GetLogSummary ¶
func (cl *ChangeLogger) GetLogSummary(ctx context.Context, since time.Time) (*LogSummary, error)
GetLogSummary returns a summary of recent log entries.
func (*ChangeLogger) LogBulkOperation ¶
func (cl *ChangeLogger) LogBulkOperation(ctx context.Context, opCtx *operationContext, level LogLevel, operation string, stats *bulkOperationStats, err error) error
LogBulkOperation logs bulk operations with aggregated statistics.
func (*ChangeLogger) LogOperation ¶
func (cl *ChangeLogger) LogOperation(ctx context.Context, opCtx *operationContext, level LogLevel, operation, category, message string, err error) error
LogOperation logs a general operation with context.
func (*ChangeLogger) LogRepositoryChange ¶
func (cl *ChangeLogger) LogRepositoryChange(ctx context.Context, opCtx *operationContext, changeRecord *ChangeRecord, level LogLevel, message string, err error) error
LogRepositoryChange logs a repository configuration change with full context.
type ChangeLoggerInterface ¶
type ChangeLoggerInterface interface {
LogOperation(ctx context.Context, operation LogOperationRecord) error
GetOperationHistory(ctx context.Context, filters LogFilters) ([]LogOperationRecord, error)
SetLogLevel(ctx context.Context, level LogLevelType) error
}
ChangeLoggerInterface defines the interface for logging repository changes.
type ChangeRecord ¶
type ChangeRecord struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
User string `json:"user"`
Organization string `json:"organization"`
Repository string `json:"repository"`
Operation string `json:"operation"` // create, update, delete
Category string `json:"category"` // settings, branch_protection, permissions, etc.
Before map[string]interface{} `json:"before,omitempty"`
After map[string]interface{} `json:"after,omitempty"`
Description string `json:"description"`
Source string `json:"source"` // cli, api, web
RequestID string `json:"requestId,omitempty"`
}
ChangeRecord represents a single configuration change.
type ChangeStore ¶
type ChangeStore interface {
Store(ctx context.Context, record *ChangeRecord) error
Get(ctx context.Context, id string) (*ChangeRecord, error)
List(ctx context.Context, filter ChangeFilter) ([]*ChangeRecord, error)
Delete(ctx context.Context, id string) error
}
ChangeStore interface for persisting change records.
type ChangeType ¶
type ChangeType string
const ( ChangeTypeAdded ChangeType = "added" ChangeTypeModified ChangeType = "modified" ChangeTypeRemoved ChangeType = "removed" )
type ChannelType ¶
type ChannelType string
const ( ChannelTypeEmail ChannelType = "email" ChannelTypeSlack ChannelType = "slack" ChannelTypeWebhook ChannelType = "webhook" ChannelTypeSMS ChannelType = "sms" ChannelTypePager ChannelType = "pager" )
type CloneError ¶
type CloneError struct {
Repository string
Operation string
Error error
Attempt int
Timestamp time.Time
MemoryUsage int64
}
CloneError represents a clone operation error with context.
type CloneService ¶
type CloneService interface {
// Clone a single repository
CloneRepository(ctx context.Context, repo RepositoryInfo, targetPath, strategy string) error
// Bulk operations
RefreshAll(ctx context.Context, targetPath, orgName, strategy string) error
CloneOrganization(ctx context.Context, orgName, targetPath, strategy string) error
// Strategy management
SetStrategy(ctx context.Context, strategy string) error
GetSupportedStrategies(ctx context.Context) ([]string, error)
}
CloneService defines the interface for repository cloning operations.
func NewCloneService ¶
func NewCloneService( apiClient APIClient, gitClient GitCommandInterface, fileSystem FileSystemInterface, logger Logger, ) CloneService
NewCloneService creates a new clone service with dependencies.
type CloneServiceConfig ¶
CloneServiceConfig holds configuration for clone service.
func DefaultCloneServiceConfig ¶
func DefaultCloneServiceConfig() *CloneServiceConfig
DefaultCloneServiceConfig returns default clone service configuration.
type CloneStats ¶
type CloneStats struct {
TotalRepositories int
Successful int
Failed int
Skipped int
MemoryPeakUsage int64
TotalDuration time.Duration
AverageSpeed float64 // repos per second
ErrorDetails []CloneError
}
CloneStats tracks bulk clone operation statistics.
type CommunicationPlan ¶
type CommunicationPlan struct {
Channels []string `json:"channels"`
NotificationTemplate string `json:"notification_template"`
EscalationContacts []string `json:"escalation_contacts"`
AdvanceNoticePeriod time.Duration `json:"advance_notice_period"`
}
Additional supporting configuration types.
type CompatibilityAnalysisResult ¶
type CompatibilityAnalysisResult struct {
Compatible bool `json:"compatible"`
Issues []CompatibilityIssue `json:"issues"`
ChecksSkipped bool `json:"checks_skipped"`
Reason string `json:"reason,omitempty"`
TestResults []CompatibilityTestResult `json:"test_results,omitempty"`
}
type CompatibilityCheckConfig ¶
type CompatibilityCheckConfig struct {
Enabled bool `json:"enabled"`
MatrixTesting MatrixTestingConfig `json:"matrixTesting"`
DependencyGraphAnalysis bool `json:"dependencyGraphAnalysis"`
ConflictDetection ConflictDetectionConfig `json:"conflictDetection"`
IntegrationTesting IntegrationTestingConfig `json:"integrationTesting"`
PerformanceImpactAnalysis bool `json:"performanceImpactAnalysis"`
SecurityImpactAnalysis bool `json:"securityImpactAnalysis"`
CompatibilityMatrix []CompatibilityMatrixEntry `json:"compatibilityMatrix"`
RegressionTesting RegressionTestingConfig `json:"regressionTesting"`
}
CompatibilityCheckConfig defines compatibility checking requirements.
type CompatibilityIssue ¶
type CompatibilityTestResult ¶
type CompatibilityTestResult struct {
TestName string `json:"test_name"`
Passed bool `json:"passed"`
Details string `json:"details,omitempty"`
}
Additional supporting types for comprehensive functionality.
type ComplianceConfig ¶
type ComplianceConfig struct {
Frameworks []ComplianceFramework `json:"frameworks"`
AuditTrailRequired bool `json:"audit_trail_required"`
DocumentationRequired bool `json:"documentation_required"`
ApprovalEvidence bool `json:"approval_evidence"`
RetentionPeriod time.Duration `json:"retention_period"`
}
ComplianceConfig defines compliance-related settings.
type ComplianceFramework ¶
type ComplianceFramework struct {
Name string `json:"name"`
Version string `json:"version"`
Requirements []Requirement `json:"requirements"`
}
ComplianceFramework defines compliance framework requirements.
type ComplianceReport ¶
type ComplianceReport struct {
Organization string `json:"organization"`
GeneratedAt time.Time `json:"generated_at"`
TotalRepositories int `json:"total_repositories"`
CompliantRepos int `json:"compliant_repos"`
NonCompliantRepos int `json:"non_compliant_repos"`
Violations []ComplianceViolation `json:"violations"`
ComplianceScore float64 `json:"compliance_score"`
Recommendations []string `json:"recommendations"`
}
ComplianceReport represents a compliance report for webhooks.
type ComplianceViolation ¶
type ComplianceViolation struct {
Repository string `json:"repository"`
PolicyID string `json:"policy_id"`
RuleID string `json:"rule_id"`
ViolationType string `json:"violation_type"`
Description string `json:"description"`
Severity string `json:"severity"`
Remediation string `json:"remediation"`
}
ComplianceViolation represents a compliance violation.
type ConditionEvaluator ¶
type ConditionEvaluator interface {
// Core evaluation methods
EvaluateConditions(ctx context.Context, conditions *AutomationConditions, event *GitHubEvent, context *EvaluationContext) (*EvaluationResult, error)
EvaluatePayloadMatcher(ctx context.Context, matcher *PayloadMatcher, payload map[string]interface{}) (bool, error)
// Specific condition type evaluators
EvaluateEventConditions(event *GitHubEvent, conditions *AutomationConditions) (bool, error)
EvaluateRepositoryConditions(ctx context.Context, repoInfo *RepositoryInfo, conditions *AutomationConditions) (bool, error)
EvaluateTimeConditions(timestamp time.Time, conditions *AutomationConditions) (bool, error)
EvaluateContentConditions(ctx context.Context, event *GitHubEvent, conditions *AutomationConditions) (bool, error)
// Utility methods
ValidateConditions(conditions *AutomationConditions) (*ConditionValidationResult, error)
ExplainEvaluation(ctx context.Context, conditions *AutomationConditions, event *GitHubEvent) (*EvaluationExplanation, error)
}
ConditionEvaluator provides functionality to evaluate automation rule conditions.
func NewConditionEvaluator ¶
func NewConditionEvaluator(logger Logger, apiClient APIClient) ConditionEvaluator
NewConditionEvaluator creates a new condition evaluator.
type ConditionExplanation ¶
type ConditionExplanation struct {
Type string `json:"type"`
Description string `json:"description"`
Expected interface{} `json:"expected"`
Actual interface{} `json:"actual"`
Result bool `json:"result"`
Reason string `json:"reason"`
}
ConditionExplanation explains how a specific condition was evaluated.
type ConditionOperator ¶
type ConditionOperator string
ConditionOperator defines how multiple conditions are combined.
const ( ConditionOperatorAND ConditionOperator = "AND" ConditionOperatorOR ConditionOperator = "OR" ConditionOperatorNOT ConditionOperator = "NOT" )
type ConditionType ¶
type ConditionType string
const ( ConditionTypeSeverity ConditionType = "severity" ConditionTypePackage ConditionType = "package" ConditionTypeVersion ConditionType = "version" ConditionTypeCVSS ConditionType = "cvss" ConditionTypeAge ConditionType = "age" ConditionTypeRepository ConditionType = "repository" ConditionTypeEcosystem ConditionType = "ecosystem" )
type ConditionValidationError ¶
type ConditionValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Suggestion string `json:"suggestion,omitempty"`
}
ConditionValidationError represents a validation error.
type ConditionValidationResult ¶
type ConditionValidationResult struct {
Valid bool `json:"valid"`
Errors []ConditionValidationError `json:"errors,omitempty"`
Warnings []ConditionValidationWarning `json:"warnings,omitempty"`
JSONPathValidations []JSONPathValidationResult `json:"jsonpathValidations,omitempty"`
RegexValidations []RegexValidationResult `json:"regexValidations,omitempty"`
}
ConditionValidationResult represents the result of condition validation.
type ConditionValidationWarning ¶
type ConditionValidationWarning struct {
Field string `json:"field"`
Message string `json:"message"`
Suggestion string `json:"suggestion,omitempty"`
}
ConditionValidationWarning represents a validation warning.
type ConfigMetadata ¶
type ConfigMetadata struct {
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Author string `json:"author" yaml:"author"`
CreatedAt time.Time `json:"created_at" yaml:"created_at"`
UpdatedAt time.Time `json:"updated_at" yaml:"updated_at"`
Version string `json:"version" yaml:"version"`
Tags map[string]string `json:"tags,omitempty" yaml:"tags,omitempty"`
}
ConfigMetadata contains metadata about the configuration.
type ConfigStorage ¶
type ConfigStorage interface {
SavePolicy(ctx context.Context, policy *WebhookPolicy) error
GetPolicy(ctx context.Context, org, policyID string) (*WebhookPolicy, error)
ListPolicies(ctx context.Context, org string) ([]*WebhookPolicy, error)
DeletePolicy(ctx context.Context, org, policyID string) error
SaveOrganizationConfig(ctx context.Context, config *OrganizationWebhookConfig) error
GetOrganizationConfig(ctx context.Context, org string) (*OrganizationWebhookConfig, error)
}
ConfigStorage defines the interface for storing webhook configuration data.
type ConfigurationChange ¶
type ConfigurationChange struct {
Type ChangeType `json:"type"`
Field string `json:"field"`
OldValue interface{} `json:"old_value,omitempty"`
NewValue interface{} `json:"new_value"`
Description string `json:"description"`
}
ConfigurationChange represents a change made to Dependabot configuration.
type ConfirmationModeType ¶
type ConfirmationModeType int
ConfirmationModeType represents the confirmation mode.
const ( ConfirmationModeInteractive ConfirmationModeType = iota ConfirmationModeAutoApprove ConfirmationModeAutoDeny ConfirmationModeDryRun )
type ConfirmationPrompt ¶
type ConfirmationPrompt struct {
// AutoConfirm bypasses prompts when true (useful for automation)
AutoConfirm bool
// contains filtered or unexported fields
}
ConfirmationPrompt handles user confirmation for sensitive operations.
func NewAutoConfirmationPrompt ¶
func NewAutoConfirmationPrompt() *ConfirmationPrompt
NewAutoConfirmationPrompt creates a confirmation prompt that auto-confirms all prompts.
func NewConfirmationPrompt ¶
func NewConfirmationPrompt() *ConfirmationPrompt
NewConfirmationPrompt creates a new confirmation prompt handler.
func (*ConfirmationPrompt) AnalyzeRepositoryChanges ¶
func (cp *ConfirmationPrompt) AnalyzeRepositoryChanges(ctx context.Context, owner, repo string, before, after *RepositoryConfig) []SensitiveChange
AnalyzeRepositoryChanges analyzes repository configuration changes for sensitivity.
func (*ConfirmationPrompt) RequestConfirmation ¶
func (cp *ConfirmationPrompt) RequestConfirmation(ctx context.Context, request *ConfirmationRequest) (*ConfirmationResult, error)
RequestConfirmation requests user confirmation for sensitive changes.
type ConfirmationPromptRecord ¶
type ConfirmationPromptRecord struct {
Title string `json:"title"`
Description string `json:"description"`
Repository string `json:"repository"`
Operation string `json:"operation"`
Risk RiskLevelType `json:"risk"`
Impact string `json:"impact"`
Metadata map[string]interface{} `json:"metadata"`
}
ConfirmationPromptRecord represents a confirmation request.
type ConfirmationRequest ¶
type ConfirmationRequest struct {
Changes []SensitiveChange `json:"changes"`
Operation string `json:"operation"` // bulk_update, rollback, etc.
Target string `json:"target"` // organization or repository name
DryRun bool `json:"dry_run"`
BatchSize int `json:"batch_size"` // number of repositories affected
Description string `json:"description"`
}
ConfirmationRequest contains details for a confirmation request.
type ConfirmationResult ¶
type ConfirmationResult struct {
Confirmed bool `json:"confirmed"`
UserChoice string `json:"user_choice"` // yes, no, skip, abort
SkippedRisks []RiskLevel `json:"skipped_risks,omitempty"`
Reason string `json:"reason,omitempty"`
}
ConfirmationResult contains the result of a confirmation request.
type ConfirmationServiceInterface ¶
type ConfirmationServiceInterface interface {
ConfirmOperation(ctx context.Context, prompt *ConfirmationPromptRecord) (bool, error)
ConfirmBulkOperation(ctx context.Context, operations []OperationRecord) ([]bool, error)
SetConfirmationMode(ctx context.Context, mode ConfirmationModeType) error
}
ConfirmationServiceInterface defines the interface for user confirmation operations.
type ConflictDetectionConfig ¶
type ConflictDetectionConfig struct {
Enabled bool `json:"enabled"`
CheckTransitiveDependencies bool `json:"check_transitive_dependencies"`
ResolveConflictsAutomatically bool `json:"resolve_conflicts_automatically"`
ConflictResolutionStrategy string `json:"conflict_resolution_strategy"`
IgnoredConflicts []string `json:"ignored_conflicts,omitempty"`
}
type ConflictResolution ¶
type ConflictResolution string
ConflictResolution defines how to handle conflicts.
const ( ConflictResolutionSkip ConflictResolution = "skip" // Skip if webhook exists ConflictResolutionOverwrite ConflictResolution = "overwrite" // Overwrite existing webhook ConflictResolutionMerge ConflictResolution = "merge" // Merge configurations ConflictResolutionError ConflictResolution = "error" // Fail on conflict )
type ConstraintPriority ¶
type ConstraintPriority string
const ( ConstraintPriorityLow ConstraintPriority = "low" ConstraintPriorityMedium ConstraintPriority = "medium" ConstraintPriorityHigh ConstraintPriority = "high" ConstraintPriorityCritical ConstraintPriority = "critical" )
type CursorPagination ¶
type CursorPagination struct {
After string
Before string
First int
Last int
HasNext bool
HasPrev bool
EndCursor string
StartCursor string
}
CursorPagination represents cursor-based pagination for efficient large dataset traversal.
type CustomMetric ¶
type CustomTestSuite ¶
type CustomValidationRule ¶
type DataMigrationHandling ¶
type DataPoint ¶
type DataPoint struct {
Timestamp time.Time `json:"timestamp"`
Value float64 `json:"value"`
Count int `json:"count"`
}
DataPoint represents a single data point in trend analysis.
type DefaultPermissions ¶
type DefaultPermissions string
DefaultPermissions defines the default permission level for workflow tokens.
const ( // DefaultPermissionsRead grants read-only permissions to workflow tokens. DefaultPermissionsRead DefaultPermissions = "read" // DefaultPermissionsWrite grants write permissions to workflow tokens. DefaultPermissionsWrite DefaultPermissions = "write" // DefaultPermissionsRestricted restricts permissions for workflow tokens. DefaultPermissionsRestricted DefaultPermissions = "restricted" )
type DependabotAllowedUpdate ¶
type DependabotAllowedUpdate struct {
DependencyType string `yaml:"dependency-type,omitempty" json:"dependency_type,omitempty"`
DependencyName string `yaml:"dependency-name,omitempty" json:"dependency_name,omitempty"`
UpdateType string `yaml:"update-type,omitempty" json:"update_type,omitempty"`
}
DependabotAllowedUpdate defines which updates are allowed.
type DependabotCommitMessage ¶
type DependabotCommitMessage struct {
Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`
PrefixDevelopment string `yaml:"prefix-development,omitempty" json:"prefix_development,omitempty"`
Include string `yaml:"include,omitempty" json:"include,omitempty"`
}
DependabotCommitMessage defines commit message preferences.
type DependabotConfig ¶
type DependabotConfig struct {
Version int `yaml:"version" json:"version"`
Updates []DependabotUpdateRule `yaml:"updates" json:"updates"`
// Registries for private package managers
Registries map[string]DependabotRegistry `yaml:"registries,omitempty" json:"registries,omitempty"`
}
DependabotConfig represents the complete Dependabot configuration.
type DependabotConfigManager ¶
type DependabotConfigManager struct {
// contains filtered or unexported fields
}
DependabotConfigManager manages Dependabot configurations for repositories.
func NewDependabotConfigManager ¶
func NewDependabotConfigManager(logger Logger, apiClient APIClient) *DependabotConfigManager
NewDependabotConfigManager creates a new Dependabot configuration manager.
func (*DependabotConfigManager) CreateDefaultConfig ¶
func (dm *DependabotConfigManager) CreateDefaultConfig(ctx context.Context, organization, repository string, ecosystems []string) (*DependabotConfig, error)
CreateDefaultConfig creates a default Dependabot configuration for a repository.
func (*DependabotConfigManager) DetectEcosystems ¶
func (dm *DependabotConfigManager) DetectEcosystems(ctx context.Context, organization, repository string) ([]string, error)
DetectEcosystems detects package ecosystems in a repository.
func (*DependabotConfigManager) GetDependabotConfig ¶
func (dm *DependabotConfigManager) GetDependabotConfig(ctx context.Context, organization, repository string) (*DependabotConfig, error)
GetDependabotConfig retrieves the current Dependabot configuration for a repository.
func (*DependabotConfigManager) GetDependabotStatus ¶
func (dm *DependabotConfigManager) GetDependabotStatus(ctx context.Context, organization, repository string) (*DependabotStatus, error)
GetDependabotStatus retrieves the current status of Dependabot for a repository.
func (*DependabotConfigManager) UpdateDependabotConfig ¶
func (dm *DependabotConfigManager) UpdateDependabotConfig(ctx context.Context, organization, repository string, config *DependabotConfig) error
UpdateDependabotConfig updates the Dependabot configuration for a repository.
func (*DependabotConfigManager) ValidateConfig ¶
func (dm *DependabotConfigManager) ValidateConfig(config *DependabotConfig) error
ValidateConfig validates a Dependabot configuration.
type DependabotConfigSummary ¶
type DependabotConfigSummary struct {
TotalEcosystems int `json:"total_ecosystems"`
EnabledEcosystems []string `json:"enabled_ecosystems"`
UpdateSchedules map[string]string `json:"update_schedules"`
TotalIgnoredDeps int `json:"total_ignored_deps"`
GroupedUpdatesCount int `json:"grouped_updates_count"`
SecurityUpdatesEnabled bool `json:"security_updates_enabled"`
RegistriesConfigured int `json:"registries_configured"`
}
DependabotConfigSummary provides a summary of the current configuration.
type DependabotError ¶
type DependabotError struct {
ID string `json:"id"`
Type DependabotErrorType `json:"type"`
Message string `json:"message"`
Ecosystem string `json:"ecosystem,omitempty"`
Directory string `json:"directory,omitempty"`
Timestamp time.Time `json:"timestamp"`
Resolved bool `json:"resolved"`
}
DependabotError represents an error encountered by Dependabot.
type DependabotErrorType ¶
type DependabotErrorType string
const ( DependabotErrorTypeConfigInvalid DependabotErrorType = "config_invalid" DependabotErrorTypeEcosystemNotFound DependabotErrorType = "ecosystem_not_found" DependabotErrorTypeRegistryAuth DependabotErrorType = "registry_auth_failed" DependabotErrorTypePermissions DependabotErrorType = "insufficient_permissions" DependabotErrorTypeRateLimit DependabotErrorType = "rate_limit_exceeded" DependabotErrorTypeUnknown DependabotErrorType = "unknown_error" )
type DependabotGroup ¶
type DependabotGroup struct {
DependencyType string `yaml:"dependency-type,omitempty" json:"dependency_type,omitempty"`
UpdateTypes []string `yaml:"update-types,omitempty" json:"update_types,omitempty"`
Patterns []string `yaml:"patterns,omitempty" json:"patterns,omitempty"`
ExcludePattern []string `yaml:"exclude-patterns,omitempty" json:"exclude_patterns,omitempty"`
AppliesTo DependabotGroupAppliesTo `yaml:"applies-to,omitempty" json:"applies_to,omitempty"`
}
DependabotGroup defines dependency groups for batch updates.
type DependabotGroupAppliesTo ¶
type DependabotGroupAppliesTo struct {
VersionUpdates []string `yaml:"version-updates,omitempty" json:"version_updates,omitempty"`
SecurityUpdates bool `yaml:"security-updates,omitempty" json:"security_updates,omitempty"`
}
DependabotGroupAppliesTo defines version update constraints for groups.
type DependabotIgnoredUpdate ¶
type DependabotIgnoredUpdate struct {
DependencyName string `yaml:"dependency-name" json:"dependency_name"`
Versions []string `yaml:"versions,omitempty" json:"versions,omitempty"`
UpdateTypes []string `yaml:"update-types,omitempty" json:"update_types,omitempty"`
}
DependabotIgnoredUpdate defines dependencies to ignore.
type DependabotPolicyConfig ¶
type DependabotPolicyConfig struct {
ID string `json:"id"`
Name string `json:"name"`
Organization string `json:"organization"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
DefaultConfig DependabotConfig `json:"default_config"`
EcosystemPolicies map[string]EcosystemPolicy `json:"ecosystem_policies"`
SecurityPolicies SecurityPolicySettings `json:"security_policies"`
ApprovalRequirements ApprovalRequirements `json:"approval_requirements"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Version int `json:"version"`
}
DependabotPolicyConfig represents organization-wide Dependabot policies.
type DependabotPolicyManager ¶
type DependabotPolicyManager struct {
// contains filtered or unexported fields
}
DependabotPolicyManager manages organization-wide Dependabot policies.
func NewDependabotPolicyManager ¶
func NewDependabotPolicyManager(logger Logger, apiClient APIClient, configManager *DependabotConfigManager) *DependabotPolicyManager
NewDependabotPolicyManager creates a new Dependabot policy manager.
func (*DependabotPolicyManager) ApplyPolicyToOrganization ¶
func (pm *DependabotPolicyManager) ApplyPolicyToOrganization(ctx context.Context, policyID, organization string) (*BulkPolicyOperation, error)
ApplyPolicyToOrganization applies a policy to all repositories in an organization.
func (*DependabotPolicyManager) CreatePolicy ¶
func (pm *DependabotPolicyManager) CreatePolicy(_ context.Context, policy *DependabotPolicyConfig) error
CreatePolicy creates a new organization-wide Dependabot policy.
func (*DependabotPolicyManager) DeletePolicy ¶
func (pm *DependabotPolicyManager) DeletePolicy(ctx context.Context, policyID string) error
DeletePolicy deletes a policy.
func (*DependabotPolicyManager) EvaluateRepositoryCompliance ¶
func (pm *DependabotPolicyManager) EvaluateRepositoryCompliance(ctx context.Context, policyID, organization, repository string) (*PolicyEvaluationResult, error)
EvaluateRepositoryCompliance evaluates a repository against a policy.
func (*DependabotPolicyManager) GenerateOrganizationReport ¶
func (pm *DependabotPolicyManager) GenerateOrganizationReport(ctx context.Context, policyID, organization string) (*OrganizationPolicyReport, error)
GenerateOrganizationReport generates a comprehensive compliance report.
func (*DependabotPolicyManager) GetPolicy ¶
func (pm *DependabotPolicyManager) GetPolicy(_ context.Context, policyID string) (*DependabotPolicyConfig, error)
GetPolicy retrieves a policy by ID.
func (*DependabotPolicyManager) UpdatePolicy ¶
func (pm *DependabotPolicyManager) UpdatePolicy(_ context.Context, policy *DependabotPolicyConfig) error
UpdatePolicy updates an existing policy.
type DependabotPolicyViolation ¶
type DependabotPolicyViolation struct {
ID string `json:"id"`
Type DependabotPolicyViolationType `json:"type"`
Severity PolicySeverity `json:"severity"`
Title string `json:"title"`
Description string `json:"description"`
Ecosystem string `json:"ecosystem,omitempty"`
Suggestion string `json:"suggestion"`
AutoFixable bool `json:"auto_fixable"`
References []string `json:"references,omitempty"`
}
DependabotPolicyViolation represents a violation of a Dependabot policy.
type DependabotPolicyViolationType ¶
type DependabotPolicyViolationType = PolicyViolationType
Type aliases for Dependabot-specific types.
const ( DependabotViolationTypeMissingConfig DependabotPolicyViolationType = "missing_config" DependabotViolationTypeInvalidConfig DependabotPolicyViolationType = "invalid_config" DependabotViolationTypeDisabledEcosystem DependabotPolicyViolationType = "disabled_ecosystem" DependabotViolationTypeInsufficientSchedule DependabotPolicyViolationType = "insufficient_schedule" DependabotViolationTypeExcessivePermissions DependabotPolicyViolationType = "excessive_permissions" DependabotViolationTypeMissingSecurityUpdates DependabotPolicyViolationType = "missing_security_updates" DependabotViolationTypeOutdatedPolicy DependabotPolicyViolationType = "outdated_policy" DependabotViolationTypeComplianceBreach DependabotPolicyViolationType = "compliance_breach" )
type DependabotRegistry ¶
type DependabotRegistry struct {
Type string `yaml:"type" json:"type"`
URL string `yaml:"url" json:"url"`
Username string `yaml:"username,omitempty" json:"username,omitempty"`
Password string `yaml:"password,omitempty" json:"password,omitempty"`
Key string `yaml:"key,omitempty" json:"key,omitempty"`
Token string `yaml:"token,omitempty" json:"token,omitempty"`
ReplaceBase bool `yaml:"replace-base,omitempty" json:"replace_base,omitempty"`
}
DependabotRegistry defines private package registry configuration.
type DependabotRepositoryOperationResult ¶
type DependabotRepositoryOperationResult struct {
Repository string `json:"repository"`
Status OperationResultStatus `json:"status"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
Duration time.Duration `json:"duration"`
Changes []ConfigurationChange `json:"changes,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
DependabotRepositoryOperationResult represents the result of an operation on a single repository.
type DependabotSchedule ¶
type DependabotSchedule struct {
Interval string `yaml:"interval" json:"interval"`
Day string `yaml:"day,omitempty" json:"day,omitempty"`
Time string `yaml:"time,omitempty" json:"time,omitempty"`
Timezone string `yaml:"timezone,omitempty" json:"timezone,omitempty"`
}
DependabotSchedule defines when Dependabot checks for updates.
type DependabotStatus ¶
type DependabotStatus struct {
Repository string `json:"repository"`
Organization string `json:"organization"`
Enabled bool `json:"enabled"`
ConfigExists bool `json:"config_exists"`
ConfigValid bool `json:"config_valid"`
LastUpdated time.Time `json:"last_updated"`
ActivePullRequests int `json:"active_pull_requests"`
RecentUpdates []DependabotUpdate `json:"recent_updates"`
Errors []DependabotError `json:"errors,omitempty"`
SupportedEcosystems []string `json:"supported_ecosystems"`
ConfigSummary DependabotConfigSummary `json:"config_summary"`
}
DependabotStatus represents the current status of Dependabot for a repository.
type DependabotUpdate ¶
type DependabotUpdate struct {
ID string `json:"id"`
Dependency string `json:"dependency"`
FromVersion string `json:"from_version"`
ToVersion string `json:"to_version"`
UpdateType string `json:"update_type"`
Ecosystem string `json:"ecosystem"`
PullRequestURL string `json:"pull_request_url,omitempty"`
Status DependabotUpdateStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
SecurityAdvisory *SecurityAdvisoryInfo `json:"security_advisory,omitempty"`
}
DependabotUpdate represents a Dependabot update activity.
type DependabotUpdateRule ¶
type DependabotUpdateRule struct {
PackageEcosystem string `yaml:"package-ecosystem" json:"package_ecosystem"`
Directory string `yaml:"directory" json:"directory"`
Schedule DependabotSchedule `yaml:"schedule" json:"schedule"`
VersioningStrategy string `yaml:"versioning-strategy,omitempty" json:"versioning_strategy,omitempty"`
AllowedUpdates []DependabotAllowedUpdate `yaml:"allow,omitempty" json:"allowed_updates,omitempty"`
IgnoredDependencies []DependabotIgnoredUpdate `yaml:"ignore,omitempty" json:"ignored_dependencies,omitempty"`
Reviewers []string `yaml:"reviewers,omitempty" json:"reviewers,omitempty"`
Assignees []string `yaml:"assignees,omitempty" json:"assignees,omitempty"`
Labels []string `yaml:"labels,omitempty" json:"labels,omitempty"`
PullRequestLimit int `yaml:"open-pull-requests-limit,omitempty" json:"pull_request_limit,omitempty"`
RebaseStrategy string `yaml:"rebase-strategy,omitempty" json:"rebase_strategy,omitempty"`
CommitMessage *DependabotCommitMessage `yaml:"commit-message,omitempty" json:"commit_message,omitempty"`
Groups map[string]DependabotGroup `yaml:"groups,omitempty" json:"groups,omitempty"`
RegistriesConfig []string `yaml:"registries,omitempty" json:"registries_config,omitempty"`
VendorUpdates bool `yaml:"vendor,omitempty" json:"vendor_updates,omitempty"`
InsecureExternalCode bool `yaml:"insecure-external-code-execution,omitempty" json:"insecure_external_code,omitempty"`
}
DependabotUpdateRule defines update rules for a package ecosystem.
type DependabotUpdateStatus ¶
type DependabotUpdateStatus string
Enum types.
const ( DependabotUpdateStatusPending DependabotUpdateStatus = "pending" DependabotUpdateStatusActive DependabotUpdateStatus = "active" DependabotUpdateStatusMerged DependabotUpdateStatus = "merged" DependabotUpdateStatusClosed DependabotUpdateStatus = "closed" DependabotUpdateStatusSuperseded DependabotUpdateStatus = "superseded" DependabotUpdateStatusFailed DependabotUpdateStatus = "failed" )
type DependabotViolationStatistics ¶
type DependabotViolationStatistics = ViolationStatistics
Type aliases for Dependabot-specific types.
type DependencyRiskAssessment ¶
type DependencyRiskAssessment struct {
OverallRisk string `json:"overall_risk"`
RiskFactors []RiskFactor `json:"risk_factors"`
Mitigations []string `json:"mitigations"`
BusinessImpact string `json:"business_impact"`
TechnicalImpact string `json:"technical_impact"`
}
type DependencyUpdate ¶
type DependencyUpdate struct {
Name string `json:"name"`
Ecosystem string `json:"ecosystem"`
CurrentVersion string `json:"current_version"`
ProposedVersion string `json:"proposed_version"`
}
Result types.
type DependencyUpdateRejection ¶
type DependencyUpdateRejection struct {
Update DependencyUpdate `json:"update"`
Reason string `json:"reason"`
}
type DependencyUpdateStrategy ¶
type DependencyUpdateStrategy string
Supporting types and enums.
const ( UpdateStrategyConservative DependencyUpdateStrategy = "conservative" UpdateStrategyModerate DependencyUpdateStrategy = "moderate" UpdateStrategyAggressive DependencyUpdateStrategy = "aggressive" UpdateStrategySecurityOnly DependencyUpdateStrategy = "security_only" UpdateStrategyCustom DependencyUpdateStrategy = "custom" )
type DependencyVersionAnalysis ¶
type DependencyVersionAnalysis struct {
DependencyName string `json:"dependency_name"`
Ecosystem string `json:"ecosystem"`
CurrentVersion string `json:"current_version"`
ProposedVersion string `json:"proposed_version"`
UpdateType string `json:"update_type"`
VersionConstraintCheck VersionConstraintCheckResult `json:"version_constraint_check"`
CompatibilityAnalysis CompatibilityAnalysisResult `json:"compatibility_analysis"`
SecurityImpact SecurityImpactAnalysis `json:"security_impact"`
PerformanceImpact PerformanceImpactAnalysis `json:"performance_impact"`
BreakingChangeAnalysis BreakingChangeAnalysisResult `json:"breaking_change_analysis"`
LicenseCompatibility LicenseCompatibilityResult `json:"license_compatibility"`
RiskAssessment DependencyRiskAssessment `json:"risk_assessment"`
RecommendedAction RecommendedAction `json:"recommended_action"`
TestingRecommendations []TestingRecommendation `json:"testing_recommendations"`
RollbackPlan RollbackPlan `json:"rollback_plan"`
Timeline UpdateTimeline `json:"timeline"`
ApprovalWorkflow ApprovalWorkflow `json:"approval_workflow"`
}
DependencyVersionAnalysis represents analysis results for a dependency version update.
type DependencyVersionPolicy ¶
type DependencyVersionPolicy struct {
ID string `json:"id"`
Name string `json:"name"`
Organization string `json:"organization"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
VersionConstraints map[string]VersionConstraintRule `json:"versionConstraints"`
EcosystemPolicies map[string]EcosystemVersionPolicy `json:"ecosystemPolicies"`
BreakingChangePolicy BreakingChangePolicy `json:"breakingChangePolicy"`
CompatibilityChecks CompatibilityCheckConfig `json:"compatibilityChecks"`
RollbackPolicy RollbackPolicy `json:"rollbackPolicy"`
ApprovalRequirements VersionUpdateApprovalRequirements `json:"approvalRequirements"`
NotificationSettings VersionPolicyNotificationConfig `json:"notificationSettings"`
TestingRequirements TestingRequirements `json:"testingRequirements"`
ReleaseWindows []ReleaseWindow `json:"releaseWindows"`
MetricsTracking MetricsTrackingConfig `json:"metricsTracking"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Version int `json:"version"`
}
DependencyVersionPolicy defines version management policies for dependencies.
type DependencyVersionPolicyManager ¶
type DependencyVersionPolicyManager struct {
// contains filtered or unexported fields
}
DependencyVersionPolicyManager manages dependency version policies for repositories.
func NewDependencyVersionPolicyManager ¶
func NewDependencyVersionPolicyManager(logger Logger, apiClient APIClient, dependabotManager *DependabotConfigManager, securityPolicyManager *SecurityUpdatePolicyManager) *DependencyVersionPolicyManager
NewDependencyVersionPolicyManager creates a new dependency version policy manager.
func (*DependencyVersionPolicyManager) AnalyzeDependencyVersionUpdate ¶
func (dvm *DependencyVersionPolicyManager) AnalyzeDependencyVersionUpdate(ctx context.Context, policyID string, dependencyName, currentVersion, proposedVersion, ecosystem string) (*DependencyVersionAnalysis, error)
AnalyzeDependencyVersionUpdate analyzes a proposed dependency version update.
func (*DependencyVersionPolicyManager) ApplyVersionConstraints ¶
func (dvm *DependencyVersionPolicyManager) ApplyVersionConstraints(ctx context.Context, policyID string, updates []DependencyUpdate) (*VersionConstraintApplicationResult, error)
ApplyVersionConstraints applies version constraints to a list of dependency updates.
func (*DependencyVersionPolicyManager) CreateDependencyVersionPolicy ¶
func (dvm *DependencyVersionPolicyManager) CreateDependencyVersionPolicy(ctx context.Context, policy *DependencyVersionPolicy) error
CreateDependencyVersionPolicy creates a new dependency version policy.
type DeprecationPolicy ¶
type DeprecationPolicy struct {
AllowDeprecatedVersions bool `json:"allow_deprecated_versions"`
DeprecationWarningPeriod time.Duration `json:"deprecation_warning_period"`
ForceUpgradeAfterEOL bool `json:"force_upgrade_after_eol"`
EOLNotificationPeriod time.Duration `json:"eol_notification_period"`
}
type DetectedChange ¶
type DetectionMethod ¶
type DetectionMethod string
const ( DetectionMethodSemver DetectionMethod = "semver" DetectionMethodAPI DetectionMethod = "api_diff" DetectionMethodSchema DetectionMethod = "schema_diff" DetectionMethodCustom DetectionMethod = "custom_rules" DetectionMethodChangeLog DetectionMethod = "changelog_analysis" DetectionMethodBinary DetectionMethod = "binary_diff" )
type DetectionRule ¶
type DetectionRule struct {
Pattern string `json:"pattern"`
Severity string `json:"severity"`
Description string `json:"description"`
Weight float64 `json:"weight"`
}
Additional supporting types.
type EcosystemPolicy ¶
type EcosystemPolicy struct {
Ecosystem string `json:"ecosystem"`
Enabled bool `json:"enabled"`
RequiredReviewers int `json:"required_reviewers"`
AllowedUpdateTypes []string `json:"allowed_update_types"`
BlockedDependencies []string `json:"blocked_dependencies"`
MaxPullRequestsPerDay int `json:"max_pull_requests_per_day"`
AutoMergeEnabled bool `json:"auto_merge_enabled"`
AutoMergeUpdateTypes []string `json:"auto_merge_update_types"`
RequiredStatusChecks []string `json:"required_status_checks"`
MinSecuritySeverity string `json:"min_security_severity"`
}
EcosystemPolicy defines policies for specific package ecosystems.
type EcosystemStats ¶
type EcosystemStats struct {
Ecosystem string `json:"ecosystem"`
TotalRepositories int `json:"total_repositories"`
EnabledRepositories int `json:"enabled_repositories"`
ComplianceRate float64 `json:"compliance_rate"`
CommonViolations []string `json:"common_violations"`
}
EcosystemStats provides statistics for a specific ecosystem.
type EcosystemVersionPolicy ¶
type EcosystemVersionPolicy struct {
Ecosystem string `json:"ecosystem"`
Enabled bool `json:"enabled"`
DefaultUpdateStrategy DependencyUpdateStrategy `json:"defaultUpdateStrategy"`
AllowMajorUpdates bool `json:"allowMajorUpdates"`
AllowMinorUpdates bool `json:"allowMinorUpdates"`
AllowPatchUpdates bool `json:"allowPatchUpdates"`
RequireSecurityUpdates bool `json:"requireSecurityUpdates"`
MaxVersionAge time.Duration `json:"maxVersionAge"`
DeprecationPolicy DeprecationPolicy `json:"deprecationPolicy"`
LicenseRestrictions []LicenseRestriction `json:"licenseRestrictions"`
PerformanceRequirements PerformanceRequirements `json:"performanceRequirements"`
QualityGates []QualityGate `json:"qualityGates"`
CustomValidationRules []CustomValidationRule `json:"customValidationRules"`
}
EcosystemVersionPolicy defines version policies specific to package ecosystems.
type EmergencyApprovalRule ¶
type EmergencyApprovalRule struct {
Enabled bool `json:"enabled"`
EmergencyApprovers []string `json:"emergency_approvers"`
MaxEmergencyDuration time.Duration `json:"max_emergency_duration"`
PostEmergencyReview bool `json:"post_emergency_review"`
JustificationRequired bool `json:"justification_required"`
}
type EmergencyOverride ¶
type EngineMetrics ¶
type EngineMetrics struct {
EventsProcessed int64 `json:"eventsProcessed"`
RulesEvaluated int64 `json:"rulesEvaluated"`
RulesExecuted int64 `json:"rulesExecuted"`
ExecutionErrors int64 `json:"executionErrors"`
AverageExecutionTime time.Duration `json:"averageExecutionTime"`
EventTypeDistribution map[string]int64 `json:"eventTypeDistribution"`
ExecutionsByStatus map[ExecutionStatus]int64 `json:"executionsByStatus"`
LastProcessedEvent time.Time `json:"lastProcessedEvent"`
StartTime time.Time `json:"startTime"`
// contains filtered or unexported fields
}
EngineMetrics holds metrics for the automation engine.
type EnvironmentBranchPolicy ¶
type EnvironmentBranchPolicy string
EnvironmentBranchPolicy defines branch protection policy for environments.
const ( EnvironmentBranchPolicyAll EnvironmentBranchPolicy = "all" EnvironmentBranchPolicyProtected EnvironmentBranchPolicy = "protected" EnvironmentBranchPolicySelected EnvironmentBranchPolicy = "selected" EnvironmentBranchPolicyNone EnvironmentBranchPolicy = "none" )
type EnvironmentInfo ¶
type EnvironmentInfo struct {
Name string `json:"name"`
ProtectionRules []ProtectionRule `json:"protectionRules,omitempty"`
DeploymentBranches []string `json:"deploymentBranches,omitempty"`
Secrets []SecretInfo `json:"secrets,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
}
EnvironmentInfo represents information about a repository environment.
type EnvironmentPolicy ¶
type EnvironmentPolicy struct {
Name string `json:"name" yaml:"name"`
RequiredReviewers []string `json:"requiredReviewers,omitempty" yaml:"requiredReviewers,omitempty"`
RequiredReviewerTeams []string `json:"requiredReviewerTeams,omitempty" yaml:"requiredReviewerTeams,omitempty"`
WaitTimer time.Duration `json:"waitTimer,omitempty" yaml:"waitTimer,omitempty"`
BranchPolicyType EnvironmentBranchPolicy `json:"branchPolicyType" yaml:"branchPolicyType"`
ProtectedBranches []string `json:"protectedBranches,omitempty" yaml:"protectedBranches,omitempty"`
BranchPatterns []string `json:"branchPatterns,omitempty" yaml:"branchPatterns,omitempty"`
RequireDeploymentBranch bool `json:"requireDeploymentBranch" yaml:"requireDeploymentBranch"`
PreventSelfReview bool `json:"preventSelfReview" yaml:"preventSelfReview"`
Secrets []string `json:"secrets,omitempty" yaml:"secrets,omitempty"`
Variables map[string]string `json:"variables,omitempty" yaml:"variables,omitempty"`
}
EnvironmentPolicy defines policy for deployment environments.
type EscalationAction ¶
type EscalationAction struct {
Type string `json:"type"`
Target string `json:"target"`
Parameters map[string]string `json:"parameters,omitempty"`
}
EscalationAction defines what to do during escalation.
type EscalationCondition ¶
type EscalationCondition struct {
Type string `json:"type"`
Operator string `json:"operator"`
Value interface{} `json:"value"`
}
EscalationCondition defines when escalation should occur.
type EscalationRule ¶
type EscalationRule struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
TriggerAfter time.Duration `json:"trigger_after"`
Conditions []EscalationCondition `json:"conditions"`
Actions []EscalationAction `json:"actions"`
MaxEscalations int `json:"max_escalations"`
}
EscalationRule defines when and how to escalate unresolved vulnerabilities.
type EscalationTarget ¶
type EscalationTarget struct {
Level int `json:"level"`
Users []string `json:"users"`
Teams []string `json:"teams,omitempty"`
External []string `json:"external,omitempty"`
}
EscalationTarget defines who to notify during escalation.
type EvaluationContext ¶
type EvaluationContext struct {
Repository *RepositoryInfo `json:"repository,omitempty"`
Organization *OrganizationInfo `json:"organization,omitempty"`
User *UserInfo `json:"user,omitempty"`
Environment string `json:"environment,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Timezone *time.Location `json:"-"`
}
EvaluationContext provides additional context for condition evaluation.
type EvaluationExplanation ¶
type EvaluationExplanation struct {
RuleID string `json:"ruleId"`
EventID string `json:"eventId"`
OverallResult bool `json:"overallResult"`
LogicalOperator ConditionOperator `json:"logicalOperator"`
ConditionBreakdown []ConditionExplanation `json:"conditionBreakdown"`
PayloadExplanations []PayloadMatchExplanation `json:"payloadExplanations"`
TimeEvaluation *TimeEvaluationExplanation `json:"timeEvaluation,omitempty"`
RepositoryEvaluation *RepositoryEvaluationExplanation `json:"repositoryEvaluation,omitempty"`
Summary string `json:"summary"`
}
EvaluationExplanation provides detailed explanation of how conditions were evaluated.
type EvaluationResult ¶
type EvaluationResult struct {
Matched bool `json:"matched"`
MatchedConditions []string `json:"matchedConditions"`
FailedConditions []string `json:"failedConditions"`
SkippedConditions []string `json:"skippedConditions"`
EvaluationTime time.Duration `json:"evaluationTime"`
SubConditionResults map[string]*EvaluationResult `json:"subConditionResults,omitempty"`
PayloadMatchResults []PayloadMatchResult `json:"payloadMatchResults,omitempty"`
Errors []string `json:"errors,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Debug map[string]interface{} `json:"debug,omitempty"`
}
EvaluationResult represents the result of condition evaluation.
type EventAction ¶
type EventAction string
EventAction defines specific actions within events.
const ( ActionOpened EventAction = "opened" ActionClosed EventAction = "closed" ActionSynchronize EventAction = "synchronize" ActionCreated EventAction = "created" ActionDeleted EventAction = "deleted" ActionEdited EventAction = "edited" ActionCompleted EventAction = "completed" ActionRequested EventAction = "requested" ActionSubmitted EventAction = "submitted" ActionPublished EventAction = "published" ActionAdded EventAction = "added" ActionRemoved EventAction = "removed" )
type EventFilter ¶
type EventFilter struct {
Organization string `json:"organization,omitempty"`
Repository string `json:"repository,omitempty"`
EventTypes []EventType `json:"event_types,omitempty"`
Actions []EventAction `json:"actions,omitempty"`
Sender string `json:"sender,omitempty"`
BranchPattern string `json:"branch_pattern,omitempty"`
FilePattern string `json:"file_pattern,omitempty"`
TimeRange *TimeRange `json:"time_range,omitempty"`
}
EventFilter defines criteria for filtering events.
type EventHandler ¶
type EventHandler interface {
HandleEvent(ctx context.Context, event *GitHubEvent) error
GetSupportedActions() []EventAction
GetPriority() int // Higher number = higher priority
}
EventHandler defines the interface for handling specific event types.
type EventMetrics ¶
type EventMetrics struct {
TotalEventsReceived int64 `json:"total_events_received"`
TotalEventsProcessed int64 `json:"total_events_processed"`
TotalEventsFailed int64 `json:"total_events_failed"`
EventsByType map[string]int64 `json:"events_by_type"`
EventsByOrganization map[string]int64 `json:"events_by_organization"`
AverageProcessingTime time.Duration `json:"average_processing_time"`
LastEventAt time.Time `json:"last_event_at"`
HandlersStatus map[string]string `json:"handlers_status"`
}
EventMetrics provides metrics for event processing.
type EventProcessingResult ¶
type EventProcessingResult struct {
EventID string `json:"event_id"`
Success bool `json:"success"`
HandlerName string `json:"handler_name"`
Error string `json:"error,omitempty"`
ProcessedAt time.Time `json:"processed_at"`
Duration string `json:"duration"`
Actions []string `json:"actions,omitempty"`
}
EventProcessingResult represents the result of event processing.
type EventProcessor ¶
type EventProcessor interface {
ProcessEvent(ctx context.Context, event *GitHubEvent) error
ValidateSignature(payload []byte, signature, secret string) bool
ParseWebhookEvent(r *http.Request) (*GitHubEvent, error)
RegisterEventHandler(eventType EventType, handler EventHandler) error
UnregisterEventHandler(eventType EventType) error
GetMetrics() *EventMetrics
ValidateEvent(ctx context.Context, event *GitHubEvent) error
FilterEvent(ctx context.Context, event *GitHubEvent, filter *EventFilter) (bool, error)
}
EventProcessor defines the interface for processing GitHub events.
Example ¶
Example test showing how to use the event system.
// Create storage and logger (would be real implementations)
storage := &mockEventStorage{}
logger := &mockLogger{}
// Create event processor
processor := NewEventProcessor(storage, logger)
// Create a custom event handler
handler := &mockEventHandler{}
handler.On("GetSupportedActions").Return([]EventAction{ActionOpened})
handler.On("GetPriority").Return(100)
// Register the handler for push events
_ = processor.RegisterEventHandler(EventTypePush, handler) //nolint:errcheck // Test setup
// Create a webhook server
server := NewEventWebhookServer(processor, "webhook-secret", logger)
// Use the server to handle webhook requests
_ = server
Output: Example completed
func NewEventProcessor ¶
func NewEventProcessor(storage EventStorage, logger Logger) EventProcessor
NewEventProcessor creates a new event processor.
type EventStorage ¶
type EventStorage interface {
StoreEvent(ctx context.Context, event *GitHubEvent) error
GetEvent(ctx context.Context, eventID string) (*GitHubEvent, error)
ListEvents(ctx context.Context, filter *EventFilter, limit, offset int) ([]*GitHubEvent, error)
DeleteEvent(ctx context.Context, eventID string) error
CountEvents(ctx context.Context, filter *EventFilter) (int, error)
}
EventStorage defines the interface for storing events.
type EventType ¶
type EventType string
EventType defines the type of GitHub events.
const ( EventTypePush EventType = "push" EventTypePullRequest EventType = "pull_request" EventTypeIssues EventType = "issues" EventTypeRepository EventType = "repository" EventTypeRelease EventType = "release" EventTypeCreate EventType = "create" EventTypeDelete EventType = "delete" EventTypeWorkflowRun EventType = "workflow_run" EventTypeDeployment EventType = "deployment" EventTypeMember EventType = "member" EventTypeTeam EventType = "team" EventTypeOrganization EventType = "organization" EventTypeInstallation EventType = "installation" EventTypeInstallationRepos EventType = "installation_repositories" )
type EventWebhookServer ¶
type EventWebhookServer struct {
// contains filtered or unexported fields
}
EventWebhookServer provides HTTP server functionality for receiving GitHub webhooks.
func NewEventWebhookServer ¶
func NewEventWebhookServer(processor EventProcessor, secret string, logger Logger) *EventWebhookServer
NewEventWebhookServer creates a new webhook server.
func (*EventWebhookServer) GetHealthCheck ¶
func (s *EventWebhookServer) GetHealthCheck(w http.ResponseWriter, r *http.Request)
GetHealthCheck provides a health check endpoint.
func (*EventWebhookServer) HandleWebhook ¶
func (s *EventWebhookServer) HandleWebhook(w http.ResponseWriter, r *http.Request)
HandleWebhook handles incoming GitHub webhook requests.
type ExclusionType ¶
type ExclusionType string
const ( ExclusionTypeCVE ExclusionType = "cve" ExclusionTypePackage ExclusionType = "package" ExclusionTypeRepository ExclusionType = "repository" ExclusionTypePattern ExclusionType = "pattern" )
type ExecutionFilter ¶
type ExecutionFilter struct {
RuleID string `json:"ruleId,omitempty"`
Status ExecutionStatus `json:"status,omitempty"`
TriggerType ExecutionTriggerType `json:"triggerType,omitempty"`
StartedAfter *time.Time `json:"startedAfter,omitempty"`
StartedBefore *time.Time `json:"startedBefore,omitempty"`
}
ExecutionFilter defines criteria for filtering rule executions.
type ExecutionStatus ¶
type ExecutionStatus string
ExecutionStatus defines the status of a rule execution.
const ( ExecutionStatusPending ExecutionStatus = "pending" ExecutionStatusRunning ExecutionStatus = "running" ExecutionStatusCompleted ExecutionStatus = "completed" ExecutionStatusFailed ExecutionStatus = "failed" ExecutionStatusCancelled ExecutionStatus = "cancelled" ExecutionStatusTimeout ExecutionStatus = "timeout" )
type ExecutionTask ¶
type ExecutionTask struct {
ID string
Rule *AutomationRule
Event *GitHubEvent
Context *AutomationExecutionContext
RetryCount int
CreatedAt time.Time
}
ExecutionTask represents a task to execute a rule.
type ExecutionTriggerType ¶
type ExecutionTriggerType string
ExecutionTriggerType defines what triggered the rule execution.
const ( ExecutionTriggerTypeEvent ExecutionTriggerType = "event" ExecutionTriggerTypeSchedule ExecutionTriggerType = "schedule" ExecutionTriggerTypeManual ExecutionTriggerType = "manual" ExecutionTriggerTypeAPI ExecutionTriggerType = "api" )
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore implements ChangeStore using local file storage.
func NewFileStore ¶
NewFileStore creates a new file-based change store.
func (*FileStore) GetStorePath ¶
GetStorePath returns the base storage path.
func (*FileStore) List ¶
func (fs *FileStore) List(ctx context.Context, filter ChangeFilter) ([]*ChangeRecord, error)
List retrieves change records based on filter criteria.
type FileSystemInterface ¶
type FileSystemInterface interface {
WriteFile(filename string, data []byte, perm int) error
ReadFile(filename string) ([]byte, error)
MkdirAll(path string, perm int) error
Exists(path string) bool
}
FileSystem interface for dependency injection.
type GitCommandInterface ¶
type GitCommandInterface interface {
Clone(ctx context.Context, url, path string) error
Pull(ctx context.Context, path string) error
Fetch(ctx context.Context, path string) error
Reset(ctx context.Context, path string, hard bool) error
}
GitCommand interface for dependency injection.
type GitHubAPIClient ¶
type GitHubAPIClient struct {
// contains filtered or unexported fields
}
GitHubAPIClient implements the APIClient interface.
func (*GitHubAPIClient) GetDefaultBranch ¶
GetDefaultBranch implements APIClient interface.
func (*GitHubAPIClient) GetRateLimit ¶
func (c *GitHubAPIClient) GetRateLimit(ctx context.Context) (*RateLimit, error)
GetRateLimit implements APIClient interface.
func (*GitHubAPIClient) GetRepository ¶
func (c *GitHubAPIClient) GetRepository(ctx context.Context, owner, repo string) (*RepositoryInfo, error)
GetRepository implements APIClient interface.
func (*GitHubAPIClient) GetRepositoryConfiguration ¶
func (c *GitHubAPIClient) GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
GetRepositoryConfiguration implements APIClient interface.
func (*GitHubAPIClient) ListOrganizationRepositories ¶
func (c *GitHubAPIClient) ListOrganizationRepositories(ctx context.Context, org string) ([]RepositoryInfo, error)
ListOrganizationRepositories implements APIClient interface.
func (*GitHubAPIClient) SetToken ¶
func (c *GitHubAPIClient) SetToken(ctx context.Context, token string) error
SetToken implements APIClient interface.
func (*GitHubAPIClient) UpdateRepositoryConfiguration ¶
func (c *GitHubAPIClient) UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
UpdateRepositoryConfiguration implements APIClient interface.
type GitHubAPIClientAdapter ¶
type GitHubAPIClientAdapter struct {
// contains filtered or unexported fields
}
GitHubAPIClientAdapter adapts ResilientGitHubClient to APIClient interface
func (*GitHubAPIClientAdapter) GetDefaultBranch ¶
func (*GitHubAPIClientAdapter) GetRateLimit ¶
func (a *GitHubAPIClientAdapter) GetRateLimit(ctx context.Context) (*RateLimit, error)
func (*GitHubAPIClientAdapter) GetRepository ¶
func (a *GitHubAPIClientAdapter) GetRepository(ctx context.Context, owner, repo string) (*RepositoryInfo, error)
func (*GitHubAPIClientAdapter) GetRepositoryConfiguration ¶
func (a *GitHubAPIClientAdapter) GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
func (*GitHubAPIClientAdapter) ListOrganizationRepositories ¶
func (a *GitHubAPIClientAdapter) ListOrganizationRepositories(ctx context.Context, org string) ([]RepositoryInfo, error)
func (*GitHubAPIClientAdapter) SetToken ¶
func (a *GitHubAPIClientAdapter) SetToken(ctx context.Context, token string) error
func (*GitHubAPIClientAdapter) UpdateRepositoryConfiguration ¶
func (a *GitHubAPIClientAdapter) UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
type GitHubCloneService ¶
type GitHubCloneService struct {
// contains filtered or unexported fields
}
GitHubCloneService implements the CloneService interface.
func (*GitHubCloneService) CloneOrganization ¶
func (s *GitHubCloneService) CloneOrganization(ctx context.Context, orgName, targetPath, strategy string) error
CloneOrganization implements CloneService interface.
func (*GitHubCloneService) CloneRepository ¶
func (s *GitHubCloneService) CloneRepository(ctx context.Context, repo RepositoryInfo, targetPath, strategy string) error
CloneRepository implements CloneService interface.
func (*GitHubCloneService) GetSupportedStrategies ¶
func (s *GitHubCloneService) GetSupportedStrategies(ctx context.Context) ([]string, error)
GetSupportedStrategies implements CloneService interface.
func (*GitHubCloneService) RefreshAll ¶
func (s *GitHubCloneService) RefreshAll(ctx context.Context, targetPath, orgName, strategy string) error
RefreshAll implements CloneService interface.
func (*GitHubCloneService) SetStrategy ¶
func (s *GitHubCloneService) SetStrategy(ctx context.Context, strategy string) error
SetStrategy implements CloneService interface.
type GitHubCloner ¶
type GitHubCloner interface {
// CloneOrganization clones all repositories from a GitHub organization
CloneOrganization(ctx context.Context, orgName, targetPath, strategy string) error
// CloneRepository clones a specific repository
CloneRepository(ctx context.Context, owner, repo, targetPath, strategy string) error
// SetToken sets the GitHub token for authentication
SetToken(token string)
// GetToken returns the current GitHub token
GetToken() string
// GetProviderName returns the provider name
GetProviderName() string
}
GitHubCloner interface defines the contract for GitHub cloning operations.
type GitHubEvent ¶
type GitHubEvent struct {
ID string `json:"id"`
Type string `json:"type"`
Action string `json:"action,omitempty"`
Organization string `json:"organization"`
Repository string `json:"repository"`
Sender string `json:"sender"`
Timestamp time.Time `json:"timestamp"`
Payload map[string]interface{} `json:"payload"`
Headers map[string]string `json:"headers"`
Signature string `json:"signature"`
}
GitHubEvent represents a GitHub webhook event.
type GitHubFactoryConfig ¶
type GitHubFactoryConfig struct {
// DefaultToken is the default token to use when none is specified
DefaultToken string
// Environment is the environment to use for token resolution
Environment env.Environment
}
GitHubFactoryConfig holds configuration for the GitHub factory.
func DefaultGitHubFactoryConfig ¶
func DefaultGitHubFactoryConfig() *GitHubFactoryConfig
DefaultGitHubFactoryConfig returns default GitHub factory configuration.
type GitHubManager ¶
type GitHubManager interface {
// Repository Operations
ListOrganizationRepositories(ctx context.Context, organization string) ([]string, error)
CloneRepository(ctx context.Context, organization, repository, targetPath string) error
GetRepositoryDefaultBranch(ctx context.Context, organization, repository string) (string, error)
// Bulk Operations
RefreshAllRepositories(ctx context.Context, targetPath, organization, strategy string) error
BulkCloneRepositories(ctx context.Context, request *BulkCloneRequest) (*BulkCloneResult, error)
// Repository Management
GetRepositoryInfo(ctx context.Context, organization, repository string) (*RepositoryInfo, error)
ValidateRepositoryAccess(ctx context.Context, organization, repository string) error
// Webhook Operations
WebhookService() WebhookService
}
GitHubManager provides a high-level facade for GitHub operations.
func NewGitHubManager ¶
func NewGitHubManager(factory GitHubProviderFactory, logger Logger) GitHubManager
NewGitHubManager creates a new GitHub manager facade.
type GitHubOrganization ¶
type GitHubOrganization struct {
ID int `json:"id"`
Login string `json:"login"`
Name string `json:"name"`
Description string `json:"description"`
Company string `json:"company"`
Location string `json:"location"`
Email string `json:"email"`
PublicRepos int `json:"public_repos"`
Followers int `json:"followers"`
Following int `json:"following"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
GitHubOrganization represents a GitHub organization.
type GitHubProvider ¶
type GitHubProvider struct {
*provider.BaseProvider
// contains filtered or unexported fields
}
GitHubProvider implements the unified GitProvider interface for GitHub.
func NewGitHubProvider ¶
func NewGitHubProvider(client APIClient, cloner CloneService) *GitHubProvider
NewGitHubProvider creates a new GitHub provider instance.
func (*GitHubProvider) ArchiveRepository ¶
func (g *GitHubProvider) ArchiveRepository(ctx context.Context, id string) error
ArchiveRepository archives a repository.
func (*GitHubProvider) Authenticate ¶
func (g *GitHubProvider) Authenticate(ctx context.Context, creds provider.Credentials) error
Authenticate sets up authentication credentials.
func (*GitHubProvider) CloneRepository ¶
func (g *GitHubProvider) CloneRepository(ctx context.Context, repo provider.Repository, target string, opts provider.CloneOptions) error
CloneRepository clones a repository to the target path.
func (*GitHubProvider) CreateRelease ¶
func (g *GitHubProvider) CreateRelease(ctx context.Context, repoID string, req provider.CreateReleaseRequest) (*provider.Release, error)
CreateRelease creates a new release.
func (*GitHubProvider) CreateRepository ¶
func (g *GitHubProvider) CreateRepository(ctx context.Context, req provider.CreateRepoRequest) (*provider.Repository, error)
CreateRepository creates a new repository.
func (*GitHubProvider) CreateWebhook ¶
func (g *GitHubProvider) CreateWebhook(ctx context.Context, repoID string, webhook provider.CreateWebhookRequest) (*provider.Webhook, error)
func (*GitHubProvider) DeleteRelease ¶
func (g *GitHubProvider) DeleteRelease(ctx context.Context, repoID, releaseID string) error
DeleteRelease deletes a release.
func (*GitHubProvider) DeleteReleaseAsset ¶
func (g *GitHubProvider) DeleteReleaseAsset(ctx context.Context, repoID, assetID string) error
DeleteReleaseAsset deletes a release asset.
func (*GitHubProvider) DeleteRepository ¶
func (g *GitHubProvider) DeleteRepository(ctx context.Context, id string) error
DeleteRepository deletes a repository.
func (*GitHubProvider) DeleteWebhook ¶
func (g *GitHubProvider) DeleteWebhook(ctx context.Context, repoID, webhookID string) error
func (*GitHubProvider) DownloadReleaseAsset ¶
func (g *GitHubProvider) DownloadReleaseAsset(ctx context.Context, repoID, assetID string) ([]byte, error)
DownloadReleaseAsset downloads a release asset.
func (*GitHubProvider) ForkRepository ¶
func (g *GitHubProvider) ForkRepository(ctx context.Context, id string, opts provider.ForkOptions) (*provider.Repository, error)
ForkRepository creates a fork of a repository.
func (*GitHubProvider) GetCapabilities ¶
func (g *GitHubProvider) GetCapabilities() []provider.Capability
GetCapabilities returns the list of supported capabilities.
func (*GitHubProvider) GetMetrics ¶
func (g *GitHubProvider) GetMetrics(ctx context.Context) (*provider.ProviderMetrics, error)
func (*GitHubProvider) GetRateLimit ¶
func (*GitHubProvider) GetRelease ¶
func (g *GitHubProvider) GetRelease(ctx context.Context, repoID, releaseID string) (*provider.Release, error)
GetRelease gets a specific release by ID.
func (*GitHubProvider) GetReleaseByTag ¶
func (g *GitHubProvider) GetReleaseByTag(ctx context.Context, repoID, tagName string) (*provider.Release, error)
GetReleaseByTag gets a release by tag name.
func (*GitHubProvider) GetRepository ¶
func (g *GitHubProvider) GetRepository(ctx context.Context, id string) (*provider.Repository, error)
GetRepository retrieves information about a specific repository.
func (*GitHubProvider) GetWebhook ¶
func (*GitHubProvider) HealthCheck ¶
func (g *GitHubProvider) HealthCheck(ctx context.Context) (*provider.HealthStatus, error)
Health and monitoring methods
func (*GitHubProvider) ListEvents ¶
func (g *GitHubProvider) ListEvents(ctx context.Context, opts provider.EventListOptions) ([]provider.Event, error)
Event management methods (placeholder implementations)
func (*GitHubProvider) ListReleaseAssets ¶
func (g *GitHubProvider) ListReleaseAssets(ctx context.Context, repoID, releaseID string) ([]provider.Asset, error)
ListReleaseAssets lists assets for a release.
func (*GitHubProvider) ListReleases ¶
func (g *GitHubProvider) ListReleases(ctx context.Context, repoID string, opts provider.ListReleasesOptions) (*provider.ReleaseList, error)
ListReleases lists releases for a repository.
func (*GitHubProvider) ListRepositories ¶
func (g *GitHubProvider) ListRepositories(ctx context.Context, opts provider.ListOptions) (*provider.RepositoryList, error)
ListRepositories lists repositories for an organization.
func (*GitHubProvider) ListWebhooks ¶
func (g *GitHubProvider) ListWebhooks(ctx context.Context, repoID string) ([]provider.Webhook, error)
Webhook management methods (placeholder implementations)
func (*GitHubProvider) ProcessEvent ¶
func (*GitHubProvider) RegisterEventHandler ¶
func (g *GitHubProvider) RegisterEventHandler(eventType string, handler provider.EventHandler) error
func (*GitHubProvider) SearchRepositories ¶
func (g *GitHubProvider) SearchRepositories(ctx context.Context, query provider.SearchQuery) (*provider.SearchResult, error)
SearchRepositories searches for repositories.
func (*GitHubProvider) StreamEvents ¶
func (g *GitHubProvider) StreamEvents(ctx context.Context, opts provider.StreamOptions) (<-chan provider.Event, error)
func (*GitHubProvider) TestWebhook ¶
func (g *GitHubProvider) TestWebhook(ctx context.Context, repoID, webhookID string) (*provider.WebhookTestResult, error)
func (*GitHubProvider) UnarchiveRepository ¶
func (g *GitHubProvider) UnarchiveRepository(ctx context.Context, id string) error
UnarchiveRepository unarchives a repository.
func (*GitHubProvider) UpdateRelease ¶
func (g *GitHubProvider) UpdateRelease(ctx context.Context, repoID, releaseID string, updates provider.UpdateReleaseRequest) (*provider.Release, error)
UpdateRelease updates an existing release.
func (*GitHubProvider) UpdateRepository ¶
func (g *GitHubProvider) UpdateRepository(ctx context.Context, id string, updates provider.UpdateRepoRequest) (*provider.Repository, error)
UpdateRepository updates repository settings.
func (*GitHubProvider) UpdateWebhook ¶
func (g *GitHubProvider) UpdateWebhook(ctx context.Context, repoID, webhookID string, updates provider.UpdateWebhookRequest) (*provider.Webhook, error)
func (*GitHubProvider) UploadReleaseAsset ¶
func (g *GitHubProvider) UploadReleaseAsset(ctx context.Context, repoID string, req provider.UploadAssetRequest) (*provider.Asset, error)
UploadReleaseAsset uploads an asset to a release.
func (*GitHubProvider) ValidateToken ¶
ValidateToken validates the authentication token.
func (*GitHubProvider) ValidateWebhookURL ¶
func (g *GitHubProvider) ValidateWebhookURL(ctx context.Context, url string) error
type GitHubProviderFactory ¶
type GitHubProviderFactory interface {
// CreateCloner creates a GitHub cloner with the specified token
CreateCloner(ctx context.Context, token string) (GitHubCloner, error)
// CreateClonerWithEnv creates a GitHub cloner with a specific environment
CreateClonerWithEnv(ctx context.Context, token string, environment env.Environment) (GitHubCloner, error)
// CreateChangeLogger creates a GitHub change logger
CreateChangeLogger(ctx context.Context, changelog *ChangeLog, options *LoggerOptions) (*ChangeLogger, error)
// GetProviderName returns the provider name
GetProviderName() string
}
GitHubProviderFactory defines the interface for creating GitHub-specific instances.
func NewGitHubProviderFactory ¶
func NewGitHubProviderFactory(environment env.Environment) GitHubProviderFactory
NewGitHubProviderFactory creates a new GitHub provider factory.
func NewGitHubProviderFactoryWithConfig ¶
func NewGitHubProviderFactoryWithConfig(config *GitHubFactoryConfig) GitHubProviderFactory
NewGitHubProviderFactoryWithConfig creates a new GitHub provider factory with configuration.
type GitHubRepository ¶
type GitHubRepository struct {
ID int `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
Description string `json:"description"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Archived bool `json:"archived"`
Disabled bool `json:"disabled"`
DefaultBranch string `json:"default_branch"`
Language string `json:"language"`
Size int `json:"size"`
StargazersCount int `json:"stargazers_count"`
WatchersCount int `json:"watchers_count"`
ForksCount int `json:"forks_count"`
OpenIssuesCount int `json:"open_issues_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PushedAt time.Time `json:"pushed_at"`
CloneURL string `json:"clone_url"`
SSHURL string `json:"ssh_url"`
HTMLURL string `json:"html_url"`
GitURL string `json:"git_url"`
}
GitHubRepository represents a GitHub repository.
type GitHubService ¶
type GitHubService interface {
APIClient
CloneService
TokenValidatorInterface
ChangeLoggerInterface
ConfirmationServiceInterface
}
GitHubService provides a unified interface for all GitHub operations.
type GitHubServiceConfig ¶
type GitHubServiceConfig struct {
API *APIClientConfig
Clone *CloneServiceConfig
}
GitHubServiceConfig holds configuration for the GitHub service.
type GitHubServiceContainer ¶
type GitHubServiceContainer struct {
APIClient APIClient
CloneService CloneService
TokenValidator TokenValidatorInterface
}
GitHubServiceContainer holds all GitHub service implementations.
func NewGitHubServiceContainer ¶
func NewGitHubServiceContainer( config *GitHubServiceConfig, httpClient HTTPClientInterface, gitClient GitCommandInterface, fileSystem FileSystemInterface, logger Logger, ) *GitHubServiceContainer
NewGitHubServiceContainer creates a new GitHub service container with all dependencies.
type GitHubTokenValidator ¶
type GitHubTokenValidator struct {
// contains filtered or unexported fields
}
GitHubTokenValidator implements the TokenValidator interface.
func (*GitHubTokenValidator) GetRequiredScopes ¶
func (v *GitHubTokenValidator) GetRequiredScopes(ctx context.Context, operation string) ([]string, error)
GetRequiredScopes implements TokenValidator interface.
func (*GitHubTokenValidator) ValidateForOperation ¶
func (v *GitHubTokenValidator) ValidateForOperation(ctx context.Context, token, operation string) error
ValidateForOperation implements TokenValidator interface.
func (*GitHubTokenValidator) ValidateForRepository ¶
func (v *GitHubTokenValidator) ValidateForRepository(ctx context.Context, token, owner, repo string) error
ValidateForRepository implements TokenValidator interface.
func (*GitHubTokenValidator) ValidateToken ¶
func (v *GitHubTokenValidator) ValidateToken(ctx context.Context, token string) (*TokenInfoRecord, error)
ValidateToken implements TokenValidator interface.
type GitHubUser ¶
type GitHubUser struct {
ID int `json:"id"`
Login string `json:"login"`
Name string `json:"name"`
Email string `json:"email"`
Company string `json:"company"`
Location string `json:"location"`
Bio string `json:"bio"`
PublicRepos int `json:"public_repos"`
Followers int `json:"followers"`
Following int `json:"following"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
GitHubUser represents a GitHub user.
type HTTPClient ¶
type HTTPClient interface {
// Do performs an HTTP request with context
Do(ctx context.Context, req *http.Request) (*http.Response, error)
// Get performs a GET request
Get(ctx context.Context, url string) (*http.Response, error)
// Post performs a POST request
Post(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
// Put performs a PUT request
Put(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
// Patch performs a PATCH request
Patch(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
// Delete performs a DELETE request
Delete(ctx context.Context, url string) (*http.Response, error)
}
HTTPClient defines the interface for HTTP operations.
func NewHTTPClientAdapter ¶
func NewHTTPClientAdapter() HTTPClient
NewHTTPClientAdapter creates a new HTTP client adapter.
func NewHTTPClientAdapterWithClient ¶
func NewHTTPClientAdapterWithClient(client *http.Client) HTTPClient
NewHTTPClientAdapterWithClient creates a new HTTP client adapter with a custom client.
type HTTPClientAdapter ¶
type HTTPClientAdapter struct {
// contains filtered or unexported fields
}
HTTPClientAdapter adapts the standard http.Client to the HTTPClient interface.
func (*HTTPClientAdapter) Patch ¶
func (a *HTTPClientAdapter) Patch(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
Patch performs a PATCH request.
type HTTPClientInterface ¶
type HTTPClientInterface interface {
Do(req *http.Request) (*http.Response, error)
Get(url string) (*http.Response, error)
Post(url, contentType string, body interface{}) (*http.Response, error)
}
HTTPClient interface for dependency injection.
type HealthCheck ¶
type ImpactLevel ¶
type ImpactLevel string
const ( ImpactLevelCritical ImpactLevel = "critical" ImpactLevelHigh ImpactLevel = "high" ImpactLevelMedium ImpactLevel = "medium" ImpactLevelLow ImpactLevel = "low" ImpactLevelMinimal ImpactLevel = "minimal" )
type IntegrationTestingConfig ¶
type IntegrationTestingConfig struct {
Enabled bool `json:"enabled"`
TestSuites []string `json:"test_suites"`
RequiredCoverage float64 `json:"required_coverage"`
Timeout time.Duration `json:"timeout"`
Environment string `json:"environment"`
PreTestSetup []string `json:"pre_test_setup"`
PostTestCleanup []string `json:"post_test_cleanup"`
TestData map[string]string `json:"test_data,omitempty"`
}
type JSONPathValidationResult ¶
type JSONPathValidationResult struct {
Path string `json:"path"`
Valid bool `json:"valid"`
Error string `json:"error,omitempty"`
}
JSONPathValidationResult represents JSONPath validation result.
type JobAuditInfo ¶
type JobAuditInfo struct {
JobID string `json:"job_id"`
RunsOn string `json:"runs_on"`
Permissions map[string]string `json:"permissions,omitempty"`
Steps []StepAuditInfo `json:"steps"`
Environment string `json:"environment,omitempty"`
SecurityScore int `json:"security_score"`
UsesSecrets []string `json:"uses_secrets,omitempty"`
UsesVariables []string `json:"uses_variables,omitempty"`
}
JobAuditInfo represents audit information for a job within a workflow.
type LicenseRestriction ¶
type ListOptions ¶
type ListOptions struct {
PerPage int // Number of items per page (default: 30, max: 100)
Type string // Repository type: all, owner, member
Sort string // Sort by: created, updated, pushed, full_name
Direction string // Sort direction: asc, desc
}
ListOptions represents options for listing operations.
type LogFilters ¶
type LogFilters struct {
Repository string `json:"repository,omitempty"`
Operation string `json:"operation,omitempty"`
User string `json:"user,omitempty"`
StartTime time.Time `json:"start_time,omitempty"`
EndTime time.Time `json:"end_time,omitempty"`
Success *bool `json:"success,omitempty"`
}
LogFilters defines filters for operation history queries.
type LogLevelType ¶
type LogLevelType int
LogLevelType represents the logging level.
const ( LogLevelTypeDebug LogLevelType = iota LogLevelTypeInfo LogLevelTypeWarn LogLevelTypeError )
type LogOperationRecord ¶
type LogOperationRecord struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Operation string `json:"operation"`
Repository string `json:"repository"`
User string `json:"user"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Metadata map[string]interface{} `json:"metadata"`
}
LogOperationRecord represents a logged operation.
type LogSummary ¶
type LogSummary struct {
Period string `json:"period"`
TotalChanges int `json:"totalChanges"`
ByCategory map[string]int `json:"byCategory"`
ByOperation map[string]int `json:"byOperation"`
ByUser map[string]int `json:"byUser"`
Errors []string `json:"errors"`
}
LogSummary provides a summary of logging activity.
type Logger ¶
type Logger interface {
Debug(msg string, args ...interface{})
Info(msg string, args ...interface{})
Warn(msg string, args ...interface{})
Error(msg string, args ...interface{})
}
Logger interface for dependency injection.
type LoggerOptions ¶
type LoggerOptions struct {
// LogDirectory specifies where log files are stored
LogDirectory string
// LogFormat specifies the log output format (json, text, csv)
LogFormat LogFormat
// LogLevel controls which events are logged
LogLevel LogLevel
// MaxLogFileSize specifies maximum size before rotation (in bytes)
MaxLogFileSize int64
// MaxLogFiles specifies how many rotated files to keep
MaxLogFiles int
// EnableConsoleOutput enables logging to stdout/stderr
EnableConsoleOutput bool
// EnableStructuredOutput enables structured JSON output
EnableStructuredOutput bool
}
LoggerOptions configures the change logger behavior.
func DefaultLoggerOptions ¶
func DefaultLoggerOptions() *LoggerOptions
DefaultLoggerOptions returns default logger configuration.
type ManualRollbackProcedure ¶
type ManualTestingItem ¶
type MatchOperator ¶
type MatchOperator string
MatchOperator defines how payload matching is performed.
const ( MatchOperatorEquals MatchOperator = "equals" MatchOperatorNotEquals MatchOperator = "not_equals" MatchOperatorContains MatchOperator = "contains" MatchOperatorNotContains MatchOperator = "not_contains" MatchOperatorStartsWith MatchOperator = "starts_with" MatchOperatorEndsWith MatchOperator = "ends_with" MatchOperatorRegex MatchOperator = "regex" MatchOperatorGreaterThan MatchOperator = "greater_than" MatchOperatorLessThan MatchOperator = "less_than" MatchOperatorExists MatchOperator = "exists" MatchOperatorNotExists MatchOperator = "not_exists" MatchOperatorEmpty MatchOperator = "empty" MatchOperatorNotEmpty MatchOperator = "not_empty" )
type MatrixTestingConfig ¶
type MatrixTestingConfig struct {
Enabled bool `json:"enabled"`
OperatingSystems []string `json:"operating_systems"`
RuntimeVersions []string `json:"runtime_versions"`
DatabaseVersions []string `json:"database_versions,omitempty"`
BrowserVersions []string `json:"browser_versions,omitempty"`
CustomDimensions map[string][]string `json:"custom_dimensions,omitempty"`
}
type MemoryMonitor ¶
type MemoryMonitor struct {
// contains filtered or unexported fields
}
MemoryMonitor tracks and manages memory usage.
type MemoryPool ¶
type MemoryPool struct {
// contains filtered or unexported fields
}
MemoryPool manages reusable memory allocations.
type MemoryPressureLevel ¶
type MemoryPressureLevel int
MemoryPressureLevel represents the current memory pressure.
const ( MemoryPressureLow MemoryPressureLevel = iota MemoryPressureMedium MemoryPressureHigh MemoryPressureCritical )
func GetMemoryPressure ¶
func GetMemoryPressure(maxMemory int64) MemoryPressureLevel
GetMemoryPressure assesses current memory pressure level.
func (MemoryPressureLevel) String ¶
func (mpl MemoryPressureLevel) String() string
String returns string representation of memory pressure level.
type MemoryStats ¶
type MemoryStats struct {
Alloc uint64 // Currently allocated bytes
TotalAlloc uint64 // Total allocated bytes (cumulative)
Sys uint64 // System bytes obtained from OS
Lookups uint64 // Number of pointer lookups
Mallocs uint64 // Number of allocations
Frees uint64 // Number of frees
HeapAlloc uint64 // Heap allocated bytes
HeapSys uint64 // Heap system bytes
HeapIdle uint64 // Heap idle bytes
HeapInuse uint64 // Heap in-use bytes
HeapReleased uint64 // Heap released bytes
HeapObjects uint64 // Number of heap objects
StackInuse uint64 // Stack in-use bytes
StackSys uint64 // Stack system bytes
MSpanInuse uint64 // MSpan in-use bytes
MSpanSys uint64 // MSpan system bytes
MCacheInuse uint64 // MCache in-use bytes
MCacheSys uint64 // MCache system bytes
BuckHashSys uint64 // Bucket hash system bytes
GCSys uint64 // GC system bytes
OtherSys uint64 // Other system bytes
NextGC uint64 // Next GC threshold
LastGC uint64 // Last GC time (nanoseconds since epoch)
PauseTotalNs uint64 // Total pause time in nanoseconds
PauseNs [256]uint64 // Last 256 GC pause times
PauseEnd [256]uint64 // Last 256 GC pause end times
NumGC uint32 // Number of GC cycles
NumForcedGC uint32 // Number of forced GC cycles
GCCPUFraction float64 // Fraction of CPU time used by GC
EnableGC bool // GC enabled flag
DebugGC bool // Debug GC flag
Timestamp time.Time // When stats were collected
}
MemoryStats represents memory usage statistics.
func GetMemoryStats ¶
func GetMemoryStats() *MemoryStats
GetMemoryStats returns current memory statistics.
func OptimizeMemoryUsage ¶
func OptimizeMemoryUsage() *MemoryStats
OptimizeMemoryUsage performs aggressive memory optimization.
func (*MemoryStats) MemoryEfficiency ¶
func (ms *MemoryStats) MemoryEfficiency() map[string]float64
MemoryEfficiency calculates memory usage efficiency metrics.
func (*MemoryStats) String ¶
func (ms *MemoryStats) String() string
String returns a human-readable string representation of memory stats.
type MemoryWatcher ¶
type MemoryWatcher struct {
// contains filtered or unexported fields
}
MemoryWatcher monitors memory usage and triggers cleanup when needed.
func NewMemoryWatcher ¶
func NewMemoryWatcher(maxMemory int64, threshold float64, checkInterval time.Duration) *MemoryWatcher
NewMemoryWatcher creates a new memory watcher.
func (*MemoryWatcher) SetPressureHandler ¶
func (mw *MemoryWatcher) SetPressureHandler(handler func(MemoryPressureLevel))
SetPressureHandler sets the callback function for memory pressure events.
type MetricsTrackingConfig ¶
type MetricsTrackingConfig struct {
Enabled bool `json:"enabled"`
MetricsCollectors []string `json:"metrics_collectors"`
TrackingFrequency time.Duration `json:"tracking_frequency"`
RetentionPeriod time.Duration `json:"retention_period"`
AlertingEnabled bool `json:"alerting_enabled"`
DashboardEnabled bool `json:"dashboard_enabled"`
CustomMetrics []CustomMetric `json:"custom_metrics"`
}
type MigrationRequest ¶
type MigrationRequest struct {
Organization string `json:"organization"`
SourceConfig string `json:"source_config,omitempty"` // Path to source configuration
TargetPolicyID string `json:"target_policy_id"`
DryRun bool `json:"dry_run"`
BackupExisting bool `json:"backup_existing"`
Mapping map[string]string `json:"mapping,omitempty"` // URL mappings for migration
}
MigrationRequest represents a request to migrate existing webhooks.
type MigrationResult ¶
type MigrationResult struct {
Organization string `json:"organization"`
TotalWebhooks int `json:"total_webhooks"`
MigratedWebhooks int `json:"migrated_webhooks"`
SkippedWebhooks int `json:"skipped_webhooks"`
FailedWebhooks int `json:"failed_webhooks"`
BackupPath string `json:"backup_path,omitempty"`
Results []WebhookMigrationResult `json:"results"`
ExecutionTime string `json:"execution_time"`
}
MigrationResult represents the result of a migration operation.
type MitigationStrategy ¶
type MitigationStrategy struct {
Type string `json:"type"`
Description string `json:"description"`
Effort string `json:"effort"`
Effectiveness string `json:"effectiveness"`
}
MitigationStrategy represents a strategy to mitigate risk.
type NotificationChannel ¶
type NotificationChannel struct {
Type ChannelType `json:"type"`
Target string `json:"target"`
Enabled bool `json:"enabled"`
Severities []VulnerabilitySeverity `json:"severities"`
Format string `json:"format,omitempty"`
RateLimit *RateLimitConfig `json:"rate_limit,omitempty"`
}
NotificationChannel defines a notification delivery channel.
type NotificationConfig ¶
type NotificationConfig struct {
Enabled bool `json:"enabled"`
Channels []NotificationChannel `json:"channels"`
Templates map[string]string `json:"templates,omitempty"`
EscalationTargets []EscalationTarget `json:"escalation_targets"`
SummaryFrequency string `json:"summary_frequency"`
}
NotificationConfig defines how notifications should be sent.
type NotificationRecipient ¶
type NotificationSettings ¶
type NotificationSettings struct {
OnSuccess bool `json:"on_success" yaml:"on_success"`
OnFailure bool `json:"on_failure" yaml:"on_failure"`
OnConflict bool `json:"on_conflict" yaml:"on_conflict"`
Recipients []string `json:"recipients" yaml:"recipients"`
SlackChannel string `json:"slack_channel,omitempty" yaml:"slack_channel,omitempty"`
}
NotificationSettings defines notification preferences.
type OperationRecord ¶
type OperationRecord struct {
ID string `json:"id"`
Type string `json:"type"`
Repository string `json:"repository"`
Description string `json:"description"`
Risk RiskLevelType `json:"risk"`
Metadata map[string]interface{} `json:"metadata"`
}
OperationRecord represents an operation that requires confirmation.
type OperationResultStatus ¶
type OperationResultStatus string
const ( OperationResultStatusSuccess OperationResultStatus = "success" OperationResultStatusFailed OperationResultStatus = "failed" OperationResultStatusSkipped OperationResultStatus = "skipped" OperationResultStatusError OperationResultStatus = "error" )
type OptimizedCloneConfig ¶
type OptimizedCloneConfig struct {
// Memory management
MaxMemoryUsage int64 // Maximum memory usage in bytes
MemoryThreshold float64 // Trigger cleanup at this % of max memory
GCInterval time.Duration // How often to check memory usage
// Streaming configuration
StreamingConfig StreamingConfig
// Worker pool configuration
WorkerPoolConfig workerpool.RepositoryPoolConfig
// Progress and monitoring
ShowProgress bool
VerboseLogging bool
MetricsEnabled bool
// Performance tuning
BatchSize int // Number of repositories to process in a batch
PrefetchSize int // Number of repositories to prefetch
}
OptimizedCloneConfig represents configuration for optimized bulk cloning.
func DefaultOptimizedCloneConfig ¶
func DefaultOptimizedCloneConfig() OptimizedCloneConfig
DefaultOptimizedCloneConfig returns optimized defaults for large-scale operations.
type OptimizedSyncCloneManager ¶
type OptimizedSyncCloneManager struct {
// contains filtered or unexported fields
}
OptimizedSyncCloneManager handles large-scale repository operations with memory optimization.
func NewOptimizedSyncCloneManager ¶
func NewOptimizedSyncCloneManager(token string, config OptimizedCloneConfig) (*OptimizedSyncCloneManager, error)
NewOptimizedSyncCloneManager creates a new optimized bulk clone manager.
func (*OptimizedSyncCloneManager) Close ¶
func (m *OptimizedSyncCloneManager) Close() error
Close cleans up resources.
func (*OptimizedSyncCloneManager) RefreshAllOptimized ¶
func (m *OptimizedSyncCloneManager) RefreshAllOptimized(ctx context.Context, targetPath, org, strategy string) (*CloneStats, error)
RefreshAllOptimized performs optimized bulk repository refresh with streaming and memory management.
type OrganizationInfo ¶
type OrganizationInfo struct {
Login string `json:"login"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Plan string `json:"plan"`
TwoFactorRequired bool `json:"twoFactorRequired"`
MemberCount int `json:"memberCount"`
RepoCount int `json:"repoCount"`
Settings map[string]string `json:"settings,omitempty"`
}
OrganizationInfo contains information about a GitHub organization.
type OrganizationMetrics ¶
type OrganizationMetrics struct {
TotalWebhooks int64 `json:"total_webhooks"`
HealthyWebhooks int64 `json:"healthy_webhooks"`
UnhealthyWebhooks int64 `json:"unhealthy_webhooks"`
AverageResponseTime time.Duration `json:"average_response_time"`
ErrorRate float64 `json:"error_rate"`
ActiveAlerts int64 `json:"active_alerts"`
}
OrganizationMetrics holds metrics for a specific organization.
type OrganizationPolicyReport ¶
type OrganizationPolicyReport struct {
Organization string `json:"organization"`
PolicyID string `json:"policy_id"`
GeneratedAt time.Time `json:"generated_at"`
Summary OrganizationPolicySummary `json:"summary"`
RepositoryResults []PolicyEvaluationResult `json:"repository_results"`
TopViolations []DependabotViolationStatistics `json:"top_violations"`
Recommendations []PolicyRecommendation `json:"recommendations"`
TrendAnalysis PolicyTrendAnalysis `json:"trend_analysis"`
ExportFormats []string `json:"available_exports"`
}
OrganizationPolicyReport provides comprehensive reporting for organization policies.
type OrganizationPolicySummary ¶
type OrganizationPolicySummary struct {
TotalRepositories int `json:"total_repositories"`
CompliantRepositories int `json:"compliant_repositories"`
ViolatingRepositories int `json:"violating_repositories"`
ComplianceRate float64 `json:"compliance_rate"`
AverageComplianceScore float64 `json:"average_compliance_score"`
TotalViolations int `json:"total_violations"`
CriticalViolations int `json:"critical_violations"`
EcosystemBreakdown map[string]EcosystemStats `json:"ecosystem_breakdown"`
ViolationBreakdown map[DependabotPolicyViolationType]int `json:"violation_breakdown"`
}
OrganizationPolicySummary provides high-level statistics.
type OrganizationWebhookConfig ¶
type OrganizationWebhookConfig struct {
Organization string `json:"organization" yaml:"organization"`
Version string `json:"version" yaml:"version"`
Metadata ConfigMetadata `json:"metadata" yaml:"metadata"`
Defaults WebhookDefaults `json:"defaults" yaml:"defaults"`
Policies []WebhookPolicy `json:"policies" yaml:"policies"`
Settings OrganizationWebhookSettings `json:"settings" yaml:"settings"`
Validation ValidationConfig `json:"validation" yaml:"validation"`
}
OrganizationWebhookConfig represents the overall webhook configuration for an organization.
type OrganizationWebhookSettings ¶
type OrganizationWebhookSettings struct {
AllowRepositoryOverride bool `json:"allow_repository_override" yaml:"allow_repository_override"`
RequireApproval bool `json:"require_approval" yaml:"require_approval"`
MaxWebhooksPerRepo int `json:"max_webhooks_per_repo" yaml:"max_webhooks_per_repo"`
RetryOnFailure bool `json:"retry_on_failure" yaml:"retry_on_failure"`
NotificationSettings NotificationSettings `json:"notification_settings" yaml:"notification_settings"`
}
OrganizationWebhookSettings contains organization-specific settings.
type PackageInfo ¶
type PackageInfo struct {
Name string `json:"name"`
Ecosystem string `json:"ecosystem"`
Type string `json:"type,omitempty"`
Namespace string `json:"namespace,omitempty"`
}
PackageInfo represents information about a vulnerable package.
type PayloadMatchExplanation ¶
type PayloadMatchExplanation struct {
Path string `json:"path"`
Operator string `json:"operator"`
Expected interface{} `json:"expected"`
Actual interface{} `json:"actual"`
Result bool `json:"result"`
Explanation string `json:"explanation"`
}
PayloadMatchExplanation explains payload matching results.
type PayloadMatchResult ¶
type PayloadMatchResult struct {
Path string `json:"path"`
Operator MatchOperator `json:"operator"`
ExpectedValue interface{} `json:"expectedValue"`
ActualValue interface{} `json:"actualValue"`
Matched bool `json:"matched"`
Error string `json:"error,omitempty"`
}
PayloadMatchResult represents the result of a single payload matcher.
type PayloadMatcher ¶
type PayloadMatcher struct {
Path string `json:"path" yaml:"path"` // JSONPath expression (e.g., "$.pull_request.title")
Operator MatchOperator `json:"operator" yaml:"operator"` // equals, contains, regex, etc.
Value interface{} `json:"value" yaml:"value"` // Value to match against
CaseSensitive bool `json:"caseSensitive,omitempty" yaml:"caseSensitive,omitempty"`
}
PayloadMatcher defines conditions for matching against event payload.
type PerformanceImpactAnalysis ¶
type PerformanceImpactAnalysis struct {
ExpectedImpact string `json:"expected_impact"`
BenchmarkResults []BenchmarkResult `json:"benchmark_results"`
PerformanceRegression float64 `json:"performance_regression"`
RecommendedActions []string `json:"recommended_actions"`
}
Additional complex supporting types.
type PerformanceRequirements ¶
type PermissionLevel ¶
type PermissionLevel string
PermissionLevel represents the level of access for a permission.
const ( PermissionNone PermissionLevel = "none" PermissionRead PermissionLevel = "read" PermissionWrite PermissionLevel = "write" PermissionAdmin PermissionLevel = "admin" )
type PermissionLevelValidationRule ¶
type PermissionLevelValidationRule struct{}
PermissionLevelValidationRule validates Actions permission level compliance.
func (*PermissionLevelValidationRule) GetDescription ¶
func (r *PermissionLevelValidationRule) GetDescription() string
func (*PermissionLevelValidationRule) GetRuleID ¶
func (r *PermissionLevelValidationRule) GetRuleID() string
func (*PermissionLevelValidationRule) Validate ¶
func (r *PermissionLevelValidationRule) Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
type PermissionsConfig ¶
type PermissionsConfig struct {
Teams map[string]string `json:"teams,omitempty"`
Users map[string]string `json:"users,omitempty"`
}
PermissionsConfig represents repository permissions configuration.
type PlannedAction ¶
type PlannedAction struct {
Repository string `json:"repository"`
PolicyID string `json:"policy_id"`
RuleID string `json:"rule_id"`
Action WebhookAction `json:"action"`
WebhookName string `json:"webhook_name"`
Changes []string `json:"changes"`
Conflicts []string `json:"conflicts,omitempty"`
}
PlannedAction represents an action that would be taken.
type PolicyApplicationPreview ¶
type PolicyApplicationPreview struct {
Organization string `json:"organization"`
TotalRepositories int `json:"total_repositories"`
PlannedActions []PlannedAction `json:"planned_actions"`
Conflicts []PolicyConflict `json:"conflicts"`
Warnings []string `json:"warnings"`
Summary PolicyApplicationSummary `json:"summary"`
}
PolicyApplicationPreview shows what would happen without making changes.
type PolicyApplicationResult ¶
type PolicyApplicationResult struct {
Repository string `json:"repository"`
PolicyID string `json:"policy_id"`
RuleID string `json:"rule_id"`
Action WebhookAction `json:"action"`
Success bool `json:"success"`
WebhookID *int64 `json:"webhook_id,omitempty"`
Error string `json:"error,omitempty"`
Skipped bool `json:"skipped"`
SkipReason string `json:"skip_reason,omitempty"`
Changes []string `json:"changes,omitempty"`
Duration string `json:"duration"`
}
PolicyApplicationResult represents the result for a single repository.
type PolicyApplicationSummary ¶
type PolicyApplicationSummary struct {
WebhooksCreated int `json:"webhooks_created"`
WebhooksUpdated int `json:"webhooks_updated"`
WebhooksDeleted int `json:"webhooks_deleted"`
ConflictsFound int `json:"conflicts_found"`
ErrorsByType map[string]int `json:"errors_by_type"`
}
PolicyApplicationSummary provides a summary of policy application.
type PolicyCache ¶
type PolicyCache struct {
// contains filtered or unexported fields
}
PolicyCache provides caching for policy evaluations and repository states.
type PolicyChange ¶
type PolicyChange struct {
Type string `json:"type"`
Target string `json:"target"`
Action string `json:"action"`
OldValue interface{} `json:"oldValue,omitempty"`
NewValue interface{} `json:"newValue"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
PolicyChange represents a change made during policy enforcement.
type PolicyConflict ¶
type PolicyConflict struct {
Repository string `json:"repository"`
ConflictType string `json:"conflict_type"`
Description string `json:"description"`
PolicyID1 string `json:"policy_id_1"`
PolicyID2 string `json:"policy_id_2,omitempty"`
ExistingWebhook *WebhookInfo `json:"existing_webhook,omitempty"`
Resolution string `json:"resolution"`
}
PolicyConflict represents a conflict between policies or existing webhooks.
type PolicyEnforcementResult ¶
type PolicyEnforcementResult struct {
PolicyID string `json:"policyId"`
Organization string `json:"organization"`
Repository string `json:"repository"`
Success bool `json:"success"`
AppliedChanges []PolicyChange `json:"appliedChanges"`
FailedChanges []PolicyChange `json:"failedChanges"`
ValidationResult []PolicyValidationResult `json:"validationResult"`
Violations []ActionsPolicyViolation `json:"violations,omitempty"`
ExecutionTime time.Duration `json:"executionTime"`
Timestamp time.Time `json:"timestamp"`
}
PolicyEnforcementResult represents the result of applying a policy.
type PolicyEvaluationResult ¶
type PolicyEvaluationResult struct {
PolicyID string `json:"policy_id"`
Repository string `json:"repository"`
Organization string `json:"organization"`
Compliant bool `json:"compliant"`
Violations []DependabotPolicyViolation `json:"violations"`
Recommendations []PolicyRecommendation `json:"recommendations"`
EvaluatedAt time.Time `json:"evaluated_at"`
NextEvaluation time.Time `json:"next_evaluation"`
ComplianceScore float64 `json:"compliance_score"`
}
PolicyEvaluationResult represents the result of policy evaluation for a repository.
type PolicyRecommendation ¶
type PolicyRecommendation struct {
ID string `json:"id"`
Type PolicyRecommendationType `json:"type"`
Priority RecommendationPriority `json:"priority"`
Title string `json:"title"`
Description string `json:"description"`
Ecosystem string `json:"ecosystem,omitempty"`
Action string `json:"action"`
Benefits []string `json:"benefits"`
}
PolicyRecommendation represents a recommendation to improve Dependabot configuration.
type PolicyRecommendationType ¶
type PolicyRecommendationType string
const ( RecommendationTypeEnableEcosystem PolicyRecommendationType = "enable_ecosystem" RecommendationTypeUpdateSchedule PolicyRecommendationType = "update_schedule" RecommendationTypeEnableGrouping PolicyRecommendationType = "enable_grouping" RecommendationTypeConfigureRegistry PolicyRecommendationType = "configure_registry" RecommendationTypeSecuritySettings PolicyRecommendationType = "security_settings" RecommendationTypePermissionReduction PolicyRecommendationType = "permission_reduction" RecommendationTypeAddReviewers PolicyRecommendationType = "add_reviewers" )
type PolicySeverity ¶
type PolicySeverity string
const ( PolicySeverityCritical PolicySeverity = "critical" PolicySeverityHigh PolicySeverity = "high" PolicySeverityMedium PolicySeverity = "medium" PolicySeverityLow PolicySeverity = "low" PolicySeverityInfo PolicySeverity = "info" )
type PolicyTrendAnalysis ¶
type PolicyTrendAnalysis struct {
TimeRange string `json:"time_range"`
ComplianceTrend TrendDirection `json:"compliance_trend"`
ViolationTrends map[string]TrendData `json:"violation_trends"`
EcosystemTrends map[string]TrendData `json:"ecosystem_trends"`
RecommendationImpact []RecommendationImpact `json:"recommendation_impact"`
}
PolicyTrendAnalysis provides trend analysis for policy compliance.
type PolicyValidationResult ¶
type PolicyValidationResult struct {
RuleID string `json:"ruleId"`
Passed bool `json:"passed"`
Severity PolicyViolationSeverity `json:"severity"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
ActualValue interface{} `json:"actualValue,omitempty"`
ExpectedValue interface{} `json:"expectedValue,omitempty"`
}
PolicyValidationResult represents the result of a policy validation.
type PolicyValidationRule ¶
type PolicyValidationRule interface {
Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
GetRuleID() string
GetDescription() string
}
PolicyValidationRule defines a rule for validating policy compliance. Implementations check specific aspects of GitHub Actions configuration against organizational policies and return validation results.
type PolicyViolation ¶
type PolicyViolation = DependabotPolicyViolation
Type aliases for Dependabot-specific types.
type PolicyViolationSeverity ¶
type PolicyViolationSeverity string
PolicyViolationSeverity defines the severity of policy violations.
const ( ViolationSeverityLow PolicyViolationSeverity = "low" ViolationSeverityMedium PolicyViolationSeverity = "medium" ViolationSeverityHigh PolicyViolationSeverity = "high" ViolationSeverityCritical PolicyViolationSeverity = "critical" )
type PolicyViolationStatus ¶
type PolicyViolationStatus string
PolicyViolationStatus defines the status of a policy violation.
const ( ViolationStatusOpen PolicyViolationStatus = "open" ViolationStatusInProgress PolicyViolationStatus = "in_progress" ViolationStatusResolved PolicyViolationStatus = "resolved" ViolationStatusIgnored PolicyViolationStatus = "ignored" )
type PolicyViolationType ¶
type PolicyViolationType string
PolicyViolationType represents the type of policy violation.
const ( ViolationTypeMissingEcosystem PolicyViolationType = "missing_ecosystem" ViolationTypeInvalidSchedule PolicyViolationType = "invalid_schedule" ViolationTypeMissingDirectory PolicyViolationType = "missing_directory" ViolationTypeSecurityUpdates PolicyViolationType = "security_updates" ViolationTypeVersionUpdates PolicyViolationType = "version_updates" ViolationTypeIgnoreConditions PolicyViolationType = "ignore_conditions" ViolationTypeAllowedDependencies PolicyViolationType = "allowed_dependencies" )
type ProductInfo ¶
ProductInfo represents product information in CVE records.
type ProtectionRule ¶
type ProtectionRule struct {
Type string `json:"type"`
Reviewers []string `json:"reviewers,omitempty"`
WaitTimer int `json:"waitTimer,omitempty"`
}
ProtectionRule represents an environment protection rule.
type QualityGate ¶
type RateLimit ¶
type RateLimit struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Reset time.Time `json:"reset"`
Used int `json:"used"`
}
RateLimit represents GitHub API rate limit information.
type RateLimitConfig ¶
type RateLimitConfig struct {
MaxPerHour int `json:"max_per_hour"`
MaxPerDay int `json:"max_per_day"`
BurstLimit int `json:"burst_limit"`
ResetPeriod time.Duration `json:"reset_period"`
}
RateLimitConfig defines rate limiting for notifications.
type RateLimitInfo ¶
type RateLimitInfo struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
ResetTime time.Time `json:"reset_time"`
}
RateLimitInfo represents GitHub rate limit information - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*RateLimitInfo) IsRateLimited ¶
func (r *RateLimitInfo) IsRateLimited() bool
IsRateLimited checks if we're close to hitting rate limits.
func (*RateLimitInfo) TimeUntilReset ¶
func (r *RateLimitInfo) TimeUntilReset() time.Duration
TimeUntilReset returns duration until rate limit resets.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter handles GitHub API rate limiting with retry logic.
func NewRateLimiter ¶
func NewRateLimiter() *RateLimiter
NewRateLimiter creates a new rate limiter with default settings.
func (*RateLimiter) GetStatus ¶
func (rl *RateLimiter) GetStatus() (int, int, time.Time)
GetStatus returns current rate limit status.
func (*RateLimiter) SetRetryAfter ¶
func (rl *RateLimiter) SetRetryAfter(duration time.Duration)
SetRetryAfter sets the retry-after duration.
func (*RateLimiter) Update ¶
func (rl *RateLimiter) Update(resp *http.Response)
Update updates rate limit information from response headers.
type RecommendationImpact ¶
type RecommendationImpact struct {
RecommendationID string `json:"recommendation_id"`
ImplementedAt time.Time `json:"implemented_at"`
ImpactedRepos int `json:"impacted_repos"`
ComplianceIncrease float64 `json:"compliance_increase"`
ViolationsReduced int `json:"violations_reduced"`
}
RecommendationImpact tracks the impact of implemented recommendations.
type RecommendationPriority ¶
type RecommendationPriority string
const ( RecommendationPriorityHigh RecommendationPriority = "high" RecommendationPriorityMedium RecommendationPriority = "medium" RecommendationPriorityLow RecommendationPriority = "low" )
type RecommendedAction ¶
type RegexValidationResult ¶
type RegexValidationResult struct {
Pattern string `json:"pattern"`
Valid bool `json:"valid"`
Error string `json:"error,omitempty"`
}
RegexValidationResult represents regex validation result.
type RegressionTestingConfig ¶
type RegressionTestingConfig struct {
Enabled bool `json:"enabled"`
BaselineVersion string `json:"baseline_version"`
TestSuites []string `json:"test_suites"`
AutomatedRegression bool `json:"automated_regression"`
ManualRegressionChecklist []string `json:"manual_regression_checklist"`
RegressionThreshold float64 `json:"regression_threshold"`
TestEnvironment string `json:"test_environment"`
}
type ReleaseSchedule ¶
type ReleaseSchedule struct {
Type string `json:"type"`
DaysOfWeek []string `json:"days_of_week,omitempty"`
TimeOfDay string `json:"time_of_day,omitempty"`
Timezone string `json:"timezone"`
StartDate time.Time `json:"start_date,omitempty"`
EndDate time.Time `json:"end_date,omitempty"`
Frequency string `json:"frequency"`
Duration time.Duration `json:"duration"`
}
type ReleaseWindow ¶
type ReleaseWindow struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
Schedule ReleaseSchedule `json:"schedule"`
AllowedUpdateTypes []string `json:"allowed_update_types"`
RestrictedEcosystems []string `json:"restricted_ecosystems"`
ApprovalRequired bool `json:"approval_required"`
Approvers []string `json:"approvers"`
NotificationSettings WindowNotificationSettings `json:"notification_settings"`
BlackoutPeriods []BlackoutPeriod `json:"blackout_periods"`
EmergencyOverride EmergencyOverride `json:"emergency_override"`
}
ReleaseWindow defines allowed time windows for dependency updates.
type RepoConfigClient ¶
type RepoConfigClient struct {
// contains filtered or unexported fields
}
RepoConfigClient provides GitHub API operations for repository configuration management.
func NewRepoConfigClient ¶
func NewRepoConfigClient(token string) *RepoConfigClient
NewRepoConfigClient creates a new GitHub API client for repository configuration.
func (*RepoConfigClient) ApplyConfigurationToOrganization ¶
func (c *RepoConfigClient) ApplyConfigurationToOrganization(ctx context.Context, org string, config *RepositoryConfig, options *BulkApplyOptions) (*BulkApplyResult, error)
ApplyConfigurationToOrganization applies repository configuration to all repositories in an organization.
func (*RepoConfigClient) CollectRepositoryStates ¶
func (c *RepoConfigClient) CollectRepositoryStates(ctx context.Context, org string) (map[string]RepositoryStateData, error)
CollectRepositoryStates collects state data for all repositories in the organization.
func (*RepoConfigClient) DeleteBranchProtection ¶
func (c *RepoConfigClient) DeleteBranchProtection(ctx context.Context, owner, repo, branch string) error
DeleteBranchProtection removes branch protection rules.
func (*RepoConfigClient) GetBranchProtection ¶
func (c *RepoConfigClient) GetBranchProtection(ctx context.Context, owner, repo, branch string) (*BranchProtection, error)
GetBranchProtection gets branch protection rules for a specific branch.
func (*RepoConfigClient) GetRateLimitStatus ¶
func (c *RepoConfigClient) GetRateLimitStatus() (int, int, time.Time)
GetRateLimitStatus returns current rate limit status.
func (*RepoConfigClient) GetRepository ¶
func (c *RepoConfigClient) GetRepository(ctx context.Context, owner, repo string) (*Repository, error)
GetRepository gets a specific repository.
func (*RepoConfigClient) GetRepositoryConfiguration ¶
func (c *RepoConfigClient) GetRepositoryConfiguration(ctx context.Context, owner, repo string) (*RepositoryConfig, error)
GetRepositoryConfiguration gets comprehensive repository configuration.
func (*RepoConfigClient) GetRepositoryPermissions ¶
func (c *RepoConfigClient) GetRepositoryPermissions(ctx context.Context, owner, repo string) (map[string]string, map[string]string, error)
GetRepositoryPermissions gets team and user permissions for a repository.
func (*RepoConfigClient) ListRepositories ¶
func (c *RepoConfigClient) ListRepositories(ctx context.Context, org string, options *ListOptions) ([]*Repository, error)
ListRepositories lists all repositories for an organization with pagination.
func (*RepoConfigClient) SetLogger ¶
func (c *RepoConfigClient) SetLogger(logger *ChangeLogger)
SetLogger sets the change logger for this client.
func (*RepoConfigClient) SetTimeout ¶
func (c *RepoConfigClient) SetTimeout(timeout time.Duration)
SetTimeout configures the HTTP client timeout.
func (*RepoConfigClient) UpdateBranchProtection ¶
func (c *RepoConfigClient) UpdateBranchProtection(ctx context.Context, owner, repo, branch string, protection *BranchProtection) (*BranchProtection, error)
UpdateBranchProtection updates branch protection rules.
func (*RepoConfigClient) UpdateBranchProtectionConfig ¶
func (c *RepoConfigClient) UpdateBranchProtectionConfig(ctx context.Context, owner, repo, branch string, config *BranchProtectionConfig) error
UpdateBranchProtectionConfig updates branch protection from config format.
func (*RepoConfigClient) UpdateRepository ¶
func (c *RepoConfigClient) UpdateRepository(ctx context.Context, owner, repo string, update *RepositoryUpdate) (*Repository, error)
UpdateRepository updates repository settings.
func (*RepoConfigClient) UpdateRepositoryConfiguration ¶
func (c *RepoConfigClient) UpdateRepositoryConfiguration(ctx context.Context, owner, repo string, config *RepositoryConfig) error
UpdateRepositoryConfiguration updates comprehensive repository configuration.
func (*RepoConfigClient) UpdateRepositoryConfigurationWithConfirmation ¶
func (c *RepoConfigClient) UpdateRepositoryConfigurationWithConfirmation(ctx context.Context, owner, repo string, config *RepositoryConfig, confirmationPrompt *ConfirmationPrompt) error
UpdateRepositoryConfigurationWithConfirmation updates repository configuration with optional confirmation prompts.
func (*RepoConfigClient) UpdateRepositoryPermissions ¶
func (c *RepoConfigClient) UpdateRepositoryPermissions(ctx context.Context, owner, repo string, perms PermissionsConfig) error
UpdateRepositoryPermissions updates team and user permissions.
type RepoConfigSettings ¶
type RepoConfigSettings struct {
HasIssues bool `json:"has_issues"`
HasProjects bool `json:"has_projects"`
HasWiki bool `json:"has_wiki"`
HasDownloads bool `json:"has_downloads"`
AllowSquashMerge bool `json:"allow_squash_merge"`
AllowMergeCommit bool `json:"allow_merge_commit"`
AllowRebaseMerge bool `json:"allow_rebase_merge"`
DeleteBranchOnMerge bool `json:"delete_branch_on_merge"`
DefaultBranch string `json:"default_branch"`
}
RepoConfigSettings represents repository feature settings.
type RepoInfo ¶
type RepoInfo struct {
// Name is the repository name
Name string `json:"name"`
// CloneURL is the HTTPS clone URL for the repository
CloneURL string `json:"clone_url"`
// Description is the repository description
Description string `json:"description"`
// Private indicates if the repository is private
Private bool `json:"private"`
// Archived indicates if the repository is archived
Archived bool `json:"archived"`
// Fork indicates if the repository is a fork
Fork bool `json:"fork"`
// DefaultBranch is the name of the repository's default branch (e.g., "main", "master")
DefaultBranch string `json:"default_branch"`
}
RepoInfo represents GitHub repository information returned by the GitHub API. It contains essential repository metadata used during clone operations and gzh.yaml generation.
func ListRepos ¶
ListRepos retrieves complete repository information for a GitHub organization. It makes paginated requests to the GitHub API to fetch all repositories in the specified organization, handling pagination automatically.
Parameters:
- ctx: Context for request cancellation and timeout control
- org: GitHub organization name
Returns a slice of RepoInfo with complete repository metadata or an error if the organization doesn't exist, access is denied, or the API request fails.
type Repository ¶
type Repository struct {
ID int64 `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
Description string `json:"description"`
Homepage string `json:"homepage"`
Private bool `json:"private"`
Archived bool `json:"archived"`
HTMLURL string `json:"html_url"`
CloneURL string `json:"clone_url"`
SSHURL string `json:"ssh_url"`
DefaultBranch string `json:"default_branch"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Language string `json:"language"`
Topics []string `json:"topics"`
// Repository settings
HasIssues bool `json:"has_issues"`
HasProjects bool `json:"has_projects"`
HasWiki bool `json:"has_wiki"`
HasDownloads bool `json:"has_downloads"`
// Security and collaboration settings
AllowSquashMerge bool `json:"allow_squash_merge"`
AllowMergeCommit bool `json:"allow_merge_commit"`
AllowRebaseMerge bool `json:"allow_rebase_merge"`
DeleteBranchOnMerge bool `json:"delete_branch_on_merge"`
}
Repository represents a GitHub repository with configuration details.
type RepositoryActionsState ¶
type RepositoryActionsState struct {
Organization string `json:"organization"`
Repository string `json:"repository"`
ActionsEnabled bool `json:"actionsEnabled"`
PermissionLevel ActionsPermissionLevel `json:"permissionLevel"`
AllowedActions []string `json:"allowedActions,omitempty"`
WorkflowPermissions WorkflowPermissions `json:"workflowPermissions"`
SecuritySettings ActionsSecuritySettings `json:"securitySettings"`
Secrets []SecretInfo `json:"secrets,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
Environments []EnvironmentInfo `json:"environments,omitempty"`
Runners []RunnerInfo `json:"runners,omitempty"`
RecentWorkflows []WorkflowInfo `json:"recentWorkflows,omitempty"`
LastUpdated time.Time `json:"lastUpdated"`
}
RepositoryActionsState represents the current Actions configuration state of a repository.
type RepositoryConfig ¶
type RepositoryConfig struct {
Name string `json:"name"`
Description string `json:"description"`
Homepage string `json:"homepage"`
Private bool `json:"private"`
Archived bool `json:"archived"`
Topics []string `json:"topics"`
Settings RepoConfigSettings `json:"settings"`
BranchProtection map[string]BranchProtectionConfig `json:"branch_protection,omitempty"`
Permissions PermissionsConfig `json:"permissions,omitempty"`
}
RepositoryConfig represents comprehensive repository configuration.
type RepositoryEvaluationExplanation ¶
type RepositoryEvaluationExplanation struct {
Repository string `json:"repository"`
Language string `json:"language"`
Topics []string `json:"topics"`
Visibility string `json:"visibility"`
IsArchived bool `json:"isArchived"`
IsTemplate bool `json:"isTemplate"`
Result bool `json:"result"`
MatchedRules []string `json:"matchedRules"`
}
RepositoryEvaluationExplanation explains repository-based condition evaluation.
type RepositoryFilters ¶
type RepositoryFilters struct {
IncludeNames []string
ExcludeNames []string
IncludePrivate bool
IncludePublic bool
Languages []string
SizeLimit int64
LastUpdatedDays int
}
RepositoryFilters contains filtering criteria for repositories.
type RepositoryInfo ¶
type RepositoryInfo struct {
Name string `json:"name"`
FullName string `json:"full_name"`
Description string `json:"description"`
DefaultBranch string `json:"default_branch"`
CloneURL string `json:"clone_url"`
SSHURL string `json:"ssh_url"`
HTMLURL string `json:"html_url"`
Private bool `json:"private"`
Archived bool `json:"archived"`
Disabled bool `json:"disabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Language string `json:"language"`
Size int `json:"size"`
Topics []string `json:"topics"`
Visibility string `json:"visibility"`
IsTemplate bool `json:"is_template"`
}
RepositoryInfo represents a GitHub repository with essential information for interfaces.
type RepositoryOperationResult ¶
type RepositoryOperationResult struct {
Repository string
Operation string
Success bool
Error string
Duration string
}
RepositoryOperationResult represents the result of a single repository operation.
type RepositoryStateData ¶
type RepositoryStateData struct {
Name string
Private bool
Archived bool
HasIssues bool
HasWiki bool
HasProjects bool
HasDownloads bool
// Branch protection
BranchProtection map[string]BranchProtectionData
// Security features
VulnerabilityAlerts bool
SecurityAdvisories bool
// Files present
Files []string
// Workflows
Workflows []string
// Last modified
LastModified string // ISO 8601 format
}
RepositoryStateData represents the raw state data collected from GitHub This is a simple data structure with no dependencies on other packages.
type RepositoryStream ¶
type RepositoryStream struct {
Repository *Repository
Error error
Metadata StreamMetadata
}
RepositoryStream represents a streaming repository result.
type RepositoryUpdate ¶
type RepositoryUpdate struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Homepage *string `json:"homepage,omitempty"`
Private *bool `json:"private,omitempty"`
Archived *bool `json:"archived,omitempty"`
HasIssues *bool `json:"has_issues,omitempty"`
HasProjects *bool `json:"has_projects,omitempty"`
HasWiki *bool `json:"has_wiki,omitempty"`
HasDownloads *bool `json:"has_downloads,omitempty"`
DefaultBranch *string `json:"default_branch,omitempty"`
AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"`
AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"`
AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"`
DeleteBranchOnMerge *bool `json:"delete_branch_on_merge,omitempty"`
Topics []string `json:"topics,omitempty"`
}
RepositoryUpdate represents fields that can be updated in a repository.
type RepositoryWebhookInfo ¶
type RepositoryWebhookInfo struct {
Repository string `json:"repository"`
Webhooks []*WebhookInfo `json:"webhooks"`
Compliance string `json:"compliance"` // compliant, non-compliant, unknown
Issues []string `json:"issues,omitempty"`
}
RepositoryWebhookInfo represents webhook information for a repository.
type RequestMetrics ¶
type RequestMetrics struct {
// contains filtered or unexported fields
}
RequestMetrics tracks API usage statistics.
type RequiredConversationResolution ¶
type RequiredConversationResolution struct {
Enabled bool `json:"enabled"`
}
type RequiredPermission ¶
type RequiredPermission struct {
Scope string `json:"scope"`
Level PermissionLevel `json:"level"`
Description string `json:"description"`
Optional bool `json:"optional"`
}
RequiredPermission represents a required permission for an operation.
type RequiredPullRequestReviews ¶
type RequiredPullRequestReviews struct {
DismissStaleReviews bool `json:"dismiss_stale_reviews"`
RequireCodeOwnerReviews bool `json:"require_code_owner_reviews"`
RequiredApprovingReviewCount int `json:"required_approving_review_count"`
DismissalRestrictions *UserTeamRestrictions `json:"dismissal_restrictions,omitempty"`
}
RequiredPullRequestReviews represents PR review requirements.
type RequiredStatusChecks ¶
type RequiredStatusChecks struct {
Strict bool `json:"strict"`
Contexts []string `json:"contexts"`
}
RequiredStatusChecks represents required status checks configuration.
type Requirement ¶
type Requirement struct {
ID string `json:"id"`
Description string `json:"description"`
Mandatory bool `json:"mandatory"`
}
Requirement defines a specific compliance requirement.
type ResilientGitHubClient ¶
type ResilientGitHubClient struct {
// contains filtered or unexported fields
}
ResilientGitHubClient provides GitHub API operations with network resilience - DISABLED (recovery package removed) Simple HTTP client implementation to replace deleted recovery package.
func NewResilientGitHubClient ¶
func NewResilientGitHubClient(token string) *ResilientGitHubClient
NewResilientGitHubClient creates a new resilient GitHub client - DISABLED (recovery package removed) Simple HTTP client implementation to replace deleted recovery package.
func NewResilientGitHubClientWithConfig ¶
func NewResilientGitHubClientWithConfig(token string, timeout time.Duration) *ResilientGitHubClient
NewResilientGitHubClientWithConfig creates a resilient GitHub client with custom config - DISABLED (recovery package removed) Simple HTTP client implementation to replace deleted recovery package.
func (*ResilientGitHubClient) Close ¶
func (c *ResilientGitHubClient) Close()
Close closes the underlying HTTP client connections - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*ResilientGitHubClient) GetDefaultBranch ¶
func (c *ResilientGitHubClient) GetDefaultBranch(ctx context.Context, org, repo string) (string, error)
GetDefaultBranch retrieves the default branch for a repository with network resilience.
func (*ResilientGitHubClient) GetRateLimit ¶
func (c *ResilientGitHubClient) GetRateLimit(ctx context.Context) (*RateLimitInfo, error)
GetRateLimit retrieves current rate limit status.
func (*ResilientGitHubClient) GetStats ¶
func (c *ResilientGitHubClient) GetStats() map[string]interface{}
GetStats returns statistics about the underlying HTTP client - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*ResilientGitHubClient) ListRepositories ¶
ListRepositories retrieves all repositories for an organization with pagination and resilience.
func (*ResilientGitHubClient) SetBaseURL ¶
func (c *ResilientGitHubClient) SetBaseURL(baseURL string)
SetBaseURL updates the base URL (useful for GitHub Enterprise).
func (*ResilientGitHubClient) SetToken ¶
func (c *ResilientGitHubClient) SetToken(token string)
SetToken updates the authentication token.
type ResponseTimeConfig ¶
type ResponseTimeConfig struct {
CriticalVulnerabilities time.Duration `json:"critical_vulnerabilities"`
HighVulnerabilities time.Duration `json:"high_vulnerabilities"`
MediumVulnerabilities time.Duration `json:"medium_vulnerabilities"`
LowVulnerabilities time.Duration `json:"low_vulnerabilities"`
BusinessHours BusinessHours `json:"business_hours"`
}
ResponseTimeConfig defines required response times.
type ResumableCloneManager ¶
type ResumableCloneManager struct {
// contains filtered or unexported fields
}
ResumableCloneManager handles resumable clone operations.
func NewResumableCloneManager ¶
func NewResumableCloneManager(config BulkOperationsConfig) *ResumableCloneManager
NewResumableCloneManager creates a new resumable clone manager.
func (*ResumableCloneManager) RefreshAllResumable ¶
func (rcm *ResumableCloneManager) RefreshAllResumable(ctx context.Context, targetPath, org, strategy string, parallel, maxRetries int, resume bool, progressMode string) error
RefreshAllResumable performs bulk repository refresh with resumable support.
type RetryableError ¶
type RetryableError struct {
Err error
RetryAfter time.Duration
AttemptsLeft int
NextRetryTime time.Time
}
RetryableError represents an error that can be retried.
func (*RetryableError) Error ¶
func (e *RetryableError) Error() string
func (*RetryableError) IsRetryable ¶
func (e *RetryableError) IsRetryable() bool
IsRetryable returns true if the error is retryable.
type ReviewNote ¶
type ReviewNote struct {
Author string `json:"author"`
Content string `json:"content"`
Type string `json:"type"`
Timestamp time.Time `json:"timestamp"`
}
ReviewNote represents a review note for a security update.
type RiskAssessment ¶
type RiskAssessment struct {
OverallRisk RiskLevel `json:"overall_risk"`
BusinessImpact ImpactLevel `json:"business_impact"`
TechnicalRisk RiskLevel `json:"technical_risk"`
Factors []RiskFactor `json:"factors"`
Mitigation []MitigationStrategy `json:"mitigation"`
Assessor string `json:"assessor"`
AssessedAt time.Time `json:"assessed_at"`
}
RiskAssessment represents a risk assessment for a security update.
type RiskFactor ¶
type RiskFactor struct {
Type string `json:"type"`
Description string `json:"description"`
Impact RiskLevel `json:"impact"`
Likelihood string `json:"likelihood"`
}
RiskFactor represents a factor contributing to risk.
type RiskLevel ¶
type RiskLevel string
RiskLevel represents the risk level of a change.
const (
SecurityRiskLevelMinimal RiskLevel = "minimal"
)
Use existing RiskLevel from interfaces.go Additional risk levels for security context.
type RiskLevelType ¶
type RiskLevelType int
RiskLevelType represents the risk level of an operation.
const ( RiskLevelLow RiskLevelType = iota RiskLevelMedium RiskLevelHigh RiskLevelCritical )
type RollbackPlan ¶
type RollbackPolicy ¶
type RollbackPolicy struct {
Enabled bool `json:"enabled"`
AutoRollbackTriggers []RollbackTrigger `json:"autoRollbackTriggers"`
ManualRollbackProcedure ManualRollbackProcedure `json:"manualRollbackProcedure"`
RollbackTimeframe time.Duration `json:"rollbackTimeframe"`
HealthCheckRequirements []HealthCheck `json:"healthCheckRequirements"`
RollbackApprovers []string `json:"rollbackApprovers"`
DataMigrationHandling DataMigrationHandling `json:"dataMigrationHandling"`
NotificationPlan RollbackNotificationPlan `json:"notificationPlan"`
PostRollbackAnalysis bool `json:"postRollbackAnalysis"`
}
RollbackPolicy defines rollback procedures and conditions.
type RollbackRequest ¶
type RollbackRequest struct {
ChangeID string `json:"changeId"`
Repository string `json:"repository"`
Category string `json:"category"`
DryRun bool `json:"dryRun"`
Description string `json:"description"`
}
RollbackRequest represents a rollback operation.
type RollbackResult ¶
type RollbackResult struct {
Success bool `json:"success"`
ChangeID string `json:"changeId"`
NewChangeID string `json:"newChangeId,omitempty"`
Errors []string `json:"errors,omitempty"`
DryRun bool `json:"dryRun"`
}
RollbackResult contains the result of a rollback operation.
type RollbackStep ¶
type RollbackTrigger ¶
type RuleFilter ¶
type RuleFilter struct {
Organization string `json:"organization,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Tags []string `json:"tags,omitempty"`
Category string `json:"category,omitempty"`
EventTypes []EventType `json:"eventTypes,omitempty"`
CreatedBy string `json:"createdBy,omitempty"`
CreatedAfter *time.Time `json:"createdAfter,omitempty"`
CreatedBefore *time.Time `json:"createdBefore,omitempty"`
}
RuleFilter defines criteria for filtering automation rules.
type RuleManager ¶
type RuleManager struct {
// contains filtered or unexported fields
}
RuleManager implements the AutomationRuleService interface.
func NewRuleManager ¶
func NewRuleManager(logger Logger, apiClient APIClient, evaluator ConditionEvaluator, actionExecutor ActionExecutor, storage RuleStorage, templateStorage TemplateStorage) *RuleManager
NewRuleManager creates a new rule manager instance.
func (*RuleManager) CancelExecution ¶
func (rm *RuleManager) CancelExecution(ctx context.Context, executionID string) error
CancelExecution cancels a running execution.
func (*RuleManager) CreateRule ¶
func (rm *RuleManager) CreateRule(ctx context.Context, rule *AutomationRule) error
CreateRule creates a new automation rule.
func (*RuleManager) CreateRuleSet ¶
func (rm *RuleManager) CreateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
CreateRuleSet creates a new rule set.
func (*RuleManager) CreateTemplate ¶
func (rm *RuleManager) CreateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
CreateTemplate creates a new rule template.
func (*RuleManager) DeleteRule ¶
func (rm *RuleManager) DeleteRule(ctx context.Context, org, ruleID string) error
DeleteRule deletes an automation rule.
func (*RuleManager) DeleteRuleSet ¶
func (rm *RuleManager) DeleteRuleSet(ctx context.Context, org, setID string) error
DeleteRuleSet deletes a rule set.
func (*RuleManager) DeleteTemplate ¶
func (rm *RuleManager) DeleteTemplate(ctx context.Context, templateID string) error
DeleteTemplate deletes a template.
func (*RuleManager) DisableRule ¶
func (rm *RuleManager) DisableRule(ctx context.Context, org, ruleID string) error
DisableRule disables an automation rule.
func (*RuleManager) DryRunRule ¶
func (rm *RuleManager) DryRunRule(ctx context.Context, ruleID string, event *GitHubEvent) (*RuleTestResult, error)
DryRunRule performs a dry run of a rule against an event without executing actions.
func (*RuleManager) EnableRule ¶
func (rm *RuleManager) EnableRule(ctx context.Context, org, ruleID string) error
EnableRule enables an automation rule.
func (*RuleManager) EvaluateConditions ¶
func (rm *RuleManager) EvaluateConditions(ctx context.Context, rule *AutomationRule, event *GitHubEvent) (bool, error)
EvaluateConditions evaluates conditions for a rule against an event.
func (*RuleManager) ExecuteRule ¶
func (rm *RuleManager) ExecuteRule(ctx context.Context, rule *AutomationRule, execContext *AutomationExecutionContext) (*AutomationRuleExecution, error)
ExecuteRule executes a rule if conditions are met.
func (*RuleManager) GetExecution ¶
func (rm *RuleManager) GetExecution(ctx context.Context, executionID string) (*AutomationRuleExecution, error)
GetExecution retrieves an execution by ID.
func (*RuleManager) GetRule ¶
func (rm *RuleManager) GetRule(ctx context.Context, org, ruleID string) (*AutomationRule, error)
GetRule retrieves an automation rule by ID.
func (*RuleManager) GetRuleSet ¶
func (rm *RuleManager) GetRuleSet(ctx context.Context, org, setID string) (*AutomationRuleSet, error)
GetRuleSet retrieves a rule set by ID.
func (*RuleManager) GetTemplate ¶
func (rm *RuleManager) GetTemplate(ctx context.Context, templateID string) (*AutomationRuleTemplate, error)
GetTemplate retrieves a template by ID.
func (*RuleManager) InstantiateTemplate ¶
func (rm *RuleManager) InstantiateTemplate(ctx context.Context, templateID string, variables map[string]interface{}) (*AutomationRule, error)
InstantiateTemplate creates a rule from a template with variable substitution.
func (*RuleManager) ListExecutions ¶
func (rm *RuleManager) ListExecutions(ctx context.Context, org string, filter *ExecutionFilter) ([]*AutomationRuleExecution, error)
ListExecutions lists executions with optional filtering.
func (*RuleManager) ListRuleSets ¶
func (rm *RuleManager) ListRuleSets(ctx context.Context, org string) ([]*AutomationRuleSet, error)
ListRuleSets lists all rule sets for an organization.
func (*RuleManager) ListRules ¶
func (rm *RuleManager) ListRules(ctx context.Context, org string, filter *RuleFilter) ([]*AutomationRule, error)
ListRules lists automation rules with optional filtering.
func (*RuleManager) ListTemplates ¶
func (rm *RuleManager) ListTemplates(ctx context.Context, category string) ([]*AutomationRuleTemplate, error)
ListTemplates lists templates by category.
func (*RuleManager) TestRule ¶
func (rm *RuleManager) TestRule(ctx context.Context, rule *AutomationRule, testEvent *GitHubEvent) (*RuleTestResult, error)
TestRule tests a rule against a sample event.
func (*RuleManager) UpdateRule ¶
func (rm *RuleManager) UpdateRule(ctx context.Context, rule *AutomationRule) error
UpdateRule updates an existing automation rule.
func (*RuleManager) UpdateRuleSet ¶
func (rm *RuleManager) UpdateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
UpdateRuleSet updates an existing rule set.
func (*RuleManager) UpdateTemplate ¶
func (rm *RuleManager) UpdateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
UpdateTemplate updates an existing template.
func (*RuleManager) ValidateRule ¶
func (rm *RuleManager) ValidateRule(ctx context.Context, rule *AutomationRule) (*RuleValidationResult, error)
ValidateRule validates a rule structure and configuration.
type RuleStorage ¶
type RuleStorage interface {
// Rule operations
CreateRule(ctx context.Context, rule *AutomationRule) error
GetRule(ctx context.Context, org, ruleID string) (*AutomationRule, error)
ListRules(ctx context.Context, org string, filter *RuleFilter) ([]*AutomationRule, error)
UpdateRule(ctx context.Context, rule *AutomationRule) error
DeleteRule(ctx context.Context, org, ruleID string) error
// Rule Set operations
CreateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
GetRuleSet(ctx context.Context, org, setID string) (*AutomationRuleSet, error)
ListRuleSets(ctx context.Context, org string) ([]*AutomationRuleSet, error)
UpdateRuleSet(ctx context.Context, ruleSet *AutomationRuleSet) error
DeleteRuleSet(ctx context.Context, org, setID string) error
// Execution history
SaveExecution(ctx context.Context, execution *AutomationRuleExecution) error
GetExecution(ctx context.Context, executionID string) (*AutomationRuleExecution, error)
ListExecutions(ctx context.Context, org string, filter *ExecutionFilter) ([]*AutomationRuleExecution, error)
}
RuleStorage defines the interface for persisting automation rules.
type RuleTestResult ¶
type RuleTestResult struct {
RuleID string `json:"ruleId"`
ConditionsMatched bool `json:"conditionsMatched"`
ActionsExecuted []ActionExecutionResult `json:"actionsExecuted"`
ExecutionTime time.Duration `json:"executionTime"`
Errors []string `json:"errors,omitempty"`
Context AutomationExecutionContext `json:"context"`
}
RuleTestResult represents the result of testing a rule.
type RuleValidationError ¶
type RuleValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Severity string `json:"severity"`
Suggestion string `json:"suggestion,omitempty"`
}
RuleValidationError represents a validation error.
type RuleValidationResult ¶
type RuleValidationResult struct {
Valid bool `json:"valid"`
Errors []RuleValidationError `json:"errors,omitempty"`
Warnings []RuleValidationWarning `json:"warnings,omitempty"`
Score int `json:"score"` // 0-100
}
RuleValidationResult represents the result of rule validation.
type RuleValidationWarning ¶
type RuleValidationWarning struct {
Field string `json:"field"`
Message string `json:"message"`
Suggestion string `json:"suggestion,omitempty"`
}
RuleValidationWarning represents a validation warning.
type RunnerInfo ¶
type RunnerInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
OS string `json:"os"`
Labels []string `json:"labels"`
Busy bool `json:"busy"`
}
RunnerInfo represents information about a repository runner.
type RunnerPolicy ¶
type RunnerPolicy struct {
AllowedRunnerTypes []RunnerType `json:"allowedRunnerTypes" yaml:"allowedRunnerTypes"`
RequireSelfHostedLabels []string `json:"requireSelfHostedLabels,omitempty" yaml:"requireSelfHostedLabels,omitempty"`
RestrictedRunnerLabels []string `json:"restrictedRunnerLabels,omitempty" yaml:"restrictedRunnerLabels,omitempty"`
MaxConcurrentJobs int `json:"maxConcurrentJobs,omitempty" yaml:"maxConcurrentJobs,omitempty"`
MaxJobExecutionTime time.Duration `json:"maxJobExecutionTime,omitempty" yaml:"maxJobExecutionTime,omitempty"`
RunnerGroups []string `json:"runnerGroups,omitempty" yaml:"runnerGroups,omitempty"`
RequireRunnerApproval bool `json:"requireRunnerApproval" yaml:"requireRunnerApproval"`
SelfHostedRunnerPolicy SelfHostedRunnerPolicy `json:"selfHostedRunnerPolicy" yaml:"selfHostedRunnerPolicy"`
}
RunnerPolicy defines policy for GitHub Actions runners.
type RunnerPolicyValidationRule ¶
type RunnerPolicyValidationRule struct{}
RunnerPolicyValidationRule validates runner policy compliance.
func (*RunnerPolicyValidationRule) GetDescription ¶
func (r *RunnerPolicyValidationRule) GetDescription() string
func (*RunnerPolicyValidationRule) GetRuleID ¶
func (r *RunnerPolicyValidationRule) GetRuleID() string
func (*RunnerPolicyValidationRule) Validate ¶
func (r *RunnerPolicyValidationRule) Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
type RunnerType ¶
type RunnerType string
RunnerType defines the type of runner allowed.
const ( RunnerTypeGitHubHosted RunnerType = "github_hosted" RunnerTypeSelfHosted RunnerType = "self_hosted" RunnerTypeOrganization RunnerType = "organization" RunnerTypeRepository RunnerType = "repository" )
type ScheduleType ¶
type ScheduleType string
ScheduleType defines the type of schedule.
const ( ScheduleTypeCron ScheduleType = "cron" ScheduleTypeInterval ScheduleType = "interval" ScheduleTypeOneTime ScheduleType = "one_time" )
type SecretInfo ¶
type SecretInfo struct {
Name string `json:"name"`
Visibility string `json:"visibility"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Environment string `json:"environment,omitempty"`
}
SecretInfo represents information about a repository secret.
type SecretPolicyValidationRule ¶
type SecretPolicyValidationRule struct{}
SecretPolicyValidationRule validates secret policy compliance.
func (*SecretPolicyValidationRule) GetDescription ¶
func (r *SecretPolicyValidationRule) GetDescription() string
func (*SecretPolicyValidationRule) GetRuleID ¶
func (r *SecretPolicyValidationRule) GetRuleID() string
func (*SecretPolicyValidationRule) Validate ¶
func (r *SecretPolicyValidationRule) Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
type SecretRotationPolicy ¶
type SecretRotationPolicy struct {
Enabled bool `json:"enabled" yaml:"enabled"`
RotationInterval time.Duration `json:"rotationInterval" yaml:"rotationInterval"`
RequireRotationWarning bool `json:"requireRotationWarning" yaml:"requireRotationWarning"`
WarningDays int `json:"warningDays" yaml:"warningDays"`
AutoRotateSecrets []string `json:"autoRotateSecrets,omitempty" yaml:"autoRotateSecrets,omitempty"`
}
SecretRotationPolicy defines policy for secret rotation.
type SecretVisibility ¶
type SecretVisibility string
SecretVisibility defines the visibility scope for secrets.
const ( SecretVisibilityAll SecretVisibility = "all" SecretVisibilityPrivate SecretVisibility = "private" SecretVisibilitySelectedRepos SecretVisibility = "selected" )
type SecretsPolicy ¶
type SecretsPolicy struct {
AllowedSecrets []string `json:"allowedSecrets,omitempty" yaml:"allowedSecrets,omitempty"`
RestrictedSecrets []string `json:"restrictedSecrets,omitempty" yaml:"restrictedSecrets,omitempty"`
RequireApprovalForNewSecrets bool `json:"requireApprovalForNewSecrets" yaml:"requireApprovalForNewSecrets"`
SecretVisibility SecretVisibility `json:"secretVisibility" yaml:"secretVisibility"`
AllowSecretsInheritance bool `json:"allowSecretsInheritance" yaml:"allowSecretsInheritance"`
SecretNamingPatterns []string `json:"secretNamingPatterns,omitempty" yaml:"secretNamingPatterns,omitempty"`
MaxSecretCount int `json:"maxSecretCount,omitempty" yaml:"maxSecretCount,omitempty"`
SecretRotationPolicy SecretRotationPolicy `json:"secretRotationPolicy" yaml:"secretRotationPolicy"`
}
SecretsPolicy defines policy for managing secrets.
type SecurityAdvisoryInfo ¶
type SecurityAdvisoryInfo struct {
ID string `json:"id"`
Summary string `json:"summary"`
Severity string `json:"severity"`
CVSS float64 `json:"cvss_score"`
References []string `json:"references"`
PublishedAt time.Time `json:"published_at"`
}
SecurityAdvisoryInfo represents security vulnerability information.
type SecurityImpactAnalysis ¶
type SecurityIssueSeverity ¶
type SecurityIssueSeverity string
const ( SeverityCritical SecurityIssueSeverity = "critical" SeverityHigh SecurityIssueSeverity = "high" SeverityMedium SecurityIssueSeverity = "medium" SeverityLow SecurityIssueSeverity = "low" SeverityInfo SecurityIssueSeverity = "info" )
type SecurityPolicySettings ¶
type SecurityPolicySettings struct {
EnableVulnerabilityAlerts bool `json:"enable_vulnerability_alerts"`
AutoFixSecurityVulns bool `json:"auto_fix_security_vulns"`
AllowedSecurityUpdateTypes []string `json:"allowed_security_update_types"`
SecurityReviewRequired bool `json:"security_review_required"`
CriticalVulnAutoMerge bool `json:"critical_vuln_auto_merge"`
VulnReportingWebhook string `json:"vuln_reporting_webhook,omitempty"`
ExcludedVulnerabilityIDs []string `json:"excluded_vulnerability_ids,omitempty"`
}
SecurityPolicySettings defines security-related policies for Dependabot.
type SecurityRiskLevel ¶
type SecurityRiskLevel string
const ( SecurityRiskCritical SecurityRiskLevel = "critical" SecurityRiskHigh SecurityRiskLevel = "high" SecurityRiskMedium SecurityRiskLevel = "medium" SecurityRiskLow SecurityRiskLevel = "low" SecurityRiskNone SecurityRiskLevel = "none" SecurityRiskMinimal SecurityRiskLevel = "minimal" )
type SecuritySettingsValidationRule ¶
type SecuritySettingsValidationRule struct{}
SecuritySettingsValidationRule validates security settings compliance.
func (*SecuritySettingsValidationRule) GetDescription ¶
func (r *SecuritySettingsValidationRule) GetDescription() string
func (*SecuritySettingsValidationRule) GetRuleID ¶
func (r *SecuritySettingsValidationRule) GetRuleID() string
func (*SecuritySettingsValidationRule) Validate ¶
func (r *SecuritySettingsValidationRule) Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
type SecurityUpdateDecision ¶
type SecurityUpdateDecision struct {
Approved bool `json:"approved"`
Reason string `json:"reason"`
RuleID string `json:"rule_id,omitempty"`
Actions []AutoApprovalAction `json:"actions,omitempty"`
RequiresTest bool `json:"requires_test"`
Conditions []string `json:"conditions,omitempty"`
}
SecurityUpdateDecision represents the result of evaluating a security update.
type SecurityUpdatePolicy ¶
type SecurityUpdatePolicy struct {
ID string `json:"id"`
Name string `json:"name"`
Organization string `json:"organization"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
AutoApprovalRules []AutoApprovalRule `json:"auto_approval_rules"`
SeverityThresholds SeverityThresholdConfig `json:"severity_thresholds"`
ResponseTimeRequirements ResponseTimeConfig `json:"response_time_requirements"`
NotificationSettings NotificationConfig `json:"notification_settings"`
ExclusionRules []VulnerabilityExclusion `json:"exclusion_rules"`
EscalationRules []EscalationRule `json:"escalation_rules"`
ComplianceSettings ComplianceConfig `json:"compliance_settings"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Version int `json:"version"`
}
SecurityUpdatePolicy defines policies for handling security updates.
type SecurityUpdatePolicyManager ¶
type SecurityUpdatePolicyManager struct {
// contains filtered or unexported fields
}
SecurityUpdatePolicyManager manages security update policies and vulnerability handling.
func NewSecurityUpdatePolicyManager ¶
func NewSecurityUpdatePolicyManager(logger Logger, apiClient APIClient, dependabotManager *DependabotConfigManager) *SecurityUpdatePolicyManager
NewSecurityUpdatePolicyManager creates a new security update policy manager.
func (*SecurityUpdatePolicyManager) CreateSecurityPolicy ¶
func (sm *SecurityUpdatePolicyManager) CreateSecurityPolicy(ctx context.Context, policy *SecurityUpdatePolicy) error
CreateSecurityPolicy creates a new security update policy.
func (*SecurityUpdatePolicyManager) EvaluateSecurityUpdate ¶
func (sm *SecurityUpdatePolicyManager) EvaluateSecurityUpdate(ctx context.Context, policyID string, update *SecurityUpdateStatus) (*SecurityUpdateDecision, error)
EvaluateSecurityUpdate evaluates whether a security update should be auto-approved.
func (*SecurityUpdatePolicyManager) ProcessSecurityUpdates ¶
func (sm *SecurityUpdatePolicyManager) ProcessSecurityUpdates(ctx context.Context, organization string) (*SecurityUpdateProcessResult, error)
ProcessSecurityUpdates processes pending security updates for an organization.
type SecurityUpdateProcessResult ¶
type SecurityUpdateProcessResult struct {
Organization string `json:"organization"`
TotalUpdates int `json:"total_updates"`
ApprovedUpdates int `json:"approved_updates"`
PendingReview int `json:"pending_review"`
FailedUpdates int `json:"failed_updates"`
Updates []SecurityUpdateStatus `json:"updates"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
ProcessingTime time.Duration `json:"processing_time"`
}
SecurityUpdateProcessResult represents the result of processing security updates.
type SecurityUpdateStatus ¶
type SecurityUpdateStatus struct {
UpdateID string `json:"update_id"`
VulnerabilityID string `json:"vulnerability_id"`
Repository string `json:"repository"`
Organization string `json:"organization"`
Package PackageInfo `json:"package"`
CurrentVersion string `json:"current_version"`
TargetVersion string `json:"target_version"`
Status UpdateStatus `json:"status"`
Priority UpdatePriority `json:"priority"`
AutoApproved bool `json:"auto_approved"`
ApprovalReason string `json:"approval_reason,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeadlineAt *time.Time `json:"deadline_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
ApprovedBy []string `json:"approved_by,omitempty"`
ReviewNotes []ReviewNote `json:"review_notes,omitempty"`
TestResults *TestResults `json:"test_results,omitempty"`
RiskAssessment *RiskAssessment `json:"risk_assessment,omitempty"`
}
SecurityUpdateStatus represents the status of a security update.
type SelfHostedRunnerPolicy ¶
type SelfHostedRunnerPolicy struct {
RequireRunnerRegistration bool `json:"requireRunnerRegistration" yaml:"requireRunnerRegistration"`
AllowedOperatingSystems []string `json:"allowedOperatingSystems,omitempty" yaml:"allowedOperatingSystems,omitempty"`
RequiredSecurityPatches bool `json:"requiredSecurityPatches" yaml:"requiredSecurityPatches"`
DisallowPublicRepositories bool `json:"disallowPublicRepositories" yaml:"disallowPublicRepositories"`
RequireEncryptedStorage bool `json:"requireEncryptedStorage" yaml:"requireEncryptedStorage"`
RunnerTimeout time.Duration `json:"runnerTimeout,omitempty" yaml:"runnerTimeout,omitempty"`
MaxRunners int `json:"maxRunners,omitempty" yaml:"maxRunners,omitempty"`
}
SelfHostedRunnerPolicy defines policy for self-hosted runners.
type SemverParser ¶
type SemverParser struct{}
func NewSemverParser ¶
func NewSemverParser() SemverParser
type SensitiveChange ¶
type SensitiveChange struct {
Repository string `json:"repository"`
Category string `json:"category"` // settings, branch_protection, permissions
Operation string `json:"operation"` // update, create, delete
Field string `json:"field"` // specific field being changed
OldValue interface{} `json:"old_value"`
NewValue interface{} `json:"new_value"`
Risk RiskLevel `json:"risk"`
Description string `json:"description"`
Impact string `json:"impact"`
}
SensitiveChange represents a potentially sensitive configuration change.
type SeverityThreshold ¶
type SeverityThreshold struct {
AutoApprove bool `json:"auto_approve"`
RequireManualReview bool `json:"require_manual_review"`
MaxResponseTime time.Duration `json:"max_response_time"`
RequiredApprovers int `json:"required_approvers"`
NotifyImmediately bool `json:"notify_immediately"`
EscalateAfter time.Duration `json:"escalate_after,omitempty"`
BusinessImpactAnalysis bool `json:"business_impact_analysis"`
}
SeverityThreshold defines response requirements for a severity level.
type SeverityThresholdConfig ¶
type SeverityThresholdConfig struct {
Critical SeverityThreshold `json:"critical"`
High SeverityThreshold `json:"high"`
Medium SeverityThreshold `json:"medium"`
Low SeverityThreshold `json:"low"`
}
SeverityThresholdConfig defines how to handle different severity levels.
type SimpleCloneService ¶
type SimpleCloneService struct{}
SimpleCloneService provides a minimal implementation of CloneService
func (*SimpleCloneService) CloneOrganization ¶
func (s *SimpleCloneService) CloneOrganization(ctx context.Context, orgName, targetPath, strategy string) error
func (*SimpleCloneService) CloneRepository ¶
func (s *SimpleCloneService) CloneRepository(ctx context.Context, repo RepositoryInfo, targetPath, strategy string) error
func (*SimpleCloneService) GetSupportedStrategies ¶
func (s *SimpleCloneService) GetSupportedStrategies(ctx context.Context) ([]string, error)
func (*SimpleCloneService) RefreshAll ¶
func (s *SimpleCloneService) RefreshAll(ctx context.Context, targetPath, orgName, strategy string) error
func (*SimpleCloneService) SetStrategy ¶
func (s *SimpleCloneService) SetStrategy(ctx context.Context, strategy string) error
type StepAuditInfo ¶
type StepAuditInfo struct {
Name string `json:"name,omitempty"`
Uses string `json:"uses,omitempty"`
Run string `json:"run,omitempty"`
ActionVersion string `json:"action_version,omitempty"`
SecurityRisk SecurityRiskLevel `json:"security_risk"`
RiskReasons []string `json:"risk_reasons,omitempty"`
UsesSecrets []string `json:"uses_secrets,omitempty"`
UsesVariables []string `json:"uses_variables,omitempty"`
}
StepAuditInfo represents audit information for a step within a job.
type StreamMetadata ¶
type StreamMetadata struct {
Page int
TotalPages int
ProcessedAt time.Time
MemoryUsage int64
CacheHit bool
RetryAttempt int
}
StreamMetadata contains stream processing metadata.
type StreamingClient ¶
type StreamingClient struct {
// contains filtered or unexported fields
}
StreamingClient provides streaming API access for large-scale operations.
func NewStreamingClient ¶
func NewStreamingClient(token string, config StreamingConfig) *StreamingClient
NewStreamingClient creates a new streaming GitHub API client.
func (*StreamingClient) GetMetrics ¶
func (sc *StreamingClient) GetMetrics() RequestMetrics
GetMetrics returns current API usage metrics.
func (*StreamingClient) StreamOrganizationRepositories ¶
func (sc *StreamingClient) StreamOrganizationRepositories(ctx context.Context, org string, config StreamingConfig) (<-chan RepositoryStream, error)
StreamOrganizationRepositories streams repositories for an organization with memory optimization.
type StreamingConfig ¶
type StreamingConfig struct {
PageSize int
MaxConcurrency int
BufferSize int
MemoryLimit int64 // in bytes
CacheEnabled bool
CacheTTL time.Duration
RetryAttempts int
RetryDelay time.Duration
RateLimitBuffer int // requests to keep in reserve
}
StreamingConfig configures streaming behavior.
func DefaultStreamingConfig ¶
func DefaultStreamingConfig() StreamingConfig
DefaultStreamingConfig returns optimized defaults for large-scale operations.
type StreamingRateLimiter ¶
type StreamingRateLimiter struct{}
StreamingRateLimiter manages API rate limiting for streaming.
type StreamingRepository ¶
type StreamingRepository struct {
ID int64 `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
DefaultBranch string `json:"default_branch"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Size int `json:"size"`
Language string `json:"language,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
StreamingRepository represents a GitHub repository with optimized memory layout for streaming.
type SyncCloneStats ¶
type SyncCloneStats struct {
TotalRepositories int
StartTime time.Time
EndTime time.Time
SuccessCount int
FailureCount int
Successful int
Failed int
}
SyncCloneStats represents statistics from sync clone operations.
type SyncResult ¶
type SyncResult struct {
Organization string `json:"organization"`
TotalRepositories int `json:"total_repositories"`
SyncedRepositories int `json:"synced_repositories"`
Discrepancies []WebhookDiscrepancy `json:"discrepancies"`
ExecutionTime string `json:"execution_time"`
}
SyncResult represents the result of synchronizing webhooks.
type TeamPermission ¶
type TeamPermission struct {
ID int64 `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Permission string `json:"permission"`
}
TeamPermission represents a team's permission on a repository.
type TemplateExample ¶
type TemplateExample struct {
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Variables map[string]interface{} `json:"variables" yaml:"variables"`
}
TemplateExample provides example configurations for a template.
type TemplateStorage ¶
type TemplateStorage interface {
CreateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
GetTemplate(ctx context.Context, templateID string) (*AutomationRuleTemplate, error)
ListTemplates(ctx context.Context, category string) ([]*AutomationRuleTemplate, error)
UpdateTemplate(ctx context.Context, template *AutomationRuleTemplate) error
DeleteTemplate(ctx context.Context, templateID string) error
}
TemplateStorage defines the interface for persisting rule templates.
type TemplateVariable ¶
type TemplateVariable struct {
Name string `json:"name" yaml:"name"`
Type string `json:"type" yaml:"type"` // string, number, boolean, array, object
Description string `json:"description" yaml:"description"`
Required bool `json:"required" yaml:"required"`
DefaultValue interface{} `json:"defaultValue,omitempty" yaml:"defaultValue,omitempty"`
Options []string `json:"options,omitempty" yaml:"options,omitempty"`
Validation string `json:"validation,omitempty" yaml:"validation,omitempty"` // Regex or validation rule
}
TemplateVariable defines a variable that can be customized in a template.
type TestDataRequirements ¶
type TestDataRequirements struct {
DataSets []string `json:"data_sets"`
SyntheticData bool `json:"synthetic_data"`
ProductionData bool `json:"production_data"`
DataMasking bool `json:"data_masking"`
DataRetention time.Duration `json:"data_retention"`
PrivacyCompliance bool `json:"privacy_compliance"`
}
type TestEnvironment ¶
type TestResults ¶
type TestResults struct {
Passed bool `json:"passed"`
TestSuite string `json:"test_suite"`
Coverage float64 `json:"coverage,omitempty"`
Duration time.Duration `json:"duration"`
FailedTests []string `json:"failed_tests,omitempty"`
ExecutedAt time.Time `json:"executed_at"`
}
TestResults represents test results for a security update.
type TestSuiteConfiguration ¶
type TestSuiteConfiguration struct {
DefaultSuites []string `json:"default_suites"`
EcosystemSpecific map[string][]string `json:"ecosystem_specific"`
CustomSuites []CustomTestSuite `json:"custom_suites"`
}
type TestingRecommendation ¶
type TestingRequirements ¶
type TestingRequirements struct {
Enabled bool `json:"enabled"`
UnitTestingRequired bool `json:"unitTestingRequired"`
IntegrationTestingRequired bool `json:"integrationTestingRequired"`
E2ETestingRequired bool `json:"e2eTestingRequired"`
PerformanceTestingRequired bool `json:"performanceTestingRequired"`
SecurityTestingRequired bool `json:"securityTestingRequired"`
MinimumTestCoverage float64 `json:"minimumTestCoverage"`
TestSuiteConfiguration TestSuiteConfiguration `json:"testSuiteConfiguration"`
AutomatedTesting AutomatedTestingConfig `json:"automatedTesting"`
ManualTestingChecklist []ManualTestingItem `json:"manual_testing_checklist"`
TestEnvironments []TestEnvironment `json:"test_environments"`
TestDataRequirements TestDataRequirements `json:"test_data_requirements"`
}
TestingRequirements defines testing requirements for version updates.
type ThresholdConfig ¶
type TimeEvaluationExplanation ¶
type TimeEvaluationExplanation struct {
EventTime time.Time `json:"eventTime"`
DayOfWeek int `json:"dayOfWeek"`
HourOfDay int `json:"hourOfDay"`
BusinessHours bool `json:"businessHours"`
TimeZone string `json:"timeZone"`
Result bool `json:"result"`
Reason string `json:"reason"`
}
TimeEvaluationExplanation explains time-based condition evaluation.
type TimelinePhase ¶
type TokenAwareGitHubClient ¶
type TokenAwareGitHubClient struct {
// contains filtered or unexported fields
}
TokenAwareGitHubClient provides GitHub API operations with automatic token expiration handling - DISABLED (recovery package removed) Simple HTTP client implementation to replace deleted recovery package.
func NewTokenAwareGitHubClient ¶
func NewTokenAwareGitHubClient(config TokenAwareGitHubClientConfig) (*TokenAwareGitHubClient, error)
NewTokenAwareGitHubClient creates a new token-aware GitHub client - DISABLED (recovery package removed) Simple HTTP client implementation to replace deleted recovery package.
func (*TokenAwareGitHubClient) GetCurrentToken ¶
func (c *TokenAwareGitHubClient) GetCurrentToken() (string, error)
GetCurrentToken returns the current valid token - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*TokenAwareGitHubClient) GetDefaultBranch ¶
func (c *TokenAwareGitHubClient) GetDefaultBranch(ctx context.Context, owner, repo string) (string, error)
GetDefaultBranch retrieves the default branch for a repository.
func (*TokenAwareGitHubClient) GetOrganization ¶
func (c *TokenAwareGitHubClient) GetOrganization(ctx context.Context, org string) (*GitHubOrganization, error)
GetOrganization retrieves organization information.
func (*TokenAwareGitHubClient) GetRateLimit ¶
func (c *TokenAwareGitHubClient) GetRateLimit(ctx context.Context) (*RateLimitInfo, error)
GetRateLimit retrieves current rate limit information.
func (*TokenAwareGitHubClient) GetRepository ¶
func (c *TokenAwareGitHubClient) GetRepository(ctx context.Context, owner, repo string) (*GitHubRepository, error)
GetRepository retrieves specific repository information.
func (*TokenAwareGitHubClient) GetTokenStatus ¶
func (c *TokenAwareGitHubClient) GetTokenStatus() (map[string]interface{}, error)
GetTokenStatus returns detailed token status information - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*TokenAwareGitHubClient) GetUser ¶
func (c *TokenAwareGitHubClient) GetUser(ctx context.Context) (*GitHubUser, error)
GetUser retrieves the authenticated user information - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*TokenAwareGitHubClient) ListRepositories ¶
func (c *TokenAwareGitHubClient) ListRepositories(ctx context.Context, owner string, page, perPage int) ([]*GitHubRepository, error)
ListRepositories retrieves repositories for a user or organization.
func (*TokenAwareGitHubClient) RefreshToken ¶
func (c *TokenAwareGitHubClient) RefreshToken(ctx context.Context) error
RefreshToken manually refreshes the GitHub token - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*TokenAwareGitHubClient) Start ¶
func (c *TokenAwareGitHubClient) Start(ctx context.Context) error
Start initializes the token expiration monitoring - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*TokenAwareGitHubClient) Stop ¶
func (c *TokenAwareGitHubClient) Stop()
Stop shuts down the token expiration monitoring - DISABLED (recovery package removed) Simple implementation without external recovery dependency.
func (*TokenAwareGitHubClient) ValidateTokenPermissions ¶
func (c *TokenAwareGitHubClient) ValidateTokenPermissions(ctx context.Context, requiredScopes []string) error
ValidateTokenPermissions validates token permissions for specific operations.
type TokenAwareGitHubClientConfig ¶
type TokenAwareGitHubClientConfig struct {
BaseURL string
PrimaryToken string
FallbackTokens []string
// HTTP client configuration
Timeout time.Duration
}
TokenAwareGitHubClientConfig configures the token-aware GitHub client - DISABLED (recovery package removed) Simple configuration struct without external recovery dependency.
func DefaultTokenAwareGitHubClientConfig ¶
func DefaultTokenAwareGitHubClientConfig() TokenAwareGitHubClientConfig
DefaultTokenAwareGitHubClientConfig returns sensible defaults - DISABLED (recovery package removed) Simple configuration without external recovery dependency.
type TokenInfo ¶
type TokenInfo struct {
User *User `json:"user"`
Scopes []string `json:"scopes"`
TokenType string `json:"token_type"` // classic, fine_grained
RateLimit *RateLimitInfo `json:"rate_limit"`
Permissions map[string]PermissionLevel `json:"permissions"`
ValidatedAt time.Time `json:"validated_at"`
}
TokenInfo contains information about the current token.
type TokenInfoRecord ¶
type TokenInfoRecord struct {
Valid bool `json:"valid"`
Scopes []string `json:"scopes"`
RateLimit RateLimit `json:"rate_limit"`
User string `json:"user"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
Permissions []string `json:"permissions"`
}
TokenInfoRecord represents information about a GitHub token.
type TokenRateLimitInfo ¶
type TokenRateLimitInfo struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Reset time.Time `json:"reset"`
Used int `json:"used"`
}
TokenRateLimitInfo represents GitHub rate limit information for token-aware client.
type TokenValidator ¶
type TokenValidator struct {
// contains filtered or unexported fields
}
TokenValidator validates GitHub token permissions.
func NewTokenValidator ¶
func NewTokenValidator(client *RepoConfigClient) *TokenValidator
NewTokenValidator creates a new token validator.
func (*TokenValidator) GetPermissionHelp ¶
func (tv *TokenValidator) GetPermissionHelp() map[string]string
GetPermissionHelp returns help text for permissions.
func (*TokenValidator) ValidateForOperation ¶
func (tv *TokenValidator) ValidateForOperation(ctx context.Context, operation string) (*ValidationResult, error)
ValidateForOperation validates token permissions for a specific operation.
func (*TokenValidator) ValidateForRepository ¶
func (tv *TokenValidator) ValidateForRepository(ctx context.Context, owner, repo string, operation string) (*ValidationResult, error)
ValidateForRepository validates permissions for a specific repository.
func (*TokenValidator) ValidateToken ¶
func (tv *TokenValidator) ValidateToken(ctx context.Context) (*ValidationResult, error)
ValidateToken validates the current token and its permissions.
type TokenValidatorInterface ¶
type TokenValidatorInterface interface {
ValidateToken(ctx context.Context, token string) (*TokenInfoRecord, error)
ValidateForOperation(ctx context.Context, token, operation string) error
ValidateForRepository(ctx context.Context, token, owner, repo string) error
GetRequiredScopes(ctx context.Context, operation string) ([]string, error)
}
TokenValidatorInterface defines the interface for GitHub token validation.
func NewGitHubTokenValidator ¶
func NewGitHubTokenValidator(apiClient APIClient, logger Logger) TokenValidatorInterface
NewGitHubTokenValidator creates a new token validator with dependencies.
type TrendData ¶
type TrendData struct {
Direction TrendDirection `json:"direction"`
ChangeRate float64 `json:"change_rate"`
DataPoints []DataPoint `json:"data_points"`
Forecast *TrendForecast `json:"forecast,omitempty"`
}
TrendData represents trend information over time.
type TrendDirection ¶
type TrendDirection string
const ( TrendDirectionImproving TrendDirection = "improving" TrendDirectionStable TrendDirection = "stable" TrendDirectionDeclining TrendDirection = "declining" TrendDirectionUnknown TrendDirection = "unknown" )
type TrendForecast ¶
type TrendForecast struct {
ProjectedValue float64 `json:"projected_value"`
Confidence float64 `json:"confidence"`
ProjectionDate time.Time `json:"projection_date"`
Methodology string `json:"methodology"`
}
TrendForecast provides forecasting for trends.
type UpdateFrequency ¶
type UpdateFrequency string
const ( UpdateFrequencyImmediate UpdateFrequency = "immediate" UpdateFrequencyDaily UpdateFrequency = "daily" UpdateFrequencyWeekly UpdateFrequency = "weekly" UpdateFrequencyBiWeekly UpdateFrequency = "bi_weekly" UpdateFrequencyMonthly UpdateFrequency = "monthly" UpdateFrequencyQuarterly UpdateFrequency = "quarterly" UpdateFrequencyManual UpdateFrequency = "manual" )
type UpdatePriority ¶
type UpdatePriority string
const ( UpdatePriorityCritical UpdatePriority = "critical" UpdatePriorityHigh UpdatePriority = "high" UpdatePriorityMedium UpdatePriority = "medium" UpdatePriorityLow UpdatePriority = "low" )
type UpdateStatus ¶
type UpdateStatus string
const ( UpdateStatusPending UpdateStatus = "pending" UpdateStatusReviewing UpdateStatus = "reviewing" UpdateStatusApproved UpdateStatus = "approved" UpdateStatusRejected UpdateStatus = "rejected" UpdateStatusTesting UpdateStatus = "testing" UpdateStatusDeploying UpdateStatus = "deploying" UpdateStatusCompleted UpdateStatus = "completed" UpdateStatusFailed UpdateStatus = "failed" UpdateStatusCancelled UpdateStatus = "cancelled" )
type UpdateTimeline ¶
type UpdateTimeline struct {
EstimatedDuration time.Duration `json:"estimated_duration"`
Phases []TimelinePhase `json:"phases"`
Dependencies []string `json:"dependencies,omitempty"`
Blockers []string `json:"blockers,omitempty"`
}
type User ¶
type User struct {
Login string `json:"login"`
ID int64 `json:"id"`
Type string `json:"type"` // User, Organization
SiteAdmin bool `json:"site_admin"`
}
User represents GitHub user information.
type UserInfo ¶
type UserInfo struct {
Login string `json:"login"`
Name string `json:"name"`
Email string `json:"email"`
Type string `json:"type"`
SiteAdmin bool `json:"siteAdmin"`
Company string `json:"company"`
Location string `json:"location"`
}
UserInfo contains information about a GitHub user.
type UserPermission ¶
type UserPermission struct {
Login string `json:"login"`
ID int64 `json:"id"`
Permission string `json:"permission"`
}
UserPermission represents a user's permission on a repository.
type UserTeamRestrictions ¶
UserTeamRestrictions represents user/team restrictions.
type ValidationConfig ¶
type ValidationConfig struct {
RequiredEvents []string `json:"required_events,omitempty" yaml:"required_events,omitempty"`
ForbiddenEvents []string `json:"forbidden_events,omitempty" yaml:"forbidden_events,omitempty"`
AllowedDomains []string `json:"allowed_domains,omitempty" yaml:"allowed_domains,omitempty"`
ForbiddenDomains []string `json:"forbidden_domains,omitempty" yaml:"forbidden_domains,omitempty"`
RequireSSL bool `json:"require_ssl" yaml:"require_ssl"`
RequireSecret bool `json:"require_secret" yaml:"require_secret"`
}
ValidationConfig defines validation rules.
type ValidationResult ¶
type ValidationResult struct {
Valid bool `json:"valid"`
TokenInfo *TokenInfo `json:"token_info"`
MissingPerms []RequiredPermission `json:"missing_permissions"`
Warnings []string `json:"warnings"`
Recommendations []string `json:"recommendations"`
ValidatedAt time.Time `json:"validated_at"`
}
ValidationResult represents the result of token validation.
type ValidatorRateLimitInfo ¶
type ValidatorRateLimitInfo struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Reset time.Time `json:"reset"`
Used int `json:"used"`
}
ValidatorRateLimitInfo contains rate limit information for token validator.
type VendorInfo ¶
type VendorInfo struct {
Name string `json:"name"`
Products []ProductInfo `json:"products"`
}
VendorInfo represents vendor information in CVE records.
type VersionApprovalRule ¶
type VersionApprovalRule struct {
RequiredApprovers int `json:"requiredApprovers"`
RequiredApprovalTeams []string `json:"requiredApprovalTeams"`
AutoApprovalConditions []AutoApprovalCondition `json:"autoApprovalConditions"`
ManualReviewRequired bool `json:"manualReviewRequired"`
SecurityReviewRequired bool `json:"securityReviewRequired"`
ArchitectureReviewRequired bool `json:"architectureReviewRequired"`
BusinessApprovalRequired bool `json:"businessApprovalRequired"`
TestingGateRequired bool `json:"testingGateRequired"`
WaitingPeriod time.Duration `json:"waitingPeriod,omitempty"`
ApprovalTimeLimit time.Duration `json:"approvalTimeLimit,omitempty"`
EscalationRules []ApprovalEscalationRule `json:"escalationRules"`
}
VersionApprovalRule defines approval rules for version updates.
type VersionConstraintApplicationResult ¶
type VersionConstraintApplicationResult struct {
PolicyID string `json:"policy_id"`
TotalUpdates int `json:"total_updates"`
ApprovedUpdates []DependencyUpdate `json:"approved_updates"`
RejectedUpdates []DependencyUpdateRejection `json:"rejected_updates"`
PendingReview []DependencyUpdate `json:"pending_review"`
ApprovedCount int `json:"approved_count"`
RejectedCount int `json:"rejected_count"`
PendingReviewCount int `json:"pending_review_count"`
ProcessedAt time.Time `json:"processed_at"`
}
type VersionConstraintCheckResult ¶
type VersionConstraintCheckResult struct {
DependencyName string `json:"dependency_name"`
ProposedVersion string `json:"proposed_version"`
Ecosystem string `json:"ecosystem"`
Allowed bool `json:"allowed"`
ViolatedConstraints []string `json:"violated_constraints"`
AppliedRules []string `json:"applied_rules"`
CheckedAt time.Time `json:"checked_at"`
}
Supporting types for analysis results.
type VersionConstraintEngine ¶
type VersionConstraintEngine struct {
// contains filtered or unexported fields
}
VersionConstraintEngine handles version constraint evaluation and resolution.
func NewVersionConstraintEngine ¶
func NewVersionConstraintEngine(logger Logger) *VersionConstraintEngine
NewVersionConstraintEngine creates a new version constraint engine.
type VersionConstraintException ¶
type VersionConstraintException struct {
Repository string `json:"repository"`
Justification string `json:"justification"`
ExpiresAt time.Time `json:"expires_at"`
Approver string `json:"approver"`
}
Supporting structs for complex configurations.
type VersionConstraintRule ¶
type VersionConstraintRule struct {
RuleID string `json:"ruleId"`
DependencyPattern string `json:"dependencyPattern"`
Ecosystem string `json:"ecosystem"`
AllowedVersions []VersionRange `json:"allowedVersions"`
BlockedVersions []VersionRange `json:"blockedVersions"`
PreferredVersions []VersionRange `json:"preferredVersions"`
MinimumVersion string `json:"minimumVersion,omitempty"`
MaximumVersion string `json:"maximumVersion,omitempty"`
VersionPattern string `json:"versionPattern,omitempty"`
AllowPrerelease bool `json:"allowPrerelease"`
AllowBetaVersions bool `json:"allowBetaVersions"`
UpdateStrategy DependencyUpdateStrategy `json:"updateStrategy"`
AutoUpdateEnabled bool `json:"autoUpdateEnabled"`
UpdateFrequency UpdateFrequency `json:"updateFrequency"`
Priority ConstraintPriority `json:"priority"`
ExpirationDate *time.Time `json:"expirationDate,omitempty"`
Justification string `json:"justification"`
Exceptions []VersionConstraintException `json:"exceptions,omitempty"`
}
VersionConstraintRule defines version constraints for dependencies.
type VersionPolicyNotificationConfig ¶
type VersionPolicyNotificationConfig struct {
Enabled bool `json:"enabled"`
Channels []VersionNotificationChannel `json:"channels"`
EventTypes []string `json:"event_types"`
NotificationTemplate string `json:"notification_template"`
Frequency string `json:"frequency"`
Recipients []NotificationRecipient `json:"recipients"`
}
type VersionRange ¶
type VersionRange struct {
Introduced string `json:"introduced,omitempty"`
Fixed string `json:"fixed,omitempty"`
LastAffected string `json:"last_affected,omitempty"`
}
VersionRange represents a range of affected versions.
type VersionUpdateApprovalRequirements ¶
type VersionUpdateApprovalRequirements struct {
MajorVersionUpdates VersionApprovalRule `json:"majorVersionUpdates"`
MinorVersionUpdates VersionApprovalRule `json:"minorVersionUpdates"`
PatchVersionUpdates VersionApprovalRule `json:"patchVersionUpdates"`
SecurityUpdates VersionApprovalRule `json:"securityUpdates"`
PreReleaseUpdates VersionApprovalRule `json:"preReleaseUpdates"`
EmergencyUpdates EmergencyApprovalRule `json:"emergencyUpdates"`
BulkUpdates BulkUpdateApprovalRule `json:"bulkUpdates"`
DependencySpecific map[string]VersionApprovalRule `json:"dependencySpecific,omitempty"`
}
VersionUpdateApprovalRequirements defines approval requirements for version updates.
type ViolationStatistics ¶
type ViolationStatistics struct {
ViolationType PolicyViolationType `json:"violation_type"`
Count int `json:"count"`
Percentage float64 `json:"percentage"`
Repositories []string `json:"repositories"`
Severity string `json:"severity"`
}
ViolationStatistics provides statistics about policy violations.
type VulnerabilityDatabase ¶
type VulnerabilityDatabase struct {
// contains filtered or unexported fields
}
VulnerabilityDatabase manages vulnerability data and CVE information.
func NewVulnerabilityDatabase ¶
func NewVulnerabilityDatabase() *VulnerabilityDatabase
NewVulnerabilityDatabase creates a new vulnerability database.
type VulnerabilityExclusion ¶
type VulnerabilityExclusion struct {
ID string `json:"id"`
Type ExclusionType `json:"type"`
Pattern string `json:"pattern"`
Reason string `json:"reason"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Approver string `json:"approver"`
CreatedAt time.Time `json:"created_at"`
}
VulnerabilityExclusion defines vulnerabilities to exclude from policies.
type VulnerabilityRecord ¶
type VulnerabilityRecord struct {
ID string `json:"id"`
CVE string `json:"cve,omitempty"`
Title string `json:"title"`
Description string `json:"description"`
Severity VulnerabilitySeverity `json:"severity"`
CVSS CVSSScore `json:"cvss"`
Package PackageInfo `json:"package"`
AffectedVersions []VersionRange `json:"affected_versions"`
PatchedVersions []string `json:"patched_versions"`
References []Reference `json:"references"`
PublishedAt time.Time `json:"published_at"`
UpdatedAt time.Time `json:"updated_at"`
WithdrawnAt *time.Time `json:"withdrawn_at,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
VulnerabilityRecord represents a vulnerability in the database.
type VulnerabilitySeverity ¶
type VulnerabilitySeverity string
Enum types.
const ( VulnSeverityCritical VulnerabilitySeverity = "critical" VulnSeverityHigh VulnerabilitySeverity = "high" VulnSeverityMedium VulnerabilitySeverity = "medium" VulnSeverityLow VulnerabilitySeverity = "low" VulnSeverityInfo VulnerabilitySeverity = "info" )
type WebhookAction ¶
type WebhookAction string
WebhookAction defines what action to take.
const ( WebhookActionCreate WebhookAction = "create" WebhookActionUpdate WebhookAction = "update" WebhookActionDelete WebhookAction = "delete" WebhookActionEnsure WebhookAction = "ensure" // create if not exists, update if exists )
type WebhookAlert ¶
type WebhookAlert struct {
ID string `json:"id"`
WebhookID string `json:"webhook_id"`
Type WebhookAlertType `json:"type"`
Severity WebhookAlertSeverity `json:"severity"`
Message string `json:"message"`
CreatedAt time.Time `json:"created_at"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
Acknowledged bool `json:"acknowledged"`
Details map[string]interface{} `json:"details,omitempty"`
}
WebhookAlert represents an alert for a webhook.
type WebhookAlertSeverity ¶
type WebhookAlertSeverity string
WebhookAlertSeverity defines severity levels for alerts.
const ( AlertSeverityInfo WebhookAlertSeverity = "info" AlertSeverityWarning WebhookAlertSeverity = "warning" AlertSeverityError WebhookAlertSeverity = "error" AlertSeverityCritical WebhookAlertSeverity = "critical" )
type WebhookAlertType ¶
type WebhookAlertType string
WebhookAlertType defines types of webhook alerts.
const ( AlertTypeHighErrorRate WebhookAlertType = "high_error_rate" AlertTypeSlowResponse WebhookAlertType = "slow_response" AlertTypeConsecutiveFailures WebhookAlertType = "consecutive_failures" AlertTypeConfigurationIssue WebhookAlertType = "configuration_issue" AlertTypeDeliveryFailure WebhookAlertType = "delivery_failure" AlertTypeEndpointDown WebhookAlertType = "endpoint_down" )
type WebhookConditions ¶
type WebhookConditions struct {
RepositoryName []string `json:"repository_name,omitempty" yaml:"repository_name,omitempty"`
RepositoryPattern []string `json:"repository_pattern,omitempty" yaml:"repository_pattern,omitempty"`
Language []string `json:"language,omitempty" yaml:"language,omitempty"`
Topics []string `json:"topics,omitempty" yaml:"topics,omitempty"`
Visibility []string `json:"visibility,omitempty" yaml:"visibility,omitempty"` // public, private, internal
IsArchived *bool `json:"is_archived,omitempty" yaml:"is_archived,omitempty"`
IsTemplate *bool `json:"is_template,omitempty" yaml:"is_template,omitempty"`
HasIssues *bool `json:"has_issues,omitempty" yaml:"has_issues,omitempty"`
CustomFields map[string]string `json:"custom_fields,omitempty" yaml:"custom_fields,omitempty"`
}
WebhookConditions defines when a rule should be applied.
type WebhookConfig ¶
type WebhookConfig struct {
URL string `json:"url"`
ContentType string `json:"content_type"`
Secret string `json:"secret,omitempty"`
InsecureSSL bool `json:"insecure_ssl"`
}
WebhookConfig represents webhook configuration settings.
type WebhookConfigTemplate ¶
type WebhookConfigTemplate struct {
URL string `json:"url" yaml:"url"`
ContentType string `json:"content_type" yaml:"content_type"`
Secret string `json:"secret,omitempty" yaml:"secret,omitempty"`
InsecureSSL bool `json:"insecure_ssl" yaml:"insecure_ssl"`
}
WebhookConfigTemplate extends WebhookConfig with template support.
type WebhookConfigurationService ¶
type WebhookConfigurationService interface {
// Policy Management
CreatePolicy(ctx context.Context, policy *WebhookPolicy) error
GetPolicy(ctx context.Context, org, policyID string) (*WebhookPolicy, error)
ListPolicies(ctx context.Context, org string) ([]*WebhookPolicy, error)
UpdatePolicy(ctx context.Context, policy *WebhookPolicy) error
DeletePolicy(ctx context.Context, org, policyID string) error
// Configuration Management
GetOrganizationConfig(ctx context.Context, org string) (*OrganizationWebhookConfig, error)
UpdateOrganizationConfig(ctx context.Context, config *OrganizationWebhookConfig) error
ValidateConfiguration(ctx context.Context, config *OrganizationWebhookConfig) (*WebhookValidationResult, error)
// Policy Application
ApplyPolicies(ctx context.Context, request *ApplyPoliciesRequest) (*ApplyPoliciesResult, error)
PreviewPolicyApplication(ctx context.Context, request *ApplyPoliciesRequest) (*PolicyApplicationPreview, error)
// Migration and Sync
MigrateExistingWebhooks(ctx context.Context, request *MigrationRequest) (*MigrationResult, error)
SyncOrganizationWebhooks(ctx context.Context, org string) (*SyncResult, error)
// Reporting and Audit
GenerateComplianceReport(ctx context.Context, org string) (*ComplianceReport, error)
GetWebhookInventory(ctx context.Context, org string) (*WebhookInventory, error)
}
WebhookConfigurationService provides organization-wide webhook configuration management.
func NewWebhookConfigurationService ¶
func NewWebhookConfigurationService(webhookService WebhookService, apiClient APIClient, logger Logger, storage ConfigStorage) WebhookConfigurationService
NewWebhookConfigurationService creates a new webhook configuration service.
type WebhookCreateRequest ¶
type WebhookCreateRequest struct {
Name string `json:"name"`
URL string `json:"url"`
Events []string `json:"events"`
Active bool `json:"active"`
Config WebhookConfig `json:"config"`
}
WebhookCreateRequest represents a request to create a new webhook.
type WebhookDefaults ¶
type WebhookDefaults struct {
Events []string `json:"events" yaml:"events"`
Active bool `json:"active" yaml:"active"`
Config WebhookConfigTemplate `json:"config" yaml:"config"`
Variables map[string]string `json:"variables,omitempty" yaml:"variables,omitempty"`
}
WebhookDefaults defines default webhook settings.
type WebhookDelivery ¶
type WebhookDelivery struct {
ID string `json:"id"`
Event string `json:"event"`
Action string `json:"action"`
StatusCode int `json:"status_code"`
Duration string `json:"duration"`
DeliveredAt time.Time `json:"delivered_at"`
Success bool `json:"success"`
Redelivered bool `json:"redelivered"`
URL string `json:"url"`
}
WebhookDelivery represents a webhook delivery record.
type WebhookDiscrepancy ¶
type WebhookDiscrepancy struct {
Repository string `json:"repository"`
WebhookID int64 `json:"webhook_id"`
DiscrepancyType string `json:"discrepancy_type"`
Expected string `json:"expected"`
Actual string `json:"actual"`
Severity string `json:"severity"`
}
WebhookDiscrepancy represents a difference between expected and actual webhook configuration.
type WebhookHealthCheck ¶
type WebhookHealthCheck struct {
Timestamp time.Time `json:"timestamp"`
Status WebhookHealthStatus `json:"status"`
ResponseTime time.Duration `json:"response_time"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
Details map[string]interface{} `json:"details,omitempty"`
}
WebhookHealthCheck represents a health check result.
type WebhookHealthStatus ¶
type WebhookHealthStatus string
WebhookHealthStatus represents the health status of a webhook.
const ( WebhookStatusHealthy WebhookHealthStatus = "healthy" WebhookStatusDegraded WebhookHealthStatus = "degraded" WebhookStatusUnhealthy WebhookHealthStatus = "unhealthy" WebhookStatusUnknown WebhookHealthStatus = "unknown" WebhookStatusDisabled WebhookHealthStatus = "disabled" )
type WebhookInfo ¶
type WebhookInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Events []string `json:"events"`
Active bool `json:"active"`
Config WebhookConfig `json:"config"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Repository string `json:"repository,omitempty"`
Organization string `json:"organization,omitempty"`
}
WebhookInfo represents a GitHub webhook configuration.
type WebhookInventory ¶
type WebhookInventory struct {
Organization string `json:"organization"`
GeneratedAt time.Time `json:"generated_at"`
TotalWebhooks int `json:"total_webhooks"`
WebhooksByType map[string]int `json:"webhooks_by_type"`
WebhooksByEvent map[string]int `json:"webhooks_by_event"`
Repositories []RepositoryWebhookInfo `json:"repositories"`
Summary WebhookInventorySummary `json:"summary"`
}
WebhookInventory represents an inventory of all webhooks in an organization.
type WebhookInventorySummary ¶
type WebhookInventorySummary struct {
ActiveWebhooks int `json:"active_webhooks"`
InactiveWebhooks int `json:"inactive_webhooks"`
DuplicateWebhooks int `json:"duplicate_webhooks"`
OrphanedWebhooks int `json:"orphaned_webhooks"`
HealthScore float64 `json:"health_score"`
}
WebhookInventorySummary provides summary statistics.
type WebhookListOptions ¶
type WebhookListOptions struct {
Organization string `json:"organization,omitempty"`
Repository string `json:"repository,omitempty"`
Page int `json:"page"`
PerPage int `json:"per_page"`
}
WebhookListOptions represents options for listing webhooks.
type WebhookMetrics ¶
type WebhookMetrics struct {
TotalWebhooks int64 `json:"total_webhooks"`
ActiveWebhooks int64 `json:"active_webhooks"`
HealthyWebhooks int64 `json:"healthy_webhooks"`
UnhealthyWebhooks int64 `json:"unhealthy_webhooks"`
TotalDeliveries int64 `json:"total_deliveries"`
SuccessfulDeliveries int64 `json:"successful_deliveries"`
FailedDeliveries int64 `json:"failed_deliveries"`
AverageResponseTime time.Duration `json:"average_response_time"`
ActiveAlerts int64 `json:"active_alerts"`
StatusDistribution map[WebhookHealthStatus]int64 `json:"status_distribution"`
OrganizationMetrics map[string]*OrganizationMetrics `json:"organization_metrics"`
LastUpdated time.Time `json:"last_updated"`
// contains filtered or unexported fields
}
WebhookMetrics holds global webhook metrics.
type WebhookMigrationResult ¶
type WebhookMigrationResult struct {
Repository string `json:"repository"`
OldWebhookID int64 `json:"old_webhook_id"`
NewWebhookID int64 `json:"new_webhook_id,omitempty"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Changes []string `json:"changes"`
}
WebhookMigrationResult represents the result for a single webhook migration.
type WebhookMonitor ¶
type WebhookMonitor struct {
// contains filtered or unexported fields
}
WebhookMonitor monitors webhook status and health.
func NewWebhookMonitor ¶
func NewWebhookMonitor(logger Logger, apiClient APIClient, config *WebhookMonitorConfig) *WebhookMonitor
NewWebhookMonitor creates a new webhook monitor.
func (*WebhookMonitor) AcknowledgeAlert ¶
func (wm *WebhookMonitor) AcknowledgeAlert(alertID string) error
AcknowledgeAlert marks an alert as acknowledged.
func (*WebhookMonitor) AddWebhook ¶
func (wm *WebhookMonitor) AddWebhook(webhook *WebhookStatus)
AddWebhook adds a webhook to the monitor (for testing/demo purposes).
func (*WebhookMonitor) GetActiveAlerts ¶
func (wm *WebhookMonitor) GetActiveAlerts() []WebhookAlert
GetActiveAlerts returns all active alerts.
func (*WebhookMonitor) GetAllWebhookStatuses ¶
func (wm *WebhookMonitor) GetAllWebhookStatuses() map[string]*WebhookStatus
GetAllWebhookStatuses returns the status of all monitored webhooks.
func (*WebhookMonitor) GetMetrics ¶
func (wm *WebhookMonitor) GetMetrics() *WebhookMetrics
GetMetrics returns current webhook metrics.
func (*WebhookMonitor) GetWebhookStatus ¶
func (wm *WebhookMonitor) GetWebhookStatus(webhookID string) (*WebhookStatus, error)
GetWebhookStatus returns the status of a specific webhook.
type WebhookMonitorConfig ¶
type WebhookMonitorConfig struct {
CheckInterval time.Duration `json:"check_interval" yaml:"check_interval"`
HealthCheckTimeout time.Duration `json:"health_check_timeout" yaml:"health_check_timeout"`
RetentionPeriod time.Duration `json:"retention_period" yaml:"retention_period"`
AlertThresholds AlertThresholds `json:"alert_thresholds" yaml:"alert_thresholds"`
EnableNotifications bool `json:"enable_notifications" yaml:"enable_notifications"`
MaxHistorySize int `json:"max_history_size" yaml:"max_history_size"`
}
WebhookMonitorConfig holds configuration for webhook monitoring.
type WebhookOperationResult ¶
type WebhookOperationResult struct {
Repository string `json:"repository"`
Operation string `json:"operation"`
Success bool `json:"success"`
WebhookInfo *WebhookInfo `json:"webhook_info,omitempty"`
Error string `json:"error,omitempty"`
Duration string `json:"duration"`
}
WebhookOperationResult represents the result of a single webhook operation.
type WebhookPolicy ¶
type WebhookPolicy struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Organization string `json:"organization" yaml:"organization"`
Enabled bool `json:"enabled" yaml:"enabled"`
Priority int `json:"priority" yaml:"priority"` // Higher number = higher priority
Rules []WebhookPolicyRule `json:"rules" yaml:"rules"`
CreatedAt time.Time `json:"created_at" yaml:"created_at"`
UpdatedAt time.Time `json:"updated_at" yaml:"updated_at"`
CreatedBy string `json:"created_by" yaml:"created_by"`
Tags map[string]string `json:"tags,omitempty" yaml:"tags,omitempty"`
}
WebhookPolicy represents an organization-wide webhook policy.
type WebhookPolicyRule ¶
type WebhookPolicyRule struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Conditions WebhookConditions `json:"conditions" yaml:"conditions"`
Action WebhookAction `json:"action" yaml:"action"`
Template WebhookTemplate `json:"template" yaml:"template"`
Enabled bool `json:"enabled" yaml:"enabled"`
OnConflict ConflictResolution `json:"on_conflict" yaml:"on_conflict"`
}
WebhookPolicyRule defines a rule for applying webhooks.
type WebhookSelector ¶
type WebhookSelector struct {
ByName string `json:"by_name,omitempty"`
ByURL string `json:"by_url,omitempty"`
ByEvents []string `json:"by_events,omitempty"`
Active *bool `json:"active,omitempty"`
}
WebhookSelector defines how to select webhooks for bulk operations.
type WebhookService ¶
type WebhookService interface {
// Repository webhooks
CreateRepositoryWebhook(ctx context.Context, owner, repo string, request *WebhookCreateRequest) (*WebhookInfo, error)
GetRepositoryWebhook(ctx context.Context, owner, repo string, webhookID int64) (*WebhookInfo, error)
ListRepositoryWebhooks(ctx context.Context, owner, repo string, options *WebhookListOptions) ([]*WebhookInfo, error)
UpdateRepositoryWebhook(ctx context.Context, owner, repo string, request *WebhookUpdateRequest) (*WebhookInfo, error)
DeleteRepositoryWebhook(ctx context.Context, owner, repo string, webhookID int64) error
// Organization webhooks
CreateOrganizationWebhook(ctx context.Context, org string, request *WebhookCreateRequest) (*WebhookInfo, error)
GetOrganizationWebhook(ctx context.Context, org string, webhookID int64) (*WebhookInfo, error)
ListOrganizationWebhooks(ctx context.Context, org string, options *WebhookListOptions) ([]*WebhookInfo, error)
UpdateOrganizationWebhook(ctx context.Context, org string, request *WebhookUpdateRequest) (*WebhookInfo, error)
DeleteOrganizationWebhook(ctx context.Context, org string, webhookID int64) error
// Bulk operations
BulkCreateWebhooks(ctx context.Context, request *BulkWebhookRequest) (*BulkWebhookResult, error)
BulkUpdateWebhooks(ctx context.Context, request *BulkWebhookUpdateRequest) (*BulkWebhookResult, error)
BulkDeleteWebhooks(ctx context.Context, request *BulkWebhookDeleteRequest) (*BulkWebhookResult, error)
// Webhook status monitoring
TestWebhook(ctx context.Context, owner, repo string, webhookID int64) (*WebhookTestResult, error)
GetWebhookDeliveries(ctx context.Context, owner, repo string, webhookID int64) ([]*WebhookDelivery, error)
}
WebhookService defines the interface for webhook operations.
func NewWebhookService ¶
func NewWebhookService(apiClient APIClient, logger Logger) WebhookService
NewWebhookService creates a new webhook service instance.
func NewWebhookServiceWithToken ¶
func NewWebhookServiceWithToken(apiClient APIClient, token string, logger Logger) WebhookService
NewWebhookServiceWithToken creates a webhook service with a token for API calls.
type WebhookStatus ¶
type WebhookStatus struct {
ID string `json:"id"`
URL string `json:"url"`
Organization string `json:"organization"`
Repository string `json:"repository,omitempty"`
Events []string `json:"events"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastChecked time.Time `json:"last_checked"`
Status WebhookHealthStatus `json:"status"`
Metrics WebhookStatusMetrics `json:"metrics"`
Config map[string]interface{} `json:"config"`
Alerts []WebhookAlert `json:"alerts"`
History []WebhookHealthCheck `json:"history"`
}
WebhookStatus represents the current status of a webhook.
type WebhookStatusMetrics ¶
type WebhookStatusMetrics struct {
TotalDeliveries int64 `json:"total_deliveries"`
SuccessfulDeliveries int64 `json:"successful_deliveries"`
FailedDeliveries int64 `json:"failed_deliveries"`
AverageResponseTime time.Duration `json:"average_response_time"`
LastDeliveryTime time.Time `json:"last_delivery_time"`
LastSuccessTime time.Time `json:"last_success_time"`
LastFailureTime time.Time `json:"last_failure_time"`
ConsecutiveFailures int `json:"consecutive_failures"`
ErrorRate float64 `json:"error_rate"`
Uptime float64 `json:"uptime"`
}
WebhookStatusMetrics holds metrics for a specific webhook.
type WebhookTemplate ¶
type WebhookTemplate struct {
Name string `json:"name" yaml:"name"`
URL string `json:"url" yaml:"url"`
Events []string `json:"events" yaml:"events"`
Active bool `json:"active" yaml:"active"`
Config WebhookConfigTemplate `json:"config" yaml:"config"`
Variables map[string]string `json:"variables,omitempty" yaml:"variables,omitempty"` // Template variables
}
WebhookTemplate defines the webhook configuration template.
type WebhookTestResult ¶
type WebhookTestResult struct {
Success bool `json:"success"`
StatusCode int `json:"status_code"`
Response string `json:"response"`
Duration string `json:"duration"`
Error string `json:"error,omitempty"`
DeliveryID string `json:"delivery_id"`
TestedAt time.Time `json:"tested_at"`
}
WebhookTestResult represents the result of testing a webhook.
type WebhookUpdateRequest ¶
type WebhookUpdateRequest struct {
ID int64 `json:"id"`
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Events []string `json:"events,omitempty"`
Active *bool `json:"active,omitempty"`
Config WebhookConfig `json:"config,omitempty"`
}
WebhookUpdateRequest represents a request to update an existing webhook.
type WebhookValidationError ¶
type WebhookValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Severity string `json:"severity"`
Suggestion string `json:"suggestion,omitempty"`
}
WebhookValidationError represents a webhook validation error.
type WebhookValidationResult ¶
type WebhookValidationResult struct {
Valid bool `json:"valid"`
Errors []WebhookValidationError `json:"errors,omitempty"`
Warnings []WebhookValidationWarning `json:"warnings,omitempty"`
Score int `json:"score"` // 0-100
}
WebhookValidationResult represents the result of webhook configuration validation.
type WebhookValidationWarning ¶
type WebhookValidationWarning struct {
Field string `json:"field"`
Message string `json:"message"`
Suggestion string `json:"suggestion,omitempty"`
}
WebhookValidationWarning represents a webhook validation warning.
type WorkflowAuditResult ¶
type WorkflowAuditResult struct {
Repository string `json:"repository"`
Organization string `json:"organization"`
TotalWorkflows int `json:"total_workflows"`
AuditedFiles []WorkflowFileAudit `json:"audited_files"`
SecurityIssues []WorkflowSecurityIssue `json:"security_issues"`
PermissionUsage []WorkflowPermissionUsage `json:"permission_usage"`
ActionUsage []ActionUsageInfo `json:"action_usage"`
Summary WorkflowAuditSummary `json:"summary"`
Timestamp time.Time `json:"timestamp"`
}
WorkflowAuditResult represents the audit result for a repository.
type WorkflowAuditSummary ¶
type WorkflowAuditSummary struct {
TotalFiles int `json:"total_files"`
FilesWithIssues int `json:"files_with_issues"`
CriticalIssues int `json:"critical_issues"`
HighRiskIssues int `json:"high_risk_issues"`
MediumRiskIssues int `json:"medium_risk_issues"`
LowRiskIssues int `json:"low_risk_issues"`
AverageSecurityScore float64 `json:"average_security_score"`
PermissionDistribution map[string]int `json:"permission_distribution"`
ActionRiskDistribution map[SecurityRiskLevel]int `json:"action_risk_distribution"`
ComplianceScore float64 `json:"compliance_score"`
}
WorkflowAuditSummary provides summary statistics.
type WorkflowAuditor ¶
type WorkflowAuditor struct {
// contains filtered or unexported fields
}
WorkflowAuditor performs security audits on GitHub Actions workflows.
func NewWorkflowAuditor ¶
func NewWorkflowAuditor(logger Logger, apiClient APIClient) *WorkflowAuditor
NewWorkflowAuditor creates a new workflow auditor.
func (*WorkflowAuditor) AuditOrganization ¶
func (wa *WorkflowAuditor) AuditOrganization(ctx context.Context, organization string) ([]*WorkflowAuditResult, error)
AuditOrganization performs workflow audit across all repositories in an organization.
func (*WorkflowAuditor) AuditRepository ¶
func (wa *WorkflowAuditor) AuditRepository(ctx context.Context, organization, repository string) (*WorkflowAuditResult, error)
AuditRepository performs a comprehensive audit of all workflows in a repository.
type WorkflowFile ¶
type WorkflowFile struct {
Name string `yaml:"name"`
On interface{} `yaml:"on"`
Permissions map[string]interface{} `yaml:"permissions"`
Jobs map[string]Job `yaml:"jobs"`
Env map[string]string `yaml:"env"`
}
Workflow structure for parsing YAML.
type WorkflowFileAudit ¶
type WorkflowFileAudit struct {
FilePath string `json:"file_path"`
WorkflowName string `json:"workflow_name"`
Triggers []string `json:"triggers"`
Jobs []JobAuditInfo `json:"jobs"`
Permissions map[string]string `json:"permissions,omitempty"`
SecurityScore int `json:"security_score"`
Issues []WorkflowSecurityIssue `json:"issues"`
LastModified time.Time `json:"last_modified"`
}
WorkflowFileAudit represents audit information for a single workflow file.
type WorkflowInfo ¶
type WorkflowInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
State string `json:"state"`
Permissions map[string]string `json:"permissions,omitempty"`
Actions []string `json:"actions,omitempty"`
LastRun time.Time `json:"lastRun"`
}
WorkflowInfo represents information about a workflow.
type WorkflowIssueType ¶
type WorkflowIssueType string
Enum types.
const ( IssueTypeExcessivePermissions WorkflowIssueType = "excessive_permissions" IssueTypeUnpinnedAction WorkflowIssueType = "unpinned_action" IssueTypeDeprecatedAction WorkflowIssueType = "deprecated_action" IssueTypeUnverifiedAction WorkflowIssueType = "unverified_action" IssueTypeSecretExposure WorkflowIssueType = "secret_exposure" IssueTypeCodeInjection WorkflowIssueType = "code_injection" IssueTypePrivilegeEscalation WorkflowIssueType = "privilege_escalation" IssueTypeInsecureRunner WorkflowIssueType = "insecure_runner" IssueTypeMissingPermissions WorkflowIssueType = "missing_permissions" IssueTypeEnvironmentIssue WorkflowIssueType = "environment_issue" )
type WorkflowPermissionUsage ¶
type WorkflowPermissionUsage struct {
Scope string `json:"scope"`
Permission string `json:"permission"`
UsageCount int `json:"usage_count"`
WorkflowFiles []string `json:"workflow_files"`
Recommended string `json:"recommended,omitempty"`
}
WorkflowPermissionUsage represents permission usage statistics.
type WorkflowPermissions ¶
type WorkflowPermissions struct {
DefaultPermissions DefaultPermissions `json:"defaultPermissions" yaml:"defaultPermissions"`
CanApproveOwnChanges bool `json:"canApproveOwnChanges" yaml:"canApproveOwnChanges"`
ActionsReadPermission ActionsTokenPermission `json:"actionsRead" yaml:"actionsRead"`
ContentsPermission ActionsTokenPermission `json:"contents" yaml:"contents"`
MetadataPermission ActionsTokenPermission `json:"metadata" yaml:"metadata"`
PackagesPermission ActionsTokenPermission `json:"packages" yaml:"packages"`
PullRequestsPermission ActionsTokenPermission `json:"pullRequests" yaml:"pullRequests"`
IssuesPermission ActionsTokenPermission `json:"issues" yaml:"issues"`
DeploymentsPermission ActionsTokenPermission `json:"deployments" yaml:"deployments"`
ChecksPermission ActionsTokenPermission `json:"checks" yaml:"checks"`
StatusesPermission ActionsTokenPermission `json:"statuses" yaml:"statuses"`
SecurityEventsPermission ActionsTokenPermission `json:"securityEvents" yaml:"securityEvents"`
IdTokenPermission ActionsTokenPermission `json:"idToken" yaml:"idToken"`
AttestationsPermission ActionsTokenPermission `json:"attestations" yaml:"attestations"`
CustomPermissions map[string]ActionsTokenPermission `json:"customPermissions,omitempty" yaml:"customPermissions,omitempty"`
}
WorkflowPermissions defines permissions for workflow tokens.
type WorkflowPermissionsValidationRule ¶
type WorkflowPermissionsValidationRule struct{}
WorkflowPermissionsValidationRule validates workflow token permissions.
func (*WorkflowPermissionsValidationRule) GetDescription ¶
func (r *WorkflowPermissionsValidationRule) GetDescription() string
func (*WorkflowPermissionsValidationRule) GetRuleID ¶
func (r *WorkflowPermissionsValidationRule) GetRuleID() string
func (*WorkflowPermissionsValidationRule) Validate ¶
func (r *WorkflowPermissionsValidationRule) Validate(ctx context.Context, policy *ActionsPolicy, currentState *RepositoryActionsState) (*PolicyValidationResult, error)
type WorkflowSecurityIssue ¶
type WorkflowSecurityIssue struct {
ID string `json:"id"`
Type WorkflowIssueType `json:"type"`
Severity SecurityIssueSeverity `json:"severity"`
Title string `json:"title"`
Description string `json:"description"`
FilePath string `json:"file_path"`
JobID string `json:"job_id,omitempty"`
StepIndex int `json:"step_index,omitempty"`
LineNumber int `json:"line_number,omitempty"`
Suggestion string `json:"suggestion"`
References []string `json:"references,omitempty"`
}
WorkflowSecurityIssue represents a security issue found in a workflow.
Source Files
¶
- actions_policy.go
- actions_policy_enforcer.go
- actions_policy_validation_rules.go
- automation_engine.go
- automation_rule.go
- bulk_operations.go
- cached_client.go
- change_logger.go
- changelog.go
- condition_evaluator.go
- confirmation.go
- constructors.go
- dependabot_config.go
- dependabot_policy_manager.go
- dependency_version_policy.go
- doc.go
- event_system.go
- facade.go
- factory.go
- filestore.go
- github_org_clone.go
- http_adapter.go
- interfaces.go
- memory_utils.go
- optimized_synclone.go
- provider_factory.go
- provider_impl.go
- rate_limiter.go
- repo_config.go
- repo_state_collector.go
- resilient_client.go
- resumable_clone.go
- rule_manager.go
- security_update_policy.go
- streaming_api.go
- token_aware_client.go
- token_validator.go
- webhook.go
- webhook_config.go
- webhook_config_impl.go
- webhook_monitor.go
- workflow_auditor.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package largescale provides efficient large-scale repository operations for GitHub.
|
Package largescale provides efficient large-scale repository operations for GitHub. |
|
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |