distribute

package
v0.0.0-...-40cbffd Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Overview

Package distribute implements the distribute command functionality

Package distribute provides the distribute command workflow and typed errors used throughout the distribute command functionality.

Package distribute exposes the distribution creation flow to the app layer.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CountExpectedLinkingTasks

func CountExpectedLinkingTasks(cfg *repoConfig.OriginConfig, groupCount int) int

CountExpectedLinkingTasks counts how many linking tasks are expected. This is used to calculate the total progress.

func LinkRepositoryPair

func LinkRepositoryPair(ctx context.Context, handler *CommandHandler, fromTarget, toTarget, uuid string, fromRemote, toRemote dataprovider.RemoteMapping) error

LinkRepositoryPair processes a single repository pair with matching UUID. Exported to allow pre-commit linking from concurrent target execution.

func LinkTargetRepositories

func LinkTargetRepositories(ctx context.Context, handler *CommandHandler, results map[string]*ProjectSetupResult) error

LinkTargetRepositories sets up cross-repo variables for each configured pair of targets. Uses a worker pool for parallel execution with rate limiting to avoid overwhelming GitLab.

func LinkTargetRepositoriesWithProgress

func LinkTargetRepositoriesWithProgress(ctx context.Context, handler *CommandHandler, results map[string]*ProjectSetupResult, tracker *progress.FooterProgressTracker) error

LinkTargetRepositoriesWithProgress sets up cross-repo variables with optional progress tracking.

func ResolveNoMemberAssignment

func ResolveNoMemberAssignment(provider string, generatedCount int, explicitNoMemberAssignment bool) (bool, bool)

ResolveNoMemberAssignment decides whether member assignment is disabled for a distribution run. Generated repositories (--count) on the GitLab provider disable assignment automatically; the second return value reports that automatic decision.

Types

type CommandHandler

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

CommandHandler contains the state and methods for the distribute command

func NewCommandHandler

func NewCommandHandler(opts *CommandHandlerOptions) (*CommandHandler, error)

NewCommandHandler creates a new handler with initial flags and mode. Configuration loading and client setup happens in the Setup() method.

func (*CommandHandler) Cleanup

func (h *CommandHandler) Cleanup(ctx context.Context) error

Cleanup performs any necessary cleanup operations after distribution. Its primary role is to persist any configuration changes that were generated during execution, such as the GroupID for a newly created evaluation subgroup.

func (*CommandHandler) DetermineMode

func (h *CommandHandler) DetermineMode(ctx context.Context) error

DetermineMode determines the distribution mode (add users or fresh) based on context and user input.

func (*CommandHandler) Execute

func (h *CommandHandler) Execute(ctx context.Context) error

Execute orchestrates the whole distribution workflow (projects ➜ members ➜ content). It is the single public entry‑point called from pipeline.go after validation.

func (*CommandHandler) PrecheckAndMaybeDeleteExisting

func (h *CommandHandler) PrecheckAndMaybeDeleteExisting(ctx context.Context) error

PrecheckAndMaybeDeleteExisting checks for existing projects and deletes them if configured. In fresh mode, it will also scan for existing projects and prompt for deletion.

func (*CommandHandler) ProcessMembersInput

func (h *CommandHandler) ProcessMembersInput(ctx context.Context) error

ProcessMembersInput processes member input for all targets

func (*CommandHandler) SaveConfig

func (h *CommandHandler) SaveConfig(ctx context.Context) error

SaveConfig saves the updated distribution configuration to disk.

func (*CommandHandler) Setup

func (h *CommandHandler) Setup(ctx context.Context) error

Setup initializes the handler with configuration and dependencies

func (*CommandHandler) ShowDistributionPlan

func (h *CommandHandler) ShowDistributionPlan(
	ctx context.Context,
	targetMembers map[string]*config.MembersConfig,
	distribution *config.Distribution,
	baseURLs map[string]string,
) (bool, error)

ShowDistributionPlan displays the planned actions and asks for confirmation.

func (*CommandHandler) Validate

func (h *CommandHandler) Validate(ctx context.Context) (bool, error)

Validate validates the distribution configuration and displays the plan for user confirmation.

type CommandHandlerOptions

type CommandHandlerOptions struct {
	Token                         string
	BaseURL                       string
	Distribution                  string
	MembersFile                   string
	GeneratedMemberCount          int
	SkipVariationConfigValidation bool
	ReplaceMembers                bool
	IgnoreConfiguredMembers       bool
	PromptConfiguredMembersAction bool
	ConfiguredMembersAction       string
	UseMembersFileDirectly        bool
	Message                       string
	Provider                      string
	AddUsers                      bool
	Fresh                         bool
	NoMemberAssignment            bool
	WorkingDir                    string
	DivekitHome                   string
	ConfigService                 config.ConfigService
	FileSystem                    filesystem.FileSystem
	UserInput                     userinput.UserInput
	DistributionSelector          config.DistributionSelector

	// Worker pool overrides
	WorkersOverride     int
	RateLimitOverride   float64
	TaskTimeoutOverride time.Duration
	// Track whether the corresponding flags were explicitly set
	WorkersSet     bool
	RateLimitSet   bool
	TaskTimeoutSet bool

	// Danger flag
	DangerouslyDeleteGroupProjects bool

	// Scripting
	Languages []string

	// Detection
	WarnUnresolved string

	// ProgressCallback forwards normalized footer progress updates to external observers.
	ProgressCallback func(label string, percent float64, details map[string]any)
	// StatusCallback forwards live activity updates for repository creation, commits and member assignment.
	StatusCallback func(message string, details map[string]any)
}

CommandHandlerOptions contains options for creating a new CommandHandler

type DeletionPlan

type DeletionPlan struct {
	Targets map[string][]*dataprovider.Project
	Total   int
}

DeletionPlan captures repositories slated for deletion per target.

func BuildDeletionPlan

func BuildDeletionPlan(ctx context.Context, cfg *config.OriginConfig, clients map[string]repository.DistributionProvider) *DeletionPlan

BuildDeletionPlan scans configured targets for existing repositories. It returns a plan grouped by target name and sorted by project name.

type DeletionResult

type DeletionResult struct {
	Deleted int
	Failed  int
}

DeletionResult summarizes the deletion outcome.

func DeleteProjects

func DeleteProjects(ctx context.Context, clients map[string]repository.DistributionProvider, plan *DeletionPlan) DeletionResult

DeleteProjects removes repositories contained in the plan using the provided clients. It displays a progress bar and returns a result summary.

type Error

Error is a type alias for the generic CommandError.

func NewAccessTokenCreationError

func NewAccessTokenCreationError(err error) *Error

NewAccessTokenCreationError creates an error for access token creation failures.

func NewClientInitError

func NewClientInitError(details string, err error) *Error

NewClientInitError creates an error for client initialization failures.

func NewConfigLoadError

func NewConfigLoadError(err error) *Error

NewConfigLoadError creates an error for configuration loading failures.

func NewConfigSaveError

func NewConfigSaveError(err error) *Error

NewConfigSaveError creates an error for configuration saving failures.

func NewConfirmationError

func NewConfirmationError(err error) *Error

NewConfirmationError creates an error for confirmation failures or cancellation.

func NewContentUploadError

func NewContentUploadError(target string, err error) *Error

NewContentUploadError creates an error for content upload failures.

func NewContextCancelledError

func NewContextCancelledError(uuid string, err error) *Error

NewContextCancelledError creates an error for cancelled context.

func NewCredentialsResolveError

func NewCredentialsResolveError(target string, err error) *Error

NewCredentialsResolveError creates an error for credential resolution failures.

func NewDirCreationError

func NewDirCreationError(path string, err error) *Error

NewDirCreationError creates an error for directory creation failures.

func NewDirWalkError

func NewDirWalkError(dir string, err error) *Error

NewDirWalkError creates an error for directory walk failures.

func NewDirectoryWalkError

func NewDirectoryWalkError(dir string, err error) *Error

NewDirectoryWalkError creates an error for directory walking failures.

func NewDistributionListingError

func NewDistributionListingError(path string, err error) *Error

NewDistributionListingError creates an error for distribution listing failures.

func NewDistributionSelectionError

func NewDistributionSelectionError(err error) *Error

NewDistributionSelectionError creates an error for distribution selection failures.

func NewError

func NewError(errorType ErrorType, message string, err error) *Error

NewError creates a new Error (kept for backward compatibility).

func NewEvaluationPipelineGroupIDError

func NewEvaluationPipelineGroupIDError(targetName string) *Error

NewEvaluationPipelineGroupIDError creates an error for evaluation pipeline group ID issues.

func NewEvaluationPipelineValidationError

func NewEvaluationPipelineValidationError(target string) *Error

NewEvaluationPipelineValidationError creates an error for evaluation pipeline validation.

func NewExecutionError

func NewExecutionError(msg string) *Error

NewExecutionError creates a general execution error.

func NewFileAccessError

func NewFileAccessError(path string, err error) *Error

NewFileAccessError creates an error for file access failures.

func NewFileCopyError

func NewFileCopyError(err error) *Error

NewFileCopyError creates an error for file copy failures.

func NewFileReadError

func NewFileReadError(path string, err error) *Error

NewFileReadError creates an error for file read failures.

func NewFileUploadError

func NewFileUploadError(err error) *Error

NewFileUploadError creates an error for file upload failures.

func NewFileWriteError

func NewFileWriteError(path string, err error) *Error

NewFileWriteError creates an error for file write failures.

func NewGitLabConnectionError

func NewGitLabConnectionError(err error) *Error

NewGitLabConnectionError creates an error for GitLab connection failures.

func NewHandlerCreationError

func NewHandlerCreationError(err error) *Error

NewHandlerCreationError creates an error for handler creation failures.

func NewHandlerOptionsError

func NewHandlerOptionsError() *Error

NewHandlerOptionsError creates an error for handler options validation.

func NewIndividualNotFoundError

func NewIndividualNotFoundError(uuid string) *Error

NewIndividualNotFoundError creates an error for missing individual configuration.

func NewIndividualizationError

func NewIndividualizationError(projectID int, err error) *Error

NewIndividualizationError creates an error for individualization failures.

func NewIndividualizerApplyError

func NewIndividualizerApplyError(uuid string, err error) *Error

NewIndividualizerApplyError creates an error for individualizer apply failures.

func NewIndividualsConfigError

func NewIndividualsConfigError(err error) *Error

NewIndividualsConfigError creates an error for individuals configuration issues.

func NewInvalidGroupIDError

func NewInvalidGroupIDError(details string, err error) *Error

NewInvalidGroupIDError creates an error for invalid group ID.

func NewLinkingValidationError

func NewLinkingValidationError(details string) *Error

NewLinkingValidationError creates an error for linking validation failures.

func NewMemberProcessingError

func NewMemberProcessingError(err error) *Error

NewMemberProcessingError creates an error for member processing failures.

func NewMemberValidationError

func NewMemberValidationError(details string, err error) *Error

NewMemberValidationError creates an error for member validation failures.

func NewMembersConfigSaveError

func NewMembersConfigSaveError(target string, err error) *Error

NewMembersConfigSaveError creates an error for saving members configuration.

func NewMembersFileProcessError

func NewMembersFileProcessError(target string, err error) *Error

NewMembersFileProcessError creates an error for members file processing failures.

func NewMembersNotFoundError

func NewMembersNotFoundError(details string) *Error

NewMembersNotFoundError creates an error when members are not found.

func NewMissingGroupIDError

func NewMissingGroupIDError(targetName string) *Error

NewMissingGroupIDError creates an error for missing group ID.

func NewModeSelectionError

func NewModeSelectionError(err error) *Error

NewModeSelectionError creates an error for mode selection failures or cancellation.

func NewMultipleErrorsError

func NewMultipleErrorsError(errors []string) *Error

NewMultipleErrorsError creates an error aggregating multiple failures.

func NewNoNewProjectsError

func NewNoNewProjectsError() *Error

NewNoNewProjectsError creates an error when no new projects need to be created.

func NewNoTargetsFoundError

func NewNoTargetsFoundError() *Error

NewNoTargetsFoundError creates an error when no targets are found.

func NewPathAccessError

func NewPathAccessError(path string, err error) *Error

NewPathAccessError creates an error for path access failures.

func NewPathResolutionError

func NewPathResolutionError(path string, err error) *Error

NewPathResolutionError creates an error for path resolution failures.

func NewPlanDisplayError

func NewPlanDisplayError(err error) *Error

NewPlanDisplayError creates an error for plan display failures.

func NewProcessProjectError

func NewProcessProjectError(projectID int, err error) *Error

NewProcessProjectError creates an error for project processing failures.

func NewProjectCreationError

func NewProjectCreationError(err error) *Error

NewProjectCreationError creates an error for project creation failures.

func NewProjectDataError

func NewProjectDataError(details string) *Error

NewProjectDataError creates an error for invalid project data.

func NewProjectIdentifierError

func NewProjectIdentifierError(err error) *Error

NewProjectIdentifierError creates an error for project identifier failures.

func NewProjectLinkingError

func NewProjectLinkingError(details string, err error) *Error

NewProjectLinkingError creates an error for project linking failures.

func NewProjectLoadError

func NewProjectLoadError(err error) *Error

NewProjectLoadError creates an error for project loading failures.

func NewProjectNilError

func NewProjectNilError() *Error

NewProjectNilError creates an error when project is nil.

func NewProjectUUIDNotFoundError

func NewProjectUUIDNotFoundError(projectID int) *Error

NewProjectUUIDNotFoundError creates an error for missing project UUID.

func NewProviderTypeError

func NewProviderTypeError(operation string) *Error

NewProviderTypeError creates an error for unsupported provider types.

func NewRelativePathError

func NewRelativePathError(path string, err error) *Error

NewRelativePathError creates an error for relative path failures.

func NewRepositoryCreationError

func NewRepositoryCreationError(target string, err error) *Error

NewRepositoryCreationError creates an error for repository creation failures.

func NewSaveIndividualsConfigError

func NewSaveIndividualsConfigError(err error) *Error

NewSaveIndividualsConfigError creates an error for saving individuals config.

func NewServiceNotInitializedError

func NewServiceNotInitializedError() *Error

NewServiceNotInitializedError creates an error for when the distribution service is not initialized.

func NewSetupError

func NewSetupError(cause error) *Error

NewSetupError creates a general setup error that wraps an underlying cause. The cause error is preserved to maintain suggestions and other error context.

func NewTargetExecutionError

func NewTargetExecutionError(targetName string, err error) *Error

NewTargetExecutionError creates an error for target execution failures.

func NewTargetNotFoundError

func NewTargetNotFoundError(target string) *Error

NewTargetNotFoundError creates an error for target not found.

func NewTempDirCreationError

func NewTempDirCreationError(err error) *Error

NewTempDirCreationError creates an error for temporary directory creation failures.

func NewTokenCreationError

func NewTokenCreationError(tokenType string, err error) *Error

NewTokenCreationError creates an error for token creation failures.

func NewTriggerTokenCreationError

func NewTriggerTokenCreationError(err error) *Error

NewTriggerTokenCreationError creates an error for trigger token creation failures.

func NewValidationError

func NewValidationError(details string, err error) *Error

NewValidationError creates a general validation error.

func NewValidationPreparationError

func NewValidationPreparationError(targetName string, err error) *Error

NewValidationPreparationError creates an error for validation preparation failures.

func NewVariableSetError

func NewVariableSetError(key string, err error) *Error

NewVariableSetError creates an error for variable setting failures.

func NewVariationConfigError

func NewVariationConfigError(err error) *Error

NewVariationConfigError creates an error for variation configuration issues.

type ErrorType

type ErrorType int

ErrorType defines domain-based error categories. Consolidated from 64+ specific types to 10 semantic domains.

const (
	// ErrConfig indicates configuration-related errors (load, save, parse, marshal).
	ErrConfig ErrorType = iota

	// ErrFilesystem indicates file system operation errors (read, write, copy, walk).
	ErrFilesystem

	// ErrGitLab indicates GitLab API or connection errors.
	ErrGitLab

	// ErrValidation indicates input validation or constraint errors.
	ErrValidation

	// ErrProcess indicates processing or execution errors.
	ErrProcess

	// ErrResource indicates missing or invalid resources.
	ErrResource

	// ErrSetup indicates initialization or setup errors.
	ErrSetup

	// ErrUserCancelled indicates user-initiated cancellation.
	ErrUserCancelled

	// ErrMultiple indicates multiple errors occurred during batch processing.
	ErrMultiple

	// ErrInternal indicates unexpected internal errors.
	ErrInternal
)

func (ErrorType) String

func (t ErrorType) String() string

String returns a human-readable name for the error type.

type Handler

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

Handler orchestrates the distribution flow.

func NewHandler

func NewHandler(opts *HandlerOptions) *Handler

NewHandler constructs a distribute handler with default dependencies.

func (*Handler) Execute

func (h *Handler) Execute(ctx context.Context, req Request) (Result, error)

Execute validates, runs, and persists a distribution execution.

type HandlerOptions

type HandlerOptions struct {
	NewInternalHandler newInternalHandlerFunc
}

HandlerOptions configures how the distribute handler creates its internal command handler.

type LinkingCoordinator

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

LinkingCoordinator coordinates inline repository linking during distribution. It tracks completed distribution tasks and triggers linking as soon as both repositories in a linking pair are ready for a given UUID.

func NewLinkingCoordinator

func NewLinkingCoordinator(ctx context.Context, handler *CommandHandler, footerTracker *progress.FooterProgressTracker) *LinkingCoordinator

NewLinkingCoordinator creates a new coordinator for inline linking.

func (*LinkingCoordinator) HasLinking

func (c *LinkingCoordinator) HasLinking() bool

HasLinking returns true if there are linking pairs configured.

func (*LinkingCoordinator) OnDistributionComplete

func (c *LinkingCoordinator) OnDistributionComplete(uuid, targetName string, mapping dataprovider.RemoteMapping)

OnDistributionComplete is called when a distribution task completes. It checks if linking can be triggered for this UUID.

func (*LinkingCoordinator) Start

func (c *LinkingCoordinator) Start() error

Start initializes the linking worker pool if there are linking pairs configured.

func (*LinkingCoordinator) Stop

func (c *LinkingCoordinator) Stop()

Stop stops the linking pool (called after Wait, safe to call multiple times).

func (*LinkingCoordinator) Wait

func (c *LinkingCoordinator) Wait()

Wait waits for all linking tasks to complete and stops the pool.

func (*LinkingCoordinator) WaitForUUID

func (c *LinkingCoordinator) WaitForUUID(uuid string)

WaitForUUID waits until all linking tasks already submitted for the UUID complete.

type ProjectSetupResult

type ProjectSetupResult struct {
	Mappings          *dataprovider.Remotes // created repos
	FailedAssignments []string              // failed member assignments
	FailedUploads     map[string]error      // file/commit errors
	SuccessfulUploads []int                 // project IDs with successful upload
}

ProjectSetupResult collects all sub-results of a target.

type Request

type Request struct {
	Token                          string
	BaseURL                        string
	Distribution                   string
	MembersFile                    string
	GeneratedMemberCount           int
	ReplaceMembers                 bool
	UseMembersFileDirectly         bool
	Message                        string
	Provider                       string
	AddUsers                       bool
	Fresh                          bool
	NoMemberAssignment             bool
	WorkingDir                     string
	DivekitHome                    string
	ConfigService                  config.ConfigService
	FileSystem                     filesystem.FileSystem
	UserInput                      userinput.UserInput
	DistributionSelector           config.DistributionSelector
	WorkersOverride                int
	RateLimitOverride              float64
	TaskTimeoutOverride            time.Duration
	WorkersSet                     bool
	RateLimitSet                   bool
	TaskTimeoutSet                 bool
	DangerouslyDeleteGroupProjects bool
	Languages                      []string
	WarnUnresolved                 string
	ProgressCallback               func(label string, percent float64, details map[string]any)
	StatusCallback                 func(message string, details map[string]any)
}

Request contains the dependencies and input required for a distribution run.

type Result

type Result struct {
	Confirmed bool
}

Result reports whether the distribution run was confirmed and executed.

type TargetCtx

type TargetCtx struct {
	Name             string
	DistributionName string
	WorkingDir       string
	CommandHandler   *CommandHandler
	TargetCfg        config.OriginTarget
}

TargetCtx contains minimal context for target-specific operations (project name pattern resolution, evaluation pipeline injection)

Directories

Path Synopsis
Package progress provides progress tracking functionality for repository deletion operations using bubble tea UI components.
Package progress provides progress tracking functionality for repository deletion operations using bubble tea UI components.
Package ui provides output formatting and rendering utilities for the distribute command, including URL styling, warning boxes, and path utilities.
Package ui provides output formatting and rendering utilities for the distribute command, including URL styling, warning boxes, and path utilities.

Jump to

Keyboard shortcuts

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