gogit

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 15 Imported by: 1

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

gogit

Enhanced Git operations toolkit providing streamlined repo management with comprehensive commit and remote sync capabilities.


CHINESE README

中文说明

Core Features

🎯 Streamlined Git Operations: Intelligent staging, committing, and status checking with comprehensive API ⚡ Smart Commit Management: Auto staging with commit and amend support, prevents unsafe operations 🔄 Remote Push Detection: Automatic checking of commit push status across multiple remotes 🌍 Cross-Platform Support: Pure Go implementation without CLI dependencies using go-git foundation 📋 Fluent API Design: Builder pattern for convenient configuration and method chaining

  • gitgo - Streamlined Git command execution engine with fluent chaining interface, using os/exec to run Git CLI commands
  • gogit (this project) - Enhanced Git operations toolkit with go-git foundation, providing pure Go implementation

Installation

go get github.com/yylego/gogit

Quick Start

Basic Usage
package main

import (
    "fmt"
    "log"

    "github.com/yylego/gogit"
)

func main() {
    // Initialize Git client
    client, err := gogit.New("/path/to/your/repo")
    if err != nil {
        log.Fatal(err)
    }

    // Stage all changes
    err = client.AddAll()
    if err != nil {
        log.Fatal(err)
    }

    // Create commit info with fluent API
    commitInfo := gogit.NewCommitInfo("Initial commit").
        WithName("Your Name").
        WithMailbox("your.mailbox@example.com")

    // Commit changes
    hash, err := client.CommitAll(commitInfo)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Commit created: %s\n", hash)
}
Advanced Features
// Check repository status
status, err := client.Status()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Repository status: %+v\n", status)

// Amend last commit (with safety check)
amendConfig := &gogit.AmendConfig{
    CommitInfo: gogit.NewCommitInfo("Updated commit message").
        WithName("Updated Name").
        WithMailbox("updated.mailbox@example.com"),
    ForceAmend: false, // Prevents amending pushed commits
}

hash, err := client.AmendCommit(amendConfig)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Amended commit: %s\n", hash)

// Check if latest commit was pushed to remote
pushed, err := client.IsLatestCommitPushed()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Latest commit pushed: %t\n", pushed)

API Reference

Core Methods
  • gogit.New(root string) (*Client, error) Creates a new Git client for the specified repo path with ignore file support

  • client.AddAll() error Stages all changes including new files, modifications, and deletions

  • client.Status() (git.Status, error) Returns current worktree status with comprehensive file change info

  • client.CommitAll(info *CommitInfo) (string, error) Commits all staged changes with provided creator signature and message

  • client.AmendCommit(cfg *AmendConfig) (string, error) Amends the last commit with safety checks for pushed commits

  • client.IsLatestCommitPushed() (bool, error) Checks if current branch has been pushed to any configured remote

  • client.IsLatestCommitPushedToRemote(name string) (bool, error) Checks push status against a specific remote repo

  • client.GetCurrentBranch() (string, error) Returns the name of the current branch

  • client.GetLatestCommit() (*object.Commit, error) Returns the latest commit object with message and author info

  • client.HasChanges() (bool, error) Checks if the repo has uncommitted changes

  • client.GetRemoteURL(name string) (string, error) Returns the URL for the specified remote

  • client.GetFirstRemoteURL() (string, error) Returns the URL of the first available remote

Configuration Types
// CommitInfo - Fluent commit configuration
type CommitInfo struct {
    Name    string // Creator name for Git commits
    Mailbox string // Creator mailbox for Git commits
    Message string // Commit message content
}

// AmendConfig - Amend operation configuration
type AmendConfig struct {
    CommitInfo *CommitInfo // New commit info for amend operation
    ForceAmend bool        // Allow amend even if commit was pushed
}
Fluent API Examples
// Create commit info with method chaining
commitInfo := gogit.NewCommitInfo("Feature implementation").
    WithName("Developer Name").
    WithMailbox("dev@company.com")

// Use default message generation if no message provided
commitInfo := gogit.NewCommitInfo("").
    WithName("Auto Account").
    WithMailbox("auto@example.com")
// Generates timestamp-based message: "[gogit](github.com/yylego/gogit) 2024-01-15 14:30:45"

Safety Features

  • Push Detection: Prevents amending commits that have been pushed to remote repos
  • Ignore File Support: Respects .gitignore patterns during operations
  • Empty Commit Handling: Returns empty string for no-change commits
  • Error Context: Comprehensive error wrapping with context info
  • Hash Verification: Validates commit integrity after operations

Best Practices

// Always check for errors
client, err := gogit.New("/path/to/repo")
if err != nil {
    return fmt.Errorf("failed to create client: %w", err)
}

// Use fluent API for clean configuration
info := gogit.NewCommitInfo("Fix critical bug").
    WithName("Bug Fixer").
    WithMailbox("fixer@company.com")

// Check push status before amending
if pushed, _ := client.IsLatestCommitPushed(); pushed {
    log.Println("Warning: Cannot amend pushed commit")
} else {
    // Safe to amend
    hash, err := client.AmendCommit(&gogit.AmendConfig{
        CommitInfo: info,
        ForceAmend: false,
    })
}

📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Documentation

Overview

Package gogit: Enhanced Git operations toolkit with streamlined repo management Delivers intelligent Git functions with comprehensive commit, amend, and remote sync capabilities Automatic staging, status tracking, and commit hash validation with remote push detection included Built on go-git package, provides cross-platform Git operations without CLI dependencies

gogit: 增强的 Git 操作工具包,提供简化的仓库管理 提供智能 Git 功能,包含全面的提交、修正和远程同步能力 包含自动暂存、状态跟踪和提交哈希验证,支持远程推送检测 基于 go-git 库构建,提供跨平台 Git 操作,无需 CLI 依赖

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AmendConfig

type AmendConfig struct {
	CommitInfo *CommitInfo // New commit info for amend operation // 修正操作的新提交信息
	ForceAmend bool        // Allow amend even if commit was pushed // 即使提交已推送也允许修正
}

AmendConfig represents settings used when amending commits Contains commit info and amend-pushed flag

AmendConfig 代表修正提交时使用的配置 包含提交信息和强制修正已推送提交的标志

type Client

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

Client represents a Git repo client with enhanced operations Encapsulates repo and worktree to streamline Git management Provides advanced interface with robust exception handling

Client 代表具有增强操作的 Git 仓库客户端 封装仓库和工作树以简化 Git 管理 提供高级接口,带有健壮的异常处理

func New

func New(root string) (*Client, error)

New initializes a Git client at the specified project root path Opens existing repo and creates worktree with ignore file support Returns configured client available to use

New 在指定的项目根路径初始化 Git 客户端 打开现有仓库并创建支持忽略文件的工作树 返回配置好的客户端,可以直接使用

func NewClient

func NewClient(repo *git.Repository, tree *git.Worktree) *Client

NewClient creates a new Git client with specified repo and worktree Combines repo and worktree to enable comprehensive Git operations Worktree should include suitable ignore file settings to optimize speed

NewClient 使用指定的仓库和工作树创建新的 Git 客户端 结合仓库和工作树以启用全面的 Git 操作 工作树应包含适当的忽略文件配置以优化速度

func (*Client) AddAll

func (c *Client) AddAll() error

AddAll stages changes including new files, modifications and deletions Equivalent to 'git add --all' operation with comprehensive change detection Fails with an issue when the staging operation encounters problems

AddAll 暂存更改,包括新文件、修改和删除 等同于 'git add --all' 操作,具有全面的更改检测 当暂存操作遇到问题时返回错误

func (*Client) AmendCommit

func (c *Client) AmendCommit(cfg *AmendConfig) (string, error)

AmendCommit amends the previous commit with new info Modifies the last commit with updated message, signature, and staged changes Blocks amending pushed commits unless ForceAmend is enabled

AmendCommit 使用新信息修正上一个提交 使用更新的消息、签名和已暂存的更改修改最后一个提交 除非启用 ForceAmend,否则阻止修正已推送的提交

func (*Client) CommitAll

func (c *Client) CommitAll(info *CommitInfo) (string, error)

CommitAll commits staged changes with the provided commit info Creates a new commit with staged files and applies specified signature Returns commit hash string, blank string when no changes exist

CommitAll 使用提供的提交信息提交已暂存的更改 创建包含已暂存文件的新提交并应用指定的签名 返回提交哈希字符串,无更改时返回空字符串

func (*Client) GetCurrentBranch

func (c *Client) GetCurrentBranch() (string, error)

GetCurrentBranch returns the name of the current branch Extracts branch name from HEAD to enable convenient access Returns short branch name such as "main" and "feature/xxx"

GetCurrentBranch 返回当前分支的名称 从 HEAD 提取分支名称以便于访问 返回短分支名称,如 "main" 和 "feature/xxx"

func (*Client) GetFirstRemoteURL

func (c *Client) GetFirstRemoteURL() (string, error)

GetFirstRemoteURL returns the URL of the first available remote Returns error when no remotes exist or no URLs configured Returns error when fetching remotes fails

GetFirstRemoteURL 返回第一个可用远程的 URL 当没有远程或未配置 URL 时返回错误 当获取远程失败时返回错误

func (*Client) GetLatestCommit

func (c *Client) GetLatestCommit() (*object.Commit, error)

GetLatestCommit returns the latest commit object from HEAD Retrieves HEAD commit to inspect details such as message, signature, and timestamp Returns complete commit object with metadata included

GetLatestCommit 返回 HEAD 的最新提交对象 获取 HEAD 提交以检查详情,如消息、签名和时间戳 返回包含元数据的完整提交对象

func (*Client) GetRemoteURL

func (c *Client) GetRemoteURL(remoteName string) (string, error)

GetRemoteURL returns the URL of the specified remote Retrieves URL from remote config using the given name Returns error when remote not found or has no URLs configured

GetRemoteURL 返回指定远程的 URL 使用给定名称从远程配置获取 URL 未找到远程或未配置 URL 时返回错误

func (*Client) HasChanges

func (c *Client) HasChanges() (bool, error)

HasChanges checks if uncommitted changes exist in the worktree Returns true when staged, modified, and untracked files exist Enables quick check to determine if commit is needed

HasChanges 检查工作树中是否存在未提交的更改 当存在已暂存、已修改和未跟踪的文件时返回 true 提供快速检查以确定是否需要提交

func (*Client) IsLatestCommitPushed

func (c *Client) IsLatestCommitPushed() (bool, error)

IsLatestCommitPushed checks if HEAD has been pushed to configured remotes Iterates through remotes and checks matching commit hashes Returns true when HEAD exists in some remote, false when not pushed

IsLatestCommitPushed 检查 HEAD 是否已推送到配置的远程 遍历远程并检查匹配的提交哈希 当 HEAD 存在于某个远程时返回 true,未推送时返回 false

func (*Client) IsLatestCommitPushedToRemote

func (c *Client) IsLatestCommitPushedToRemote(remoteName string) (bool, error)

IsLatestCommitPushedToRemote checks if HEAD has been pushed to specified remote Compares HEAD hash with remote branch hash to decide push status Returns true when hashes match, false when remote branch not found

IsLatestCommitPushedToRemote 检查 HEAD 是否已推送到指定的远程 比较 HEAD 哈希与远程分支哈希来判断推送状态 哈希匹配时返回 true,未找到远程分支时返回 false

func (*Client) Must

func (c *Client) Must() *Client88Must

func (*Client) Repo

func (c *Client) Repo() *git.Repository

Repo returns the underlying Git repo instance Enables access to basic repo operations when needed

Repo 返回底层的 Git 仓库实例 在需要时提供对基础仓库操作的访问

func (*Client) Status

func (c *Client) Status() (git.Status, error)

Status returns the current status of the worktree with file change information Provides comprehensive status including staged, modified, and untracked files Returns git.Status map with file paths and corresponding change status

Status 返回工作树的当前状态及文件更改信息 提供全面的状态,包括已暂存、已修改和未跟踪的文件 返回包含文件路径及其相应更改状态的 git.Status 映射

func (*Client) Tree

func (c *Client) Tree() *git.Worktree

Tree returns the Git worktree used in file operations Enables direct worktree manipulation when needed

Tree 返回用于文件操作的 Git 工作树 在需要时支持直接操作工作树

type Client88Must

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

func (*Client88Must) AddAll

func (T *Client88Must) AddAll()

func (*Client88Must) AmendCommit

func (T *Client88Must) AmendCommit(cfg *AmendConfig) (res string)

func (*Client88Must) CommitAll

func (T *Client88Must) CommitAll(info *CommitInfo) (res string)

func (*Client88Must) GetCurrentBranch

func (T *Client88Must) GetCurrentBranch() (res string)

func (*Client88Must) GetFirstRemoteURL

func (T *Client88Must) GetFirstRemoteURL() (res string)

func (*Client88Must) GetLatestCommit

func (T *Client88Must) GetLatestCommit() (res *object.Commit)

func (*Client88Must) GetRemoteURL

func (T *Client88Must) GetRemoteURL(remoteName string) (res string)

func (*Client88Must) HasChanges

func (T *Client88Must) HasChanges() (res bool)

func (*Client88Must) IsLatestCommitPushed

func (T *Client88Must) IsLatestCommitPushed() (res bool)

func (*Client88Must) IsLatestCommitPushedToRemote

func (T *Client88Must) IsLatestCommitPushedToRemote(remoteName string) (res bool)

func (*Client88Must) Repo

func (T *Client88Must) Repo() (res *git.Repository)

func (*Client88Must) Status

func (T *Client88Must) Status() (res git.Status)

func (*Client88Must) Tree

func (T *Client88Must) Tree() (res *git.Worktree)

type CommitInfo

type CommitInfo struct {
	Name    string // Author name for Git commits // 用于 Git 提交的作者姓名
	Mailbox string // Author mailbox for Git commits // 用于 Git 提交的作者邮箱地址
	Message string // Commit message content // 提交消息内容
}

CommitInfo represents Git commit authorship info and message content Contains authorship details and commit message used in Git operations Supports fluent pattern enabling convenient configuration

CommitInfo 代表 Git 提交署名信息和消息内容 包含署名详情和用于 Git 操作的提交消息 支持构建器模式以便于配置

func NewCommitInfo

func NewCommitInfo(message string) *CommitInfo

NewCommitInfo creates a new CommitInfo instance with specified message Initializes commit info with provided message, leaving fields blank to be configured Returns CommitInfo instance that enables fluent pattern chaining

NewCommitInfo 使用指定消息创建新的 CommitInfo 实例 使用提供的消息初始化提交信息,留空字段以便后续配置 返回支持构建器模式链式调用的 CommitInfo 实例

func (*CommitInfo) BuildCommitMessage

func (c *CommitInfo) BuildCommitMessage() string

BuildCommitMessage generates commit message using provided content or creates default message Returns custom message if available, otherwise generates timestamp-based default message Default format includes package name, path, and current timestamp

BuildCommitMessage 使用提供的内容生成提交消息或创建默认消息 如果有自定义消息则返回,否则生成基于时间戳的默认消息 默认格式包含包名、路径和当前时间戳

func (*CommitInfo) GetObjectSignature

func (c *CommitInfo) GetObjectSignature() *object.Signature

GetObjectSignature creates Git signature object used in commit operations Builds object.Signature with name, mailbox, and current timestamp Uses package defaults when info is not provided

GetObjectSignature 创建用于提交操作的 Git 签名对象 使用姓名、邮箱地址和当前时间戳构建 object.Signature 在未提供信息时使用包默认值

func (*CommitInfo) WithMailbox

func (c *CommitInfo) WithMailbox(mailbox string) *CommitInfo

WithMailbox sets the mailbox and returns the updated CommitInfo instance Configures mailbox used in Git commit signatures Supports fluent pattern chaining enabling convenient configuration

WithMailbox 设置邮箱地址并返回更新的 CommitInfo 实例 配置 Git 提交签名中使用的邮箱地址 支持构建器模式链式调用以启用便捷配置

func (*CommitInfo) WithMessage

func (c *CommitInfo) WithMessage(message string) *CommitInfo

WithMessage sets the commit message content and returns the updated CommitInfo instance Replaces any existing message with the provided content Enables fluent configuration through method pattern chaining

WithMessage 设置提交消息内容并返回更新的 CommitInfo 实例 使用提供的内容替换任何现有消息 通过构建器模式链式调用实现流畅配置

func (*CommitInfo) WithName

func (c *CommitInfo) WithName(name string) *CommitInfo

WithName sets the name and returns the updated CommitInfo instance Enables fluent method pattern supporting configuration chaining Name represents the Git name displayed in commit records

WithName 设置姓名并返回更新的 CommitInfo 实例 支持流畅的构建器模式以便于配置链式调用 Name 代表在提交历史中显示的 Git 姓名

Directories

Path Synopsis
Package gogitassist: Git repo initialization and worktree management assistance Provides support functions for creating Git repos and configuring worktree with ignore patterns Features system-wide, shared, and project-wide gitignore pattern loading and application
Package gogitassist: Git repo initialization and worktree management assistance Provides support functions for creating Git repos and configuring worktree with ignore patterns Features system-wide, shared, and project-wide gitignore pattern loading and application
Package gogitchange: Git changed files detection and processing toolkit Provides utilities for identifying, filtering, and processing changed files in Git worktree Features customizable matching options and file processing capabilities for changed files
Package gogitchange: Git changed files detection and processing toolkit Provides utilities for identifying, filtering, and processing changed files in Git worktree Features customizable matching options and file processing capabilities for changed files

Jump to

Keyboard shortcuts

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