git

package
v0.0.0-...-5b3f85d Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package git provides Git operations abstraction and utilities for repository management within the GZH Manager system.

This package defines interfaces and implementations for Git operations, enabling consistent repository management across different Git platforms and providing testable abstractions for Git functionality.

Key Components:

Git Interface:

  • Repository cloning and initialization
  • Branch and tag management
  • Commit and history operations
  • Remote repository management
  • Status and diff operations

Implementations:

  • LibGit2Repository: Git operations using libgit2
  • CommandLineGit: Git operations using git command
  • MockGitRepository: Generated mock for unit testing

Features:

  • Cross-platform Git operations
  • Authentication handling (SSH, HTTPS, tokens)
  • Progress tracking for long operations
  • Error handling and recovery
  • Repository state validation

Clone Strategies:

  • reset: Hard reset to remote state
  • pull: Merge remote changes with local
  • fetch: Update remote tracking only

Authentication Support:

  • SSH key authentication
  • Personal access tokens
  • Username/password authentication
  • Credential helper integration

Example usage:

repo := git.NewRepository(path)
err := repo.Clone(url, options)
status, err := repo.Status()
err = repo.Pull(strategy)

The abstraction enables consistent Git operations throughout the application while supporting comprehensive testing and different Git backend implementations.

Index

Constants

View Source
const (
	// StrategyReset performs a hard reset followed by pull.
	StrategyReset = "reset"
	// StrategyPull merges remote changes with local changes.
	StrategyPull  = "pull"
	StrategyFetch = "fetch"
)
View Source
const (
	RepoTypeNone   = "none"   // Not a Git repository
	RepoTypeEmpty  = "empty"  // Git repository with no commits
	RepoTypeNormal = "normal" // Git repository with commits
)

Repository type constants.

Variables

View Source
var AllowedGitCommands = map[string]bool{
	"clone":    true,
	"pull":     true,
	"fetch":    true,
	"reset":    true,
	"status":   true,
	"log":      true,
	"remote":   true,
	"config":   true,
	"branch":   true,
	"checkout": true,
}

AllowedGitCommands defines the whitelist of safe git commands

View Source
var AllowedGitOptions = map[string]bool{
	"--hard":           true,
	"--force":          true,
	"--quiet":          true,
	"--verbose":        true,
	"--progress":       true,
	"--prune":          true,
	"--all":            true,
	"--tags":           true,
	"--origin":         true,
	"--upstream":       true,
	"--set-upstream":   true,
	"--unset-upstream": true,
	"--depth":          true,
	"--shallow-depth":  true,
	"--single-branch":  true,
}

AllowedGitOptions defines safe git options

Functions

func CheckGitRepoType

func CheckGitRepoType(dir string) (string, error)

CheckGitRepoType checks the type of a Git repository. Returns "none" if not a Git repo, "empty" if no commits, "normal" if has commits.

func CheckoutBranch

func CheckoutBranch(ctx context.Context, repoPath, branch string) error

CheckoutBranch checks out a specific branch.

func GetCurrentBranch

func GetCurrentBranch(ctx context.Context, repoPath string) (string, error)

GetCurrentBranch gets the current branch name.

func GetRemoteURL

func GetRemoteURL(ctx context.Context, repoPath string) (string, error)

GetRemoteURL gets the remote URL for a repository.

func HasUncommittedChanges

func HasUncommittedChanges(ctx context.Context, repoPath string) (bool, error)

HasUncommittedChanges checks if the repository has uncommitted changes.

func IsGitRepository

func IsGitRepository(path string) bool

IsGitRepository checks if a directory is a git repository.

Types

type AuthConfig

type AuthConfig struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Token    string `json:"token"`
	SSHKey   string `json:"sshKey"`
}

AuthConfig represents authentication configuration.

type AuthManager

type AuthManager interface {
	// Configure SSH authentication
	ConfigureSSHAuth(ctx context.Context, keyPath, passphrase string) error

	// Configure token authentication
	ConfigureTokenAuth(ctx context.Context, token string) error

	// Configure username/password authentication
	ConfigurePasswordAuth(ctx context.Context, username, password string) error

	// Get current authentication method
	GetAuthMethod() string

	// Validate authentication
	ValidateAuth(ctx context.Context, remoteURL string) error
}

AuthManager defines the interface for Git authentication.

func NewAuthManager

func NewAuthManager(logger Logger) AuthManager

NewAuthManager creates a new auth manager with dependencies.

type AuthManagerImpl

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

AuthManagerImpl implements the AuthManager interface.

func (*AuthManagerImpl) ConfigurePasswordAuth

func (a *AuthManagerImpl) ConfigurePasswordAuth(ctx context.Context, username, password string) error

ConfigurePasswordAuth implements AuthManager interface.

func (*AuthManagerImpl) ConfigureSSHAuth

func (a *AuthManagerImpl) ConfigureSSHAuth(ctx context.Context, keyPath, passphrase string) error

ConfigureSSHAuth implements AuthManager interface.

func (*AuthManagerImpl) ConfigureTokenAuth

func (a *AuthManagerImpl) ConfigureTokenAuth(ctx context.Context, token string) error

ConfigureTokenAuth implements AuthManager interface.

func (*AuthManagerImpl) GetAuthMethod

func (a *AuthManagerImpl) GetAuthMethod() string

GetAuthMethod implements AuthManager interface.

func (*AuthManagerImpl) ValidateAuth

func (a *AuthManagerImpl) ValidateAuth(ctx context.Context, remoteURL string) error

ValidateAuth implements AuthManager interface.

type BulkOperation

type BulkOperation struct {
	Type     string                 `json:"type"` // clone, pull, fetch, reset
	Strategy string                 `json:"strategy,omitempty"`
	Options  map[string]interface{} `json:"options,omitempty"`
}

BulkOperation represents a bulk operation to execute.

type BulkOperator

type BulkOperator interface {
	// Execute operation on multiple repositories
	ExecuteBulkOperation(ctx context.Context, repoPaths []string, operation BulkOperation) ([]BulkResult, error)

	// Execute with concurrency control
	ExecuteBulkOperationWithOptions(ctx context.Context, repoPaths []string, operation BulkOperation, options BulkOptions) ([]BulkResult, error)

	// Get operation progress
	GetProgress() <-chan BulkProgress
}

BulkOperator defines the interface for bulk Git operations.

func NewBulkOperator

func NewBulkOperator(
	config *BulkOperatorConfig,
	gitClient Client,
	strategyExecutor StrategyExecutor,
	logger Logger,
) BulkOperator

NewBulkOperator creates a new bulk operator with dependencies.

type BulkOperatorConfig

type BulkOperatorConfig struct {
	Concurrency int
	Timeout     time.Duration
}

BulkOperatorConfig holds configuration for bulk operations.

func DefaultBulkOperatorConfig

func DefaultBulkOperatorConfig() *BulkOperatorConfig

DefaultBulkOperatorConfig returns default configuration.

type BulkOperatorImpl

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

BulkOperatorImpl implements the BulkOperator interface.

func (*BulkOperatorImpl) ExecuteBulkOperation

func (b *BulkOperatorImpl) ExecuteBulkOperation(ctx context.Context, repoPaths []string, operation BulkOperation) ([]BulkResult, error)

ExecuteBulkOperation implements BulkOperator interface.

func (*BulkOperatorImpl) ExecuteBulkOperationWithOptions

func (b *BulkOperatorImpl) ExecuteBulkOperationWithOptions(ctx context.Context, repoPaths []string, operation BulkOperation, options BulkOptions) ([]BulkResult, error)

ExecuteBulkOperationWithOptions implements BulkOperator interface.

func (*BulkOperatorImpl) GetProgress

func (b *BulkOperatorImpl) GetProgress() <-chan BulkProgress

GetProgress implements BulkOperator interface.

type BulkOptions

type BulkOptions struct {
	Concurrency      int                `json:"concurrency"`
	Timeout          time.Duration      `json:"timeout"`
	ContinueOnError  bool               `json:"continueOnError"`
	ProgressCallback func(BulkProgress) `json:"-"`
}

BulkOptions represents options for bulk operations.

type BulkProgress

type BulkProgress struct {
	TotalRepos      int           `json:"totalRepos"`
	CompletedRepos  int           `json:"completedRepos"`
	SuccessfulRepos int           `json:"successfulRepos"`
	FailedRepos     int           `json:"failedRepos"`
	CurrentRepo     string        `json:"currentRepo"`
	ElapsedTime     time.Duration `json:"elapsedTime"`
	EstimatedTime   time.Duration `json:"estimatedTime"`
}

BulkProgress represents progress information for bulk operations.

type BulkResult

type BulkResult struct {
	RepoPath string           `json:"repoPath"`
	Success  bool             `json:"success"`
	Result   *OperationResult `json:"result,omitempty"`
	Error    string           `json:"error,omitempty"`
	Duration time.Duration    `json:"duration"`
}

BulkResult represents the result of a bulk operation on a repository.

type Client

type Client interface {
	// Repository operations
	Clone(ctx context.Context, options CloneOptions) (*OperationResult, error)
	Pull(ctx context.Context, repoPath string, options PullOptions) (*OperationResult, error)
	Fetch(ctx context.Context, repoPath string, remote string) (*OperationResult, error)
	Reset(ctx context.Context, repoPath string, options ResetOptions) (*OperationResult, error)

	// Repository status
	GetRepository(ctx context.Context, path string) (*Repository, error)
	IsRepository(ctx context.Context, path string) bool
	IsDirty(ctx context.Context, repoPath string) (bool, error)
	GetCurrentBranch(ctx context.Context, repoPath string) (string, error)
	GetDefaultBranch(ctx context.Context, repoPath string) (string, error)

	// Branch operations
	ListBranches(ctx context.Context, repoPath string) ([]string, error)
	CreateBranch(ctx context.Context, repoPath, branchName string) (*OperationResult, error)
	CheckoutBranch(ctx context.Context, repoPath, branchName string) (*OperationResult, error)
	DeleteBranch(ctx context.Context, repoPath, branchName string) (*OperationResult, error)

	// Remote operations
	ListRemotes(ctx context.Context, repoPath string) (map[string]string, error)
	AddRemote(ctx context.Context, repoPath, name, url string) (*OperationResult, error)
	RemoveRemote(ctx context.Context, repoPath, name string) (*OperationResult, error)
	SetRemoteURL(ctx context.Context, repoPath, remote, url string) (*OperationResult, error)

	// Commit operations
	GetLastCommit(ctx context.Context, repoPath string) (*Commit, error)
	GetCommitHistory(ctx context.Context, repoPath string, limit int) ([]Commit, error)

	// Utility operations
	ValidateRepository(ctx context.Context, path string) error
	GetStatus(ctx context.Context, repoPath string) (*StatusResult, error)
}

Client defines the interface for Git operations.

func NewClient

func NewClient(config *ClientConfig, executor CommandExecutor, logger Logger) Client

NewClient creates a new Git client with dependencies.

type ClientConfig

type ClientConfig struct {
	Timeout       time.Duration
	RetryCount    int
	RetryDelay    time.Duration
	DefaultBranch string
}

ClientConfig holds configuration for Git client.

func DefaultClientConfig

func DefaultClientConfig() *ClientConfig

DefaultClientConfig returns default configuration.

type ClientImpl

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

ClientImpl implements the Client interface.

func (*ClientImpl) AddRemote

func (g *ClientImpl) AddRemote(ctx context.Context, repoPath, name, url string) (*OperationResult, error)

AddRemote implements Client interface.

func (*ClientImpl) CheckoutBranch

func (g *ClientImpl) CheckoutBranch(_ context.Context, repoPath, branch string) (*OperationResult, error)

CheckoutBranch implements Client interface.

func (*ClientImpl) Clone

func (g *ClientImpl) Clone(ctx context.Context, options CloneOptions) (*OperationResult, error)

Clone implements Client interface.

func (*ClientImpl) CreateBranch

func (g *ClientImpl) CreateBranch(_ context.Context, repoPath, branchName string) (*OperationResult, error)

CreateBranch implements Client interface.

func (*ClientImpl) DeleteBranch

func (g *ClientImpl) DeleteBranch(ctx context.Context, repoPath, branchName string) (*OperationResult, error)

DeleteBranch implements Client interface.

func (*ClientImpl) Fetch

func (g *ClientImpl) Fetch(ctx context.Context, repoPath string, remote string) (*OperationResult, error)

Fetch implements Client interface.

func (*ClientImpl) GetCommitHistory

func (g *ClientImpl) GetCommitHistory(ctx context.Context, repoPath string, limit int) ([]Commit, error)

GetCommitHistory implements Client interface.

func (*ClientImpl) GetCurrentBranch

func (g *ClientImpl) GetCurrentBranch(ctx context.Context, repoPath string) (string, error)

GetCurrentBranch implements Client interface.

func (*ClientImpl) GetDefaultBranch

func (g *ClientImpl) GetDefaultBranch(_ context.Context, repoPath string) (string, error)

GetDefaultBranch implements Client interface.

func (*ClientImpl) GetLastCommit

func (g *ClientImpl) GetLastCommit(ctx context.Context, repoPath string) (*Commit, error)

GetLastCommit implements Client interface.

func (*ClientImpl) GetRepository

func (g *ClientImpl) GetRepository(_ context.Context, path string) (*Repository, error)

GetRepository implements Client interface.

func (*ClientImpl) GetStatus

func (g *ClientImpl) GetStatus(ctx context.Context, repoPath string) (*StatusResult, error)

GetStatus implements Client interface.

func (*ClientImpl) IsDirty

func (g *ClientImpl) IsDirty(ctx context.Context, repoPath string) (bool, error)

IsDirty implements Client interface.

func (*ClientImpl) IsRepository

func (g *ClientImpl) IsRepository(ctx context.Context, path string) bool

IsRepository implements Client interface.

func (*ClientImpl) ListBranches

func (g *ClientImpl) ListBranches(_ context.Context, repoPath string) ([]string, error)

ListBranches implements Client interface.

func (*ClientImpl) ListRemotes

func (g *ClientImpl) ListRemotes(ctx context.Context, repoPath string) (map[string]string, error)

ListRemotes implements Client interface.

func (*ClientImpl) Pull

func (g *ClientImpl) Pull(ctx context.Context, repoPath string, options PullOptions) (*OperationResult, error)

Pull implements Client interface.

func (*ClientImpl) RemoveRemote

func (g *ClientImpl) RemoveRemote(ctx context.Context, repoPath, name string) (*OperationResult, error)

RemoveRemote implements Client interface.

func (*ClientImpl) Reset

func (g *ClientImpl) Reset(ctx context.Context, repoPath string, options ResetOptions) (*OperationResult, error)

Reset implements Client interface.

func (*ClientImpl) SetRemoteURL

func (g *ClientImpl) SetRemoteURL(ctx context.Context, repoPath, remote, url string) (*OperationResult, error)

SetRemoteURL implements Client interface.

func (*ClientImpl) ValidateRepository

func (g *ClientImpl) ValidateRepository(ctx context.Context, path string) error

ValidateRepository implements Client interface.

type CloneOptions

type CloneOptions struct {
	URL          string `json:"url"`
	Path         string `json:"path"`
	Branch       string `json:"branch,omitempty"`
	Depth        int    `json:"depth,omitempty"`
	SingleBranch bool   `json:"singleBranch"`
	Bare         bool   `json:"bare"`
	Mirror       bool   `json:"mirror"`
	Recursive    bool   `json:"recursive"`
	SSHKeyPath   string `json:"sshKeyPath,omitempty"`
	Token        string `json:"token,omitempty"`
}

CloneOptions represents options for cloning a repository.

type CommandExecutor

type CommandExecutor interface {
	Execute(ctx context.Context, command string, args ...string) ([]byte, error)
	ExecuteInDir(ctx context.Context, dir, command string, args ...string) ([]byte, error)
}

CommandExecutor interface for dependency injection.

type Commit

type Commit struct {
	Hash      string    `json:"hash"`
	ShortHash string    `json:"shortHash"`
	Author    string    `json:"author"`
	Email     string    `json:"email"`
	Message   string    `json:"message"`
	Date      time.Time `json:"date"`
}

Commit represents a Git commit.

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 OperationResult

type OperationResult struct {
	Success      bool              `json:"success"`
	Message      string            `json:"message"`
	Error        string            `json:"error,omitempty"`
	Duration     time.Duration     `json:"duration"`
	ChangedFiles []string          `json:"changedFiles,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

OperationResult represents the result of a Git operation.

type Operations

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

Operations provides common git operations.

func NewOperations

func NewOperations(verbose bool) *Operations

NewOperations creates a new git operations handler.

func (*Operations) Clone

func (o *Operations) Clone(ctx context.Context, cloneURL, targetPath string) error

Clone clones a repository to the specified path.

func (*Operations) ExecuteStrategy

func (o *Operations) ExecuteStrategy(ctx context.Context, repoPath string, strategy gitplatform.CloneStrategy) error

ExecuteStrategy executes the specified git strategy in the repository path.

type PullOptions

type PullOptions struct {
	Remote     string `json:"remote"`
	Branch     string `json:"branch,omitempty"`
	Strategy   string `json:"strategy"` // merge, rebase, fast-forward
	Force      bool   `json:"force"`
	AllowDirty bool   `json:"allowDirty"`
}

PullOptions represents options for pulling changes.

type Repository

type Repository struct {
	Path          string            `json:"path"`
	RemoteURL     string            `json:"remoteUrl"`
	CurrentBranch string            `json:"currentBranch"`
	DefaultBranch string            `json:"defaultBranch"`
	Remotes       map[string]string `json:"remotes"`
	IsDirty       bool              `json:"isDirty"`
	IsDetached    bool              `json:"isDetached"`
	LastCommit    *Commit           `json:"lastCommit,omitempty"`
}

Repository represents a Git repository.

type ResetOptions

type ResetOptions struct {
	Mode   string `json:"mode"`   // soft, mixed, hard
	Target string `json:"target"` // commit hash, branch, tag
	Force  bool   `json:"force"`
}

ResetOptions represents options for resetting repository state.

type SecureGitExecutor

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

SecureGitExecutor provides safe git command execution with input validation

func NewSecureGitExecutor

func NewSecureGitExecutor() (*SecureGitExecutor, error)

NewSecureGitExecutor creates a new secure git executor

func (*SecureGitExecutor) Execute

Execute executes a validated git command

func (*SecureGitExecutor) ExecuteSecure

func (e *SecureGitExecutor) ExecuteSecure(ctx context.Context, repoPath string, args ...string) error

ExecuteSecure validates and executes a git command in one call

func (*SecureGitExecutor) GetGitVersion

func (e *SecureGitExecutor) GetGitVersion(ctx context.Context) (string, error)

GetGitVersion returns the git version for diagnostics

func (*SecureGitExecutor) ValidateCommand

func (e *SecureGitExecutor) ValidateCommand(repoPath string, args ...string) (*ValidatedGitCommand, error)

ValidateCommand validates git command arguments against allowlists

type Service

type Service interface {
	Client
	StrategyExecutor
	BulkOperator
	AuthManager
}

Service provides a unified interface for all Git operations.

func NewService

func NewService(
	config *ServiceConfig,
	executor CommandExecutor,
	logger Logger,
) Service

NewService creates a new Git service with all dependencies.

type ServiceConfig

type ServiceConfig struct {
	Client     *ClientConfig
	BulkOp     *BulkOperatorConfig
	EnableAuth bool
}

ServiceConfig holds configuration for the Git service.

func DefaultServiceConfig

func DefaultServiceConfig() *ServiceConfig

DefaultServiceConfig returns default configuration.

type ServiceDependencies

type ServiceDependencies struct {
	Executor CommandExecutor
	Logger   Logger
}

ServiceDependencies holds all the dependencies needed for Git services.

func NewServiceDependencies

func NewServiceDependencies(executor CommandExecutor, logger Logger) *ServiceDependencies

NewServiceDependencies creates a default set of service dependencies.

type ServiceImpl

type ServiceImpl struct {
	Client
	StrategyExecutor
	BulkOperator
	AuthManager
}

ServiceImpl implements the unified Git service interface.

type StatusResult

type StatusResult struct {
	Clean          bool     `json:"clean"`
	Branch         string   `json:"branch"`
	Ahead          int      `json:"ahead"`
	Behind         int      `json:"behind"`
	ModifiedFiles  []string `json:"modifiedFiles"`
	StagedFiles    []string `json:"stagedFiles"`
	UntrackedFiles []string `json:"untrackedFiles"`
	ConflictFiles  []string `json:"conflictFiles"`
}

StatusResult represents the status of a Git repository.

type StrategyExecutor

type StrategyExecutor interface {
	// Execute strategy on a repository
	ExecuteStrategy(ctx context.Context, repoPath, strategy string) (*OperationResult, error)

	// Get supported strategies
	GetSupportedStrategies() []string

	// Validate strategy
	IsValidStrategy(strategy string) bool

	// Get strategy description
	GetStrategyDescription(strategy string) string
}

StrategyExecutor defines the interface for executing different Git strategies.

func NewStrategyExecutor

func NewStrategyExecutor(gitClient Client, logger Logger) StrategyExecutor

NewStrategyExecutor creates a new strategy executor with dependencies.

type StrategyExecutorImpl

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

StrategyExecutorImpl implements the StrategyExecutor interface.

func (*StrategyExecutorImpl) ExecuteStrategy

func (s *StrategyExecutorImpl) ExecuteStrategy(ctx context.Context, repoPath, strategy string) (*OperationResult, error)

ExecuteStrategy implements StrategyExecutor interface.

func (*StrategyExecutorImpl) GetStrategyDescription

func (s *StrategyExecutorImpl) GetStrategyDescription(strategy string) string

GetStrategyDescription implements StrategyExecutor interface.

func (*StrategyExecutorImpl) GetSupportedStrategies

func (s *StrategyExecutorImpl) GetSupportedStrategies() []string

GetSupportedStrategies implements StrategyExecutor interface.

func (*StrategyExecutorImpl) IsValidStrategy

func (s *StrategyExecutorImpl) IsValidStrategy(strategy string) bool

IsValidStrategy implements StrategyExecutor interface.

func (*StrategyExecutorImpl) ValidateStrategy

func (s *StrategyExecutorImpl) ValidateStrategy(strategy string) error

ValidateStrategy implements StrategyExecutor interface.

type ValidatedGitCommand

type ValidatedGitCommand struct {
	Command  string
	Args     []string
	RepoPath string
	Options  []string
}

ValidatedGitCommand represents a validated git command

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
provider

Jump to

Keyboard shortcuts

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