cmd

package
v1.1.13 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package cmd implements the command-line interface for Hitch, a Git workflow manager for multi-environment development.

Overview

This package provides the complete CLI implementation using the Cobra framework, with commands for managing feature branch promotions across multiple deployment environments (dev, qa, staging, production, etc.).

Core Commands

The package implements these primary commands:

  • init: Initialize a new Hitch repository with environments
  • status: Display current environment status and branch promotions
  • validate: Validate hitch.json configuration file
  • promote: Promote a feature branch to an environment
  • demote: Remove a feature branch from an environment
  • rebuild: Rebuild an environment branch from base + features
  • release: Merge an environment to the base branch (e.g., dev → main)
  • cleanup: Remove merged branches that are no longer needed
  • lock: Lock an environment to prevent concurrent modifications
  • unlock: Unlock an environment to allow modifications
  • recover: Recover from stale locks or crashed operations
  • hook: Git hook integration command for manual hook setup
  • install: Install Hitch binary to system PATH

Command Patterns

Commands follow consistent patterns for user experience:

// Promote: hitch promote <branch> to <environment>
hitch promote feature/login to dev

// Demote: hitch demote <branch> from <environment>
hitch demote feature/login from dev

// Rebuild: hitch rebuild <environment>
hitch rebuild dev

// Release: hitch release <environment>
hitch release dev

Safety Mechanisms

All commands implement multiple safety layers:

  • Temp Branch Testing: Operations are tested in temporary branches before actual execution (via safety.TempBranchTester)
  • Lock Management: Prevents concurrent environment modifications via metadata.LockManager
  • Panic Recovery: Automatic recovery from crashes with state restoration
  • Validation: Comprehensive pre-flight checks before any git operations

Global Flags

All commands support these global flags:

  • --verbose, -v: Enable verbose output for debugging
  • --no-color: Disable colored output for CI/CD environments

Command-Specific Flags

Common command-specific flags include:

  • promote/demote: --no-rebuild (skip automatic rebuild)
  • rebuild: --dry-run (preview changes), --force (bypass lock checks)
  • cleanup: --dry-run (preview cleanup), --force (skip eligibility checks)
  • lock: --reason (provide lock justification)
  • unlock: --force (force unlock even if not lock owner)
  • status: --env (filter by environment), --json (JSON output), --stale (show stale branches)

Testing

The package includes comprehensive test coverage with:

  • Unit tests for individual commands (promote_test.go, cleanup_release_test.go)
  • Integration tests for complex workflows (integration_edge_cases_test.go)
  • Behavioral tests for user-facing scenarios (behavioral_test.go)
  • Helper and error path tests (helpers_errors_test.go, status_lock_test.go)

All tests run in isolated environments to ensure reproducibility.

Architecture

Commands follow a consistent execution pattern:

  1. Parse and validate user input (args, flags)
  2. Load and validate repository state
  3. Load metadata from hitch-metadata branch
  4. Acquire necessary locks via LockManager
  5. Test operations in temp branches (TempBranchTester)
  6. Execute hooks if configured (HookExecutor)
  7. Perform actual git operations
  8. Update metadata and commit changes
  9. Release locks and cleanup
  10. Display user-friendly output

Error Handling

Commands use colored, user-friendly error messages:

  • ✓ Green checkmarks for successful operations
  • ⚠ Yellow warnings for non-blocking issues
  • ❌ Red X marks for errors and failures

Example output:

✓ Successfully tested merge of feature/login into dev
✓ Added feature/login to dev feature list
✓ Updated metadata
⚠ Skipped rebuild (use 'hitch rebuild dev' to rebuild)

Dependencies

The package coordinates multiple internal packages:

  • internal/git: Git repository operations
  • internal/metadata: Metadata management on orphan branch
  • internal/safety: Safe operation testing
  • internal/validation: Input and state validation
  • internal/hooks: Hook execution
  • internal/security: Input sanitization

Example Usage

Basic workflow for promoting a feature:

// Initialize Hitch in a repository
hitch init --environments dev,qa,staging,prod --base main

// Promote feature to dev
hitch promote feature/login to dev

// Check status
hitch status

// Rebuild dev environment
hitch rebuild dev

// Promote to qa after testing
hitch promote feature/login to qa
hitch rebuild qa

// Release to main when ready
hitch release qa

// Cleanup merged branches
hitch cleanup --dry-run  // Preview
hitch cleanup            // Execute

Index

Constants

This section is empty.

Variables

View Source
var RootCmd = &cobra.Command{
	Use:     "hitch",
	Short:   "Git workflow manager for multi-environment development",
	Version: version.GetVersionString(),
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {

		ui.SetLoggingConfig(noColor, quiet)

		logConfig := core.LoggingConfig{
			Quiet:           quiet,
			Verbose:         verbose,
			NoColor:         noColor,
			LogFile:         logFile,
			Level:           core.ParseLogLevel(logLevel),
			EnableCaller:    verbose,
			EnableTimestamp: verbose,
			EnableSystemLog: false,
		}
		if err := core.SetLoggingConfig(logConfig); err != nil {
			return fmt.Errorf("failed to configure logging: %w", err)
		}

		if noColor {
			color.NoColor = true
		}

		if cmd.Name() != "help" && cmd.Name() != "version" {
			repoPath, err := findGitRepository()
			if err == nil && repoPath != "" {
				globalRepoLock := core.GetGlobalRepositoryLock(repoPath)
				if lockErr := globalRepoLock.Lock(); lockErr != nil {
					return lockErr
				}
			}
		}

		return nil
	},
	PersistentPostRunE: func(cmd *cobra.Command, args []string) error {

		if cmd.Name() != "help" && cmd.Name() != "version" {
			repoPath, err := findGitRepository()
			if err == nil && repoPath != "" {
				globalRepoLock := core.GetGlobalRepositoryLock(repoPath)
				if unlockErr := globalRepoLock.Unlock(); unlockErr != nil {

					fmt.Fprintf(os.Stderr, "Warning: failed to unlock repository: %v\n", unlockErr)
				}

			}
		}
		return nil
	},
}

rootCmd represents the base command

Functions

func Execute

func Execute() error

Execute runs the root command

func ResetGlobalFlags added in v1.1.11

func ResetGlobalFlags()

ResetGlobalFlags resets all global flags to their default values This is primarily used in tests to ensure clean state between test runs

Types

type AvailableHook added in v1.1.12

type AvailableHook struct {
	Type    string
	Name    string
	Command string
	Config  metadata.HookConfig
}

Helper structs for interactive selection

type BranchChangeStatus added in v1.1.12

type BranchChangeStatus struct {
	BranchName     string
	HasChanges     bool
	CommitsAhead   int
	ForcePushed    bool
	Deleted        bool
	CurrentSHA     string
	LastRebuildSHA string
	RebuildNeeded  bool
}

BranchChangeStatus represents the change status of a branch since last rebuild

type BranchInfo added in v0.1.21

type BranchInfo struct {
	CreatedAt            time.Time      `json:"created_at"`
	LastCommitAt         time.Time      `json:"last_commit_at"`
	PromotedTo           []string       `json:"promoted_to"`
	MergedToMainAt       *time.Time     `json:"merged_to_main_at,omitempty"`
	MergedToMainBy       string         `json:"merged_to_main_by,omitempty"`
	CanDelete            bool           `json:"can_delete"`
	EligibleForCleanupAt *time.Time     `json:"eligible_for_cleanup_at,omitempty"`
	LastRebuildSHA       string         `json:"last_rebuild_sha,omitempty"`
	RebuildStatus        *RebuildStatus `json:"rebuild_status,omitempty"`
}

BranchInfo contains branch status information

type CommandContext added in v1.1.9

type CommandContext struct {
	Repo *hitchgit.Repo
	Meta *metadata.Metadata
}

CommandContext holds shared state for commands that operate on a repo and metadata

type EnvironmentInfo added in v0.1.21

type EnvironmentInfo struct {
	BaseBranch  string    `json:"base_branch"`
	Features    []string  `json:"features"`
	Locked      bool      `json:"locked"`
	LockInfo    *LockInfo `json:"lock_info,omitempty"`
	LastRebuild time.Time `json:"last_rebuild,omitempty"`
}

EnvironmentInfo contains environment status information

type HookContext added in v1.1.12

type HookContext struct {
	Branch      string
	Environment string
	UserEmail   string
	UserName    string
	BaseBranch  string
}

HookContext represents context for hook execution

type JSONHook added in v1.1.12

type JSONHook struct {
	Name       string   `json:"name"`
	Type       string   `json:"type"`
	Command    string   `json:"command"`
	Args       []string `json:"args"`
	WorkingDir string   `json:"working_dir,omitempty"`
	Required   bool     `json:"required"`
}

type JSONHookType added in v1.1.12

type JSONHookType struct {
	Name  string     `json:"name"`
	Hooks []JSONHook `json:"hooks"`
	Count int        `json:"count"`
}

type JSONHooks added in v1.1.12

type JSONHooks struct {
	Timestamp         time.Time               `json:"timestamp"`
	HookTypes         map[string]JSONHookType `json:"hook_types"`
	SortedHookTypes   []string                `json:"sorted_hook_types"`
	TotalHooks        int                     `json:"total_hooks"`
	TemplateVariables []TemplateVariable      `json:"template_variables"`
	Metadata          JSONMetadataInfo        `json:"metadata"`
}

type JSONMetadataInfo added in v1.1.12

type JSONMetadataInfo struct {
	Version        string    `json:"version"`
	InitializedAt  time.Time `json:"initialized_at"`
	LastModifiedAt time.Time `json:"last_modified_at"`
	LastModifiedBy string    `json:"last_modified_by"`
	LastCommand    string    `json:"last_command"`
}

type JSONStatus added in v0.1.21

type JSONStatus struct {
	Timestamp  time.Time      `json:"timestamp"`
	Repository RepositoryInfo `json:"repository"`
	Metadata   MetadataInfo   `json:"metadata"`
}

JSONStatus represents the complete status in JSON format

type LockInfo added in v0.1.21

type LockInfo struct {
	LockedBy string    `json:"locked_by"`
	LockedAt time.Time `json:"locked_at"`
	Reason   string    `json:"reason,omitempty"`
	IsStale  bool      `json:"is_stale"`
}

LockInfo contains lock status information

type MetadataInfo added in v0.1.21

type MetadataInfo struct {
	Version        string    `json:"version"`
	InitializedAt  time.Time `json:"initialized_at"`
	LastModifiedAt time.Time `json:"last_modified_at"`
	LastModifiedBy string    `json:"last_modified_by"`
	LastCommand    string    `json:"last_command"`
}

MetadataInfo contains metadata status information

type RebuildStatus added in v1.1.12

type RebuildStatus struct {
	HasChanges     bool   `json:"has_changes"`
	CommitsAhead   int    `json:"commits_ahead"`
	ForcePushed    bool   `json:"force_pushed"`
	Deleted        bool   `json:"deleted"`
	CurrentSHA     string `json:"current_sha"`
	LastRebuildSHA string `json:"last_rebuild_sha"`
	RebuildNeeded  bool   `json:"rebuild_needed"`
}

RebuildStatus contains rebuild status information for a branch

type ReleaseContext added in v1.1.12

type ReleaseContext struct {
	Repo                   *hitchgit.Repo
	Meta                   *metadata.Metadata
	UserEmail, UserName    string
	Processor              *core.DefaultBranchProcessor
	DependencyAnalyzer     *core.DependencyAnalyzer
	ReleaseMetadataManager *core.ReleaseMetadataManager
	ValidationManager      *core.ReleaseValidationManager
	ReleaseRecord          *core.ReleaseRecord
}

ReleaseContext holds all the initialized components needed for a release

type RepositoryInfo added in v0.1.21

type RepositoryInfo struct {
	Branches           map[string]BranchInfo      `json:"branches"`
	SortedBranches     []string                   `json:"sorted_branches"`
	Environments       map[string]EnvironmentInfo `json:"environments"`
	SortedEnvironments []string                   `json:"sorted_environments"`
}

RepositoryInfo contains repository status information

type TemplateVariable added in v1.1.12

type TemplateVariable struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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