git

package
v0.4.1-rc3 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package git provides a high-level client for interacting with Git repositories programmatically from Go applications. It abstracts the direct execution of 'git' command-line operations, offering a more Go-idiomatic API.

The primary entry point for using this package is the GitClient type, which is instantiated via the NewClient function. The client requires a working directory to determine the repository context and can be configured using GitClientConfig.

Key features include:

  • Repository context detection (finding .git and top-level directories).
  • Execution of common Git commands (status, commit, add, branch, etc.) through structured methods.
  • Abstraction over command execution, allowing for custom executors (primarily for testing).
  • Integration with structured logging via the slog package.

Usage Example:

// Assume globalLogger is an initialized *slog.Logger
ctx := context.Background()
workDir, _ := os.Getwd()

gitCfg := git.GitClientConfig{
	Logger: globalLogger,
	// Other configurations can be set here
}

client, err := git.NewClient(ctx, workDir, gitCfg)
if err != nil {
	log.Fatalf("Failed to create Git client: %v", err)
}

branch, err := client.GetCurrentBranchName(ctx)
if err != nil {
	log.Printf("Error getting branch: %v", err)
} else {
	log.Printf("Current branch: %s", branch)
}

Error Handling:

Methods on the GitClient typically return an error as their last argument if an operation fails. Errors can originate from underlying git command failures, invalid input, or issues with the repository state. It's important for callers to check these errors.

Logging:

The GitClient uses an slog.Logger instance provided via GitClientConfig. This allows for consistent, structured logging of its operations, which can be directed to various outputs (e.g., console, files, AI-consumable streams) by configuring the logger's handlers at the application level.

Testing:

The GitClient is designed with testability in mind. The GitClientConfig.Executor field allows injecting a mock 'executor' interface, enabling unit tests for client methods without relying on an actual 'git' executable or a live repository.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TruncateString

func TruncateString(input string, maxLen int) string

TruncateString helper can be removed if not used, or kept if useful elsewhere. For now, keeping it as it was in the provided file.

Types

type GitClient

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

GitClient provides methods for interacting with a Git repository.

func NewClient

func NewClient(ctx context.Context, workDir string, config GitClientConfig) (*GitClient, error)

NewClient creates and initializes a new GitClient. The GitClientConfig's Executor field should be pre-populated, or validateAndSetDefaults will create a default OSCommandExecutor.

func (*GitClient) AddAll

func (c *GitClient) AddAll(ctx context.Context) error

AddAll stages all changes.

func (*GitClient) Commit

func (c *GitClient) Commit(ctx context.Context, message string) error

Commit commits staged changes with a message.

func (*GitClient) CreateAndSwitchBranch

func (c *GitClient) CreateAndSwitchBranch(
	ctx context.Context,
	newBranchName string,
	baseBranch string,
) error

CreateAndSwitchBranch creates a new branch and switches to it.

func (*GitClient) GetCurrentBranchName

func (c *GitClient) GetCurrentBranchName(ctx context.Context) (string, error)

GetCurrentBranchName returns the name of the current branch.

func (*GitClient) GetDiffCached

func (c *GitClient) GetDiffCached(ctx context.Context) (string, string, error)

GetDiffCached returns the cached diff.

func (*GitClient) GetDiffUnstaged

func (c *GitClient) GetDiffUnstaged(ctx context.Context) (string, string, error)

GetDiffUnstaged returns the unstaged diff.

func (*GitClient) GetLogAndDiffFromMergeBase added in v0.2.1

func (c *GitClient) GetLogAndDiffFromMergeBase(
	ctx context.Context,
	baseBranchRef string,
) (log, diff string, err error)

GetLogAndDiffFromMergeBase finds the common ancestor with a branch and returns the log and diff since that point.

func (*GitClient) GetRemoteURL added in v0.2.1

func (c *GitClient) GetRemoteURL(ctx context.Context, remoteName string) (string, error)

GetRemoteURL retrieves the URL for a given remote name.

func (*GitClient) GetStatusShort

func (c *GitClient) GetStatusShort(ctx context.Context) (string, string, error)

GetStatusShort returns the short status of the repository.

func (*GitClient) GitDir

func (c *GitClient) GitDir() string

GitDir returns the .git directory path.

func (*GitClient) HasStagedChanges

func (c *GitClient) HasStagedChanges(ctx context.Context) (bool, error)

HasStagedChanges checks if there are staged changes.

func (*GitClient) IsBranchAhead

func (c *GitClient) IsBranchAhead(ctx context.Context) (bool, error)

IsBranchAhead checks if the local branch is ahead of the remote.

func (*GitClient) IsWorkingDirClean

func (c *GitClient) IsWorkingDirClean(ctx context.Context) (bool, error)

IsWorkingDirClean checks if the working directory is clean.

func (*GitClient) ListTrackedAndCachedFiles

func (c *GitClient) ListTrackedAndCachedFiles(ctx context.Context) (string, string, error)

ListTrackedAndCachedFiles returns a list of tracked and cached files.

func (*GitClient) ListUntrackedFiles

func (c *GitClient) ListUntrackedFiles(ctx context.Context) (string, string, error)

ListUntrackedFiles returns a list of untracked files.

func (*GitClient) LocalBranchExists

func (c *GitClient) LocalBranchExists(ctx context.Context, branchName string) (bool, error)

LocalBranchExists checks if a local branch exists.

func (*GitClient) Logger

func (c *GitClient) Logger() *slog.Logger

Logger returns the logger.

func (*GitClient) MainBranchName

func (c *GitClient) MainBranchName() string

MainBranchName returns the configured main branch name.

func (*GitClient) Path

func (c *GitClient) Path() string

Path returns the repository path.

func (*GitClient) PullRebase

func (c *GitClient) PullRebase(ctx context.Context, branch string) error

PullRebase pulls changes from the remote and rebases.

func (*GitClient) Push

func (c *GitClient) Push(ctx context.Context, branch string) error

Push pushes changes to the remote.

func (*GitClient) PushAndSetUpstream

func (c *GitClient) PushAndSetUpstream(ctx context.Context, branchName string) error

PushAndSetUpstream pushes the branch and sets the upstream.

func (*GitClient) RemoteName

func (c *GitClient) RemoteName() string

RemoteName returns the configured remote name.

func (*GitClient) StashPush added in v0.2.1

func (c *GitClient) StashPush(ctx context.Context) error

StashPush saves the current state of the working directory and the index, but leaves the working directory clean.

func (*GitClient) SwitchBranch

func (c *GitClient) SwitchBranch(ctx context.Context, branchName string) error

SwitchBranch switches to a branch.

type GitClientConfig

type GitClientConfig struct {
	GitExecutable         string
	DefaultRemoteName     string               // Will be set by cmd layer from LoadedAppConfig
	DefaultMainBranchName string               // Will be set by cmd layer from LoadedAppConfig
	Logger                *slog.Logger         // Logger for GitClient's own operations
	Executor              exec.CommandExecutor // Use the new CommandExecutor interface from internal/exec
}

GitClientConfig configures the GitClient.

Jump to

Keyboard shortcuts

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