### Install Static Libgit2 for Git2go Source: https://github.com/libgit2/git2go/blob/main/README.md Use this command to get libgit2 and install it statically into git2go. Ensure submodules are updated first. ```bash git submodule update --init make install-static ``` -------------------------------- ### Get Repository Working Directory Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Retrieves the working directory path of the repository. Example shows printing the path. ```go func (v *Repository) WorkDir() string ``` ```go workdir := repo.WorkDir() fmt.Println(workdir) // /path/to/repo ``` -------------------------------- ### Get HEAD Reference Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Retrieves the HEAD reference of the repository. Example shows getting the target of the HEAD reference. ```go func (v *Repository) Head() (*Reference, error) ``` ```go head, err := repo.Head() if err != nil { log.Fatal(err) } defer head.Free() target := head.Target() ``` -------------------------------- ### Create and Switch Git Branches Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md This example demonstrates creating a new branch pointing to a specific commit and then switching to that branch using checkout. ```go // Create branch ref, err := repo.References.Create( "refs/heads/feature", commitOid, false, "Created feature branch", ) // Switch branch err = repo.CheckoutRef(ref, nil) ``` -------------------------------- ### Get Repository Path Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Returns the path to the .git directory of the repository. ```go func (v *Repository) Path() string ``` -------------------------------- ### Fetch Changes from Remote Source: https://github.com/libgit2/git2go/blob/main/_autodocs/quick-reference.md Fetch updates from a remote repository. This example configures credentials for authentication during the fetch operation. ```go remote, _ := repo.Remotes.Lookup("origin") deferr remote.Free() remote.Fetch(nil, &git.FetchOptions{ Callbacks: &git.RemoteCallbacks{ CredentialsCallback: func(url, user string, allowed git.CredentialType) (*git.Credential, error) { return git.NewCredentialSSHKeyFromAgent("git") }, }, }) ``` -------------------------------- ### Get Repository Configuration Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Retrieves the configuration object for a repository. The configuration object should be freed when no longer needed. ```Go cfg, err := repo.Config() if err != nil { log.Fatal(err) } defers cfg.Free() // Read configuration values ``` -------------------------------- ### Build with static linking flags Source: https://github.com/libgit2/git2go/blob/main/README.md To statically link against libgit2, pass the `-tags static,system_libgit2` flag to Go build commands. This applies to building, testing, and installing. ```go go build -tags static,system_libgit2 github.com/my/project/... ``` ```go go test -tags static,system_libgit2 github.com/my/project/... ``` ```go go install -tags static,system_libgit2 github.com/my/project/... ``` -------------------------------- ### Get Repository State Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Returns the current state of the repository, such as merge or rebase in progress. ```go func (v *Repository) State() RepositoryState ``` -------------------------------- ### Discover Git Repository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Discovers a Git repository starting from a given path. Specify search boundaries and whether to search across filesystem boundaries. ```go func Discover(start string, across_fs bool, ceiling_dirs []string) (string, error) ``` ```go gitDir, err := git.Discover("/path/to/file", false, []string{"/home"}) if err != nil { log.Fatal(err) } fmt.Println(gitDir) ``` -------------------------------- ### Discover Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Discovers a git repository starting from a given path. This function searches for a .git directory. ```APIDOC ## Discover ### Description Discovers a git repository starting from a given path. This function searches for a .git directory. ### Method (Not specified, likely a function call) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **start** (string) - Yes - Starting search path - **across_fs** (bool) - Yes - Search across filesystem boundaries - **ceiling_dirs** ([]string) - Yes - Directories to stop search at ### Request Example ```go gitDir, err := git.Discover("/path/to/file", false, []string{"/home"}) if err != nil { log.Fatal(err) } fmt.Println(gitDir) ``` ### Response #### Success Response (0) - **string** - Path to discovered .git directory #### Response Example (None) ``` -------------------------------- ### Url Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/remote.md Returns the remote URL. Includes an example of how to retrieve and print the URL of the 'origin' remote. ```APIDOC ## Url ### Description Returns the remote URL. ### Method GET ### Endpoint N/A (Method on Remote object) ### Returns - **string**: Remote URL ### Request Example ```go origin, _ := repo.Remotes.Lookup("origin") fmt.Println(origin.Url()) ``` ``` -------------------------------- ### Get Commit Summary Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the first line of the commit message, often used as a concise summary. ```go summary := commit.Summary() fmt.Println(summary) // First line of message ``` -------------------------------- ### Open Repository and Get HEAD Commit in Go Source: https://github.com/libgit2/git2go/blob/main/_autodocs/START_HERE.md Opens the current Git repository, retrieves the HEAD commit, and prints its message and author. Ensure the repository is accessible from the current directory. Resources are freed using defer. ```go package main import ( "fmt" "log" git "github.com/libgit2/git2go/v34" ) func main() { // Open a repository repo, err := git.OpenRepository(".") if err != nil { log.Fatal(err) } defer repo.Free() // Get HEAD commit head, err := repo.Head() if err != nil { log.Fatal(err) } defer head.Free() // Look up the commit commit, err := repo.LookupCommit(head.Target()) if err != nil { log.Fatal(err) } defer commit.Free() // Print commit info fmt.Println("Message:", commit.Message()) fmt.Println("Author:", commit.Author().Name) } ``` -------------------------------- ### Open Repository and Get HEAD Commit Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md Opens an existing Git repository, retrieves the HEAD reference, and looks up the commit associated with HEAD. Ensure to free repository and reference objects when done. ```go import "github.com/libgit2/git2go/v34" // Open a repository repo, err := git.OpenRepository("/path/to/repo") if err != nil { log.Fatal(err) } defer repo.Free() // Get HEAD reference head, err := repo.Head() if err != nil { log.Fatal(err) } defer head.Free() // Look up the commit commit, err := repo.LookupCommit(head.Target()) if err != nil { log.Fatal(err) } defer commit.Free() fmt.Println(commit.Message()) ``` -------------------------------- ### Create a New TreeBuilder Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/tree.md Use NewTreeBuilder to create a new tree builder. Pass nil for the source parameter to start with an empty builder. Remember to free the builder when done. ```go builder, err := repo.NewTreeBuilder(nil) if err != nil { log.Fatal(err) } deffer builder.Free() ``` -------------------------------- ### Configure Repository Settings Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Demonstrates how to open a repository's configuration, set string and boolean values for user name, email, and pull rebase behavior, and then retrieve a configured value. ```go repo, err := git.OpenRepository("/path/to/repo") if err != nil { log.Fatal(err) } defer repo.Free() cfg, err := repo.Config() if err != nil { log.Fatal(err) } defer cfg.Free() // Configure user for this repository err = cfg.SetString("user.name", "John Doe") if err != nil { log.Fatal(err) } err = cfg.SetString("user.email", "john@example.com") if err != nil { log.Fatal(err) } // Enable rebasing for pulls err = cfg.SetBool("pull.rebase", true) if err != nil { log.Fatal(err) } // Retrieve and verify username, err := cfg.LookupString("user.name") if err != nil { log.Fatal(err) } fmt.Printf("Configured for user: %s\n", username) ``` -------------------------------- ### Initialize New Git Repository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Initializes a new git repository at the specified path. Can create either a standard or a bare repository based on the `isbare` flag. Remember to free the repository handle after use. ```go repo, err := git.InitRepository("/path/to/new/repo", false) if err != nil { log.Fatal(err) } def repo.Free() ``` -------------------------------- ### RawHeader Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Gets the full raw text of the commit header. ```APIDOC ## RawHeader ### Description Gets the full raw text of the commit header. ### Method func (c *Commit) RawHeader() string ### Returns string - Raw header content ``` -------------------------------- ### Create and Use Oid Source: https://github.com/libgit2/git2go/blob/main/_autodocs/types.md Demonstrates creating an Oid from a hex string and using its methods like String() and IsZero(). ```go oid, err := git.NewOid("bd6629ceced7f5a8a6ef7b0b9c8b4a6c6c8f5c0e") if err != nil { log.Fatal(err) } hexStr := oid.String() fmt.Println(hexStr) if oid.IsZero() { fmt.Println("Zero OID") } ``` -------------------------------- ### Open Default System Configuration Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Use OpenDefault to access the combined global and system-level configurations. Free the config object after use. ```go cfg, err := git.OpenDefault() if err != nil { log.Fatal(err) } deffer cfg.Free() username, err := cfg.LookupString("user.name") if err != nil { log.Fatal(err) } fmt.Println(username) ``` -------------------------------- ### Get Remote URL Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/remote.md Retrieves the URL of a remote repository. This is useful for inspecting remote configurations. ```go origin, _ := repo.Remotes.Lookup("origin") fmt.Println(origin.Url()) ``` -------------------------------- ### InitRepository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Initializes a new git repository at the specified path. It can create either a standard or a bare repository based on the provided flag. ```APIDOC ## InitRepository ### Description Initializes a new git repository at the specified path. ### Method `func InitRepository(path string, isbare bool) (*Repository, error)` ### Parameters #### Path Parameters - **path** (string) - Required - Path where repository will be created - **isbare** (bool) - Required - Create as bare repository if true ### Returns - `*Repository` - Newly initialized repository handle ### Example ```go repo, err := git.InitRepository("/path/to/new/repo", false) if err != nil { log.Fatal(err) } defer repo.Free() ``` ``` -------------------------------- ### Open Configuration from Disk Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Use OpenOndisk to load a configuration file from a specified path. Ensure the path is correct and the file exists. Free the config object after use. ```go cfg, err := git.OpenOndisk("/path/to/config") if err != nil { log.Fatal(err) } deffer cfg.Free() ``` -------------------------------- ### Run Git2go Tests Manually After Static Build Source: https://github.com/libgit2/git2go/blob/main/README.md Alternatively, build the static library first using 'make install-static', then run Go tests with the '-tags static' flag. ```bash make install-static go test -v -tags static ./... ``` -------------------------------- ### Managing Repository Collections Source: https://github.com/libgit2/git2go/blob/main/_autodocs/INDEX.md Demonstrates creating remotes, references, and tags within a repository using its managed collections. ```go repo.Remotes.Create("origin", "https://github.com/user/repo.git") ``` ```go repo.References.Create("refs/heads/feature", commitOid, false, "") ``` ```go repo.Tags.Create("v1.0", commitOid, true, "Release 1.0", sig) ``` -------------------------------- ### Get Reference Type Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Returns the type of the reference, which can be invalid, a direct OID reference, or a symbolic reference. ```go ref.Type() ``` -------------------------------- ### Configure Remote Credentials and Transfer Progress Source: https://github.com/libgit2/git2go/blob/main/_autodocs/quick-reference.md Implement `CredentialsCallback` for authentication and `TransferProgressCallback` to monitor download progress during remote operations. ```go &git.RemoteCallbacks{ CredentialsCallback: func(url, user string, allowed git.CredentialType) (*git.Credential, error) { return git.NewCredentialSSHKeyFromAgent("git") }, TransferProgressCallback: func(progress git.TransferProgress) error { fmt.Printf("%d/%d objects\n", progress.ReceivedObjects, progress.TotalObjects) return nil }, } ``` -------------------------------- ### Iterate Over Configuration Entries Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Creates an iterator to loop through all configuration entries. Use `ForEach` to process each entry with a callback function. Remember to free the iterator when done. ```go iter, err := cfg.Iterator() if err != nil { log.Fatal(err) } defer iter.Free() iter.ForEach(func(entry *git.ConfigEntry) error { fmt.Printf("%s = %s\n", entry.Name, entry.Value) return nil }) ``` -------------------------------- ### Get Reference Name Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Retrieves the full name of a git reference. This includes the full path, such as 'refs/heads/main'. ```go ref, err := repo.ReferenceLookup("HEAD") if err != nil { log.Fatal(err) } def ref.Free() name := ref.Name() fmt.Println(name) ``` -------------------------------- ### Initialize and Iterate Rebasing Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md This snippet shows how to initialize a rebase operation and then iterate through its operations. Remember to free the rebase object when done. ```go rebase, err := repo.RebaseInit(upstream, nil, nil, nil) def rebase.Free() // Iterate through rebase operations for { op, err := rebase.Next() if err != nil { break } // Process operation... } ``` -------------------------------- ### Get Commit Message Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the full commit message. Ensure the commit object is valid before calling. ```go commit, err := repo.LookupCommit(oid) if err != nil { log.Fatal(err) } msg := commit.Message() fmt.Println(msg) ``` -------------------------------- ### OpenDefault Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Opens the default system configuration, which includes both global and system-level configurations. This provides access to the standard git configuration settings. ```APIDOC ## OpenDefault ### Description Opens the default system configuration, which includes both global and system-level configurations. This provides access to the standard git configuration settings. ### Method func OpenDefault() (*Config, error) ### Returns - `*Config` - Default configuration ### Example ```go cfg, err := git.OpenDefault() if err != nil { log.Fatal(err) } defer cfg.Free() username, err := cfg.LookupString("user.name") if err != nil { log.Fatal(err) } fmt.Println(username) ``` ``` -------------------------------- ### Get Tree OID Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/tree.md Retrieves the unique identifier (OID) of a Git tree object. This is useful for referencing the tree. ```go tree, err := commit.Tree() if err != nil { log.Fatal(err) } defer tree.Free() id := tree.Id() fmt.Println(id.String()) ``` -------------------------------- ### Wrap Object Database into Repository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Creates a new repository instance that wraps an existing object database (ODB). This is useful when you have an ODB instance and want to interact with it as a full repository. ```go repo, err := git.NewRepositoryWrapOdb(odb) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Repository Index Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Retrieves the index (staging area) of a repository. The index object should be freed when no longer needed. ```Go index, err := repo.Index() if err != nil { log.Fatal(err) } defers index.Free() ``` -------------------------------- ### Get Reference Short Name Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Retrieves the short name of a reference, removing prefixes like 'refs/heads/' or 'refs/tags/'. ```go shortName := ref.ShortHand() fmt.Println(shortName) // "main" instead of "refs/heads/main" ``` -------------------------------- ### Build Go Binaries with Static Linking Source: https://github.com/libgit2/git2go/blob/main/README.md When using statically linked libgit2, pass the '-tags static' flag to all Go build commands to ensure correct pkg-config integration. ```bash go build -tags static github.com/my/project/... ``` ```bash go test -tags static github.com/my/project/... ``` ```bash go install -tags static github.com/my/project/... ``` -------------------------------- ### Get Reference Target OID Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Retrieves the OID that a direct reference points to. Returns nil if the reference is symbolic. ```go target := ref.Target() if target != nil { fmt.Println(target.String()) } ``` -------------------------------- ### Get Index Entry Count Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/index.md Retrieves the number of staged entries in the index. Useful for iterating through all staged files. ```go index, err := repo.Index() if err != nil { log.Fatal(err) } defer index.Free() count := index.EntryCount() fmt.Printf("Staged files: %d\n", count) ``` -------------------------------- ### PushOptions Structure Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/remote.md Defines the configuration options for push operations. Includes callbacks and custom headers. ```go type PushOptions struct { Callbacks RemoteCallbacks CustomHeaders []string } ``` -------------------------------- ### Get Parent Count Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Returns the total number of parent commits for a given commit. This can be used to iterate through all parents. ```go count := commit.ParentCount() fmt.Printf("Commit has %d parent(s)\n", count) for i := uint(0); i < count; i++ { parentId := commit.ParentId(i) fmt.Println(parentId.String()) } ``` -------------------------------- ### Create New Empty Configuration Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Use NewConfig to create an empty configuration object. Remember to free the config object when done using defer cfg.Free(). ```go cfg, err := git.NewConfig() if err != nil { log.Fatal(err) } deffer cfg.Free() err = cfg.SetString("user.name", "John Doe") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Clear Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/tree.md Removes all entries from the tree builder, resetting it to an empty state. This is useful for starting a new tree from scratch. ```APIDOC ## Clear ### Description Clears all entries from the builder, effectively resetting it to an empty state. This operation is useful when you need to discard all previously added entries and start building a new tree. ### Method func (builder *TreeBuilder) Clear() error ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - **error** - An error if the clear operation fails. ``` -------------------------------- ### Iterate Through Commits Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md Iterates through commits starting from the HEAD, printing the summary of each commit until the first parent is reached or there are no more parents. ```go ref, _ := repo.Head() target := ref.Target() commit, _ := repo.LookupCommit(target) defer commit.Free() for { if commit == nil { break } fmt.Println(commit.Summary()) if commit.ParentCount() == 0 { break } parent := commit.Parent(0) commit.Free() commit = parent } ``` -------------------------------- ### CloneOptions Struct Source: https://github.com/libgit2/git2go/blob/main/_autodocs/types.md Options for cloning a repository, including fetch and checkout configurations. ```go type CloneOptions struct { Bare bool CheckoutBranch string FetchOpts *FetchOptions CheckoutOpts *CheckoutOptions RemoteCreateCallback RemoteCreateCallback } ``` -------------------------------- ### Create a Git Commit Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md This code demonstrates how to create a new commit in a repository. It requires writing the index to a tree, defining a signature, and specifying the parent commit and message. ```go tree, _ := index.WriteTree(repo) sig := &git.Signature{ Name: "John Doe", Email: "john@example.com", When: time.Now(), } oid, err := repo.CreateCommit( "HEAD", sig, sig, "My commit message", tree, ) ``` -------------------------------- ### Get Index Entry by Index Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/index.md Retrieves a specific index entry using its 0-based index. Useful when iterating through all entries. ```go for i := uint(0); i < count; i++ { entry, err := index.EntryByIndex(i) if err != nil { log.Fatal(err) } fmt.Printf("%s (%d bytes)\n", entry.Path, entry.Size) ``` -------------------------------- ### Get Index Entry by Path Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/index.md Retrieves an index entry by its file path and conflict stage. Use git.IndexStageNormal for regular entries. ```go entry, err := index.EntryByPath("main.go", git.IndexStageNormal) if err != nil { log.Fatal(err) } fmt.Printf("Entry: %s, Mode: %o\n", entry.Path, entry.Mode) ``` -------------------------------- ### Set Reference Database Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Sets the reference database for the repository. Requires a Refdb object. ```go func (v *Repository) SetRefdb(refdb *Refdb) ``` -------------------------------- ### Free Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Frees the configuration object and saves changes to disk. ```APIDOC ## Free ### Description Frees the configuration object and saves changes to disk. ### Method (Implicitly a method on Config object) ### Example ```go cfg, err := git.OpenDefault() if err != nil { log.Fatal(err) } cfg.SetString("user.name", "John Doe") cfg.Free() // Saves changes ``` ``` -------------------------------- ### Get Content to Sign Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the combined raw header and raw message content, which is the data that would be passed to a signing function. ```go content := commit.ContentToSign() // Pass to signing function ``` -------------------------------- ### Get Raw Commit Header Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the full raw text of the commit header, which includes author, committer, date, and other metadata. ```go rawHeader := commit.RawHeader() ``` -------------------------------- ### Define ConfigLevel Type and Constants Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Defines the hierarchy levels for git configuration files, from system-wide to repository-specific. ```go type ConfigLevel int // Configuration file hierarchy level. // Constants: // - ConfigLevelProgramdata - Windows program data folder // - ConfigLevelSystem - System-wide configuration // - ConfigLevelGlobal - User's global configuration // - ConfigLevelXDG - XDG standards configuration // - ConfigLevelLocal - Repository configuration // - ConfigLevelWorktree - Worktree configuration // - ConfigLevelApp - Application configuration // - ConfigLevelHighest - Highest priority (typically local) ``` -------------------------------- ### Get Raw Commit Message Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the raw commit message without any decoding. Useful for preserving original formatting or encoding. ```go rawMsg := commit.RawMessage() ``` -------------------------------- ### ConfigIterator.ForEach Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Iterates through the remaining configuration entries and applies a callback function to each. This provides a convenient way to process all configuration settings without manual iteration. ```APIDOC ## ConfigIterator.ForEach ### Description Iterates through remaining entries. ### Method func (iter *ConfigIterator) ForEach(callback func(*ConfigEntry) error) error ### Parameters #### Path Parameters - **callback** (func(*ConfigEntry) error) - Yes - Called for each entry ### Returns - Error if iteration fails ### Example ```go err := iter.ForEach(func(entry *git.ConfigEntry) error { fmt.Printf("%s = %s (level: %d)\n", entry.Name, entry.Value, entry.Level) return nil }) ``` ``` -------------------------------- ### Open Git Repository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Opens an existing git repository at the specified path. Ensure to free the repository handle when done to prevent resource leaks. ```go repo, err := git.OpenRepository("/path/to/repo") if err != nil { log.Fatal(err) } def repo.Free() ``` -------------------------------- ### Get Tree Entry by Index Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/tree.md Retrieves a specific tree entry using its 0-based index. Useful for iterating through all entries in a tree sequentially. ```go for i := uint(0); i < tree.EntryCount(); i++ { entry := tree.Entry(i) if entry != nil { fmt.Printf("%s (type: %v)\n", entry.Name, entry.Type) } } ``` -------------------------------- ### Import git2go for dynamic linking Source: https://github.com/libgit2/git2go/blob/main/README.md When dynamically linking against a released version of libgit2, import git2go using Go modules with the appropriate version suffix. CGo handles linking via pkg-config. ```go import "github.com/libgit2/git2go/v34" ``` -------------------------------- ### Get Patch for a Specific Delta Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/diff.md Retrieves the patch content for a specific file change (delta) within a diff. The patch can then be formatted or inspected. ```go patch, err := diff.Patch(0) if err != nil { log.Fatal(err) } defer patch.Free() str, err := patch.String() if err != nil { log.Fatal(err) } fmt.Println(str) ``` -------------------------------- ### Get Parent Commit OID Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the Object ID (OID) of a specific parent commit by its index, without loading the parent object itself. ```go parentId := commit.ParentId(0) ``` -------------------------------- ### Lookup String Configuration Value Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Retrieves a configuration value as a string. Use this when the expected configuration value is text. ```go username, err := cfg.LookupString("user.name") if err != nil { log.Fatal(err) } fmt.Println(username) ``` -------------------------------- ### FetchOptions Structure Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/remote.md Defines the configuration options for fetch operations. Includes callbacks, pruning behavior, tag download settings, and custom headers. ```go type FetchOptions struct { Callbacks RemoteCallbacks Prune FetchPrune UpdateFetchHead bool DownloadTags uint CustomHeaders []string } ``` -------------------------------- ### Get Commit Committer Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the committer's signature, including name, email, and timestamp. The returned Signature object contains these details. ```go committer := commit.Committer() fmt.Printf("%s <%s>\n", committer.Name, committer.Email) ``` -------------------------------- ### Open and Free Repository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Opens a Git repository and ensures it is freed when done. This is a common pattern for managing repository resources. ```Go repo, err := git.OpenRepository("/path/to/repo") if err != nil { log.Fatal(err) } defers repo.Free() ``` -------------------------------- ### Get Commit Author Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the author's signature, including name, email, and timestamp. The returned Signature object contains these details. ```go author := commit.Author() fmt.Printf("%s <%s>\n", author.Name, author.Email) fmt.Println(author.When) ``` -------------------------------- ### Get Commit Tree Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the tree object associated with the commit. Remember to free the tree object when done to prevent memory leaks. ```go tree, err := commit.Tree() if err != nil { log.Fatal(err) } defer tree.Free() ``` -------------------------------- ### Implementing Custom Fetch Credentials Source: https://github.com/libgit2/git2go/blob/main/_autodocs/INDEX.md Provides a custom callback for fetching remote resources, specifically handling SSH key authentication using an agent. ```go remote.Fetch(nil, &git.FetchOptions{ Callbacks: &git.RemoteCallbacks{ CredentialsCallback: func(url, user string, allowed git.CredentialType) (*git.Credential, error) { return git.NewCredentialSSHKeyFromAgent("git") }, }, }) ``` -------------------------------- ### Checkout from Index Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Checks out files from the Git index. Requires an Index object and optional checkout options. ```go func (v *Repository) CheckoutIndex(index *Index, opts *CheckoutOptions) error ``` -------------------------------- ### Manage Git Object Lifetime Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/object.md Demonstrates the correct way to manage the lifetime of Git objects and the repository itself. Always free objects and the repository when they are no longer needed to prevent memory leaks, using `defer` for automatic cleanup. ```go repo, _ := git.OpenRepository("/path/to/repo") defer repo.Free() obj, _ := repo.Lookup(oid) defer obj.Free() // Free before repo.Free() // obj is valid here // After obj.Free(), obj is invalid ``` -------------------------------- ### Get Tree Entry by Path Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/tree.md Retrieves a tree entry using a relative path, allowing traversal into subdirectories. Returns an error if the path is not found. ```go entry, err := tree.EntryByPath("src/main.go") if err != nil { log.Fatal(err) } fmt.Printf("Found: %s\n", entry.Name) ``` -------------------------------- ### Walk a Git Tree Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md Recursively walks through a Git tree, printing the path for each file and directory entry found. ```go tree, _ := commit.Tree() defer tree.Free() tree.Walk(func(dirname string, entry *git.TreeEntry) error { path := dirname + entry.Name if entry.IsFile() { fmt.Printf("File: %s\n", path) } else if entry.IsDir() { fmt.Printf("Dir: %s\n", path) } return nil }) ``` -------------------------------- ### Get Tree Entry by Name Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/tree.md Finds a tree entry by its filename. Returns nil if the entry is not found directly within the current tree level. ```go entry := tree.EntryByName("main.go") if entry != nil { fmt.Printf("Found: %s\n", entry.Name) } ``` -------------------------------- ### Free Git Resources Source: https://github.com/libgit2/git2go/blob/main/_autodocs/quick-reference.md Always free repository, reference, commit, and tree resources when they are no longer needed to prevent memory leaks. ```go repo, _ := git.OpenRepository("/path/to/repo") deferr repo.Free() ref, _ := repo.Head() deferr ref.Free() commit, _ := repo.LookupCommit(ref.Target()) deferr commit.Free() tree, _ := commit.Tree() deferr tree.Free() ``` -------------------------------- ### Get Symbolic Reference Target Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Retrieves the name of the reference that a symbolic reference points to. This is useful for understanding chains of symbolic references like HEAD. ```go head, err := repo.Head() if err != nil { log.Fatal(err) } def head.Free() if head.Type() == git.ReferenceSymbolic { target := head.SymbolicTarget() fmt.Printf("HEAD -> %s\n", target) } ``` -------------------------------- ### Get Blame Information for a File Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md Retrieve blame information for a file, which shows which commit last modified each line. Iterate through the hunks to access details. ```go blame, err := repo.BlameFile("src/main.go", nil) def blame.Free() // Iterate blame hunks for i := uint(0); i < blame.GetHunkCount(); i++ { hunk := blame.GetHunk(i) fmt.Printf("Lines %d-%d by %s\n", hunk.FinalStartLineNumber, hunk.LinesInHunk, hunk.FinalSignature.Name) } ``` -------------------------------- ### Create Symbolic Reference Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Creates a new symbolic reference pointing to another reference name. Use 'force' to overwrite an existing reference. ```go repo.References.CreateSymbolic("name", "target", false, "logMessage") ``` -------------------------------- ### Get Commit Tree OID Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves the Object ID (OID) of the commit's tree without loading the entire tree object into memory. ```go treeOid := commit.TreeId() fmt.Println(treeOid.String()) ``` -------------------------------- ### Get Object Identifier (OID) Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/object.md Retrieves the unique Object Identifier (OID) for the git object. The OID is typically represented as a hexadecimal SHA-1 hash. ```go id := obj.Id() fmt.Println(id.String()) // Hexadecimal SHA-1 ``` -------------------------------- ### Iterate Through Remaining Configuration Entries Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Processes all remaining configuration entries using a provided callback function. The callback is executed for each entry found during iteration. ```go err := iter.ForEach(func(entry *git.ConfigEntry) error { fmt.Printf("%s = %s (level: %d)\n", entry.Name, entry.Value, entry.Level) return nil }) ``` -------------------------------- ### Get Owning Repository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/object.md Retrieves the repository that owns the current object. This is useful for performing further operations on the repository, such as looking up other objects or accessing the working directory. ```go obj, _ := repo.Lookup(oid) owner := obj.Owner() fmt.Println(owner.WorkDir()) ``` -------------------------------- ### Resource Cleanup Pattern Source: https://github.com/libgit2/git2go/blob/main/_autodocs/START_HERE.md Always use `defer obj.Free()` immediately after creating an object to ensure proper resource cleanup. ```Go defer obj.Free() ``` -------------------------------- ### DiffHunk Structure Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/diff.md Represents a contiguous hunk of changes within a diff, specifying the starting lines, line counts in both old and new files, and the hunk header. ```go type DiffHunk struct { OldStart int OldLines int NewStart int NewLines int Header string } ``` -------------------------------- ### Lookup Int64 Configuration Value Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Retrieves a configuration value as a 64-bit integer. Use this for larger numeric configuration settings. ```go cfg.LookupInt64("some.large.number") ``` -------------------------------- ### Get Number of Changed Files in Diff Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/diff.md Retrieves the total count of modified files within a diff. This is useful for understanding the scope of changes before iterating through individual file deltas. ```go diff, err := repo.DiffIndexToWorkdir(nil, nil) if err != nil { log.Fatal(err) } defer diff.Free() numDeltas, err := diff.NumDeltas() if err != nil { log.Fatal(err) } fmt.Printf("Files changed: %d\n", numDeltas) ``` -------------------------------- ### Set Int64 Configuration Value Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Sets a configuration value as a 64-bit integer. Use this for larger numeric configuration settings. ```go cfg.SetInt64("some.large.number", 9876543210) ``` -------------------------------- ### Find System Configuration File Path Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Retrieves the file path for the system-wide Git configuration. This is useful for understanding where global settings are stored. ```go sysPath, err := git.ConfigFindSystem() if err != nil { log.Fatal(err) } fmt.Println(sysPath) ``` -------------------------------- ### Go Module Replace Directive Example Source: https://github.com/libgit2/git2go/blob/main/README.md If git2go is checked out locally and your project is elsewhere, you may need a 'replace' directive in your go.mod file to point to the local git2go path. ```go replace github.com/libgit2/git2go/v34 => ../../libgit2/git2go ``` -------------------------------- ### DiffIndexToWorkdir: Compare Index to Working Directory Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/diff.md Computes the difference between the Git index and the working directory. Use this to see unstaged changes. ```go diff, err := repo.DiffIndexToWorkdir(nil, nil) if err != nil { log.Fatal(err) } defer diff.Free() count, _ := diff.NumDeltas() fmt.Printf("Unstaged changes: %d files\n", count) ``` -------------------------------- ### Get Parent Commit Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Retrieves a specific parent commit by its index (0 for the first parent). Returns nil if the parent does not exist. Remember to free the parent commit object if retrieved. ```go parent := commit.Parent(0) if parent != nil { defer parent.Free() msg := parent.Message() } ``` -------------------------------- ### Run Static Tests for Git2go Source: https://github.com/libgit2/git2go/blob/main/README.md This command runs tests for the main branch, ensuring libgit2 is built locally first. It's a wrapper provided by the Makefile. ```bash make test-static ``` -------------------------------- ### OpenOndisk Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Opens a configuration file from disk at the specified path. This allows direct manipulation of a specific configuration file. ```APIDOC ## OpenOndisk ### Description Opens a configuration file from disk at the specified path. This allows direct manipulation of a specific configuration file. ### Method func OpenOndisk(path string) (*Config, error) ### Parameters #### Path Parameters - **path** (string) - Yes - Path to config file ### Returns - `*Config` - Loaded configuration ### Example ```go cfg, err := git.OpenOndisk("/path/to/config") if err != nil { log.Fatal(err) } defer cfg.Free() ``` ``` -------------------------------- ### Iterate All References Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/reference.md Creates an iterator to traverse all references in the repository. Remember to free the iterator when done. ```go iter, err := repo.References.Iterator() if err != nil { log.Fatal(err) } deferr iter.Free() iter.ForEach(func(ref *Reference) error { fmt.Println(ref.Name()) return nil }) ``` -------------------------------- ### Peel Object to Target Type Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/object.md Recursively follows tag objects to reach a specified target object type (e.g., Commit, Tree, Blob). This is useful for getting the actual object a tag points to, potentially after several levels of indirection. ```go // tag -> commit -> tree -> tree entries obj, _ := repo.Lookup(tagOid) // Peel tag to commit commitObj, err := obj.Peel(git.ObjectCommit) if err != nil { log.Fatal(err) } defer commitObj.Free() commit, _ := commitObj.AsCommit() ``` -------------------------------- ### Connect Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/remote.md Establishes a connection to the remote for either fetching or pushing operations. ```APIDOC ## Connect ### Description Establishes a connection to the remote. ### Method POST ### Endpoint N/A (Method on Remote object) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **direction** (ConnectDirection) - Required - Fetch or push direction - `ConnectDirectionFetch`: For fetch operations - `ConnectDirectionPush`: For push operations ### Returns - **error**: Error if connection fails ``` -------------------------------- ### Configuration Source: https://github.com/libgit2/git2go/blob/main/_autodocs/INDEX.md Functions for creating and accessing Git configuration settings, both globally and per-repository. ```APIDOC ## Configuration ### Description Functions for creating and accessing Git configuration settings, both globally and per-repository. ### Functions - NewConfig - OpenOndisk - OpenDefault - Repository.Config - LookupString - SetString - LookupBool - SetBool ``` -------------------------------- ### Path Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Returns the path to the .git directory. This directory contains all the metadata and object database for the repository. ```APIDOC ## Path ### Description Returns the path to the .git directory. ### Method (Not specified, likely internal or part of a larger operation) ### Returns - **string** - Path to .git directory ``` -------------------------------- ### Output Directory Structure Source: https://github.com/libgit2/git2go/blob/main/_autodocs/MANIFEST.md This diagram shows the organization of the documentation files within the output directory. ```text OUTPUT DIRECTORY STRUCTURE ├── INDEX.md ← Start here for overview ├── README.md ← Quick start and patterns ├── types.md ← Type reference ├── errors.md ← Error handling ├── quick-reference.md ← Fast lookup ├── MANIFEST.md ← This file └── api-reference/ ├── repository.md ← Repository operations ├── commit.md ← Commit objects ├── reference.md ← References/branches ├── tree.md ← Tree objects ├── index.md ← Staging area ├── object.md ← Base object type ├── diff.md ← Diff operations ├── remote.md ← Remote operations └── config.md ← Configuration ``` -------------------------------- ### Open Repository Configuration Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Access a repository's specific configuration using the Repository.Config() method. Free both the repository and config objects after use. ```go repo, _ := git.OpenRepository("/path/to/repo") deffer repo.Free() cfg, err := repo.Config() if err != nil { log.Fatal(err) } deffer cfg.Free() localUser, err := cfg.LookupString("user.name") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Open Git Repository with Extended Options Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Opens a git repository with advanced options, including search flags and a ceiling directory to limit the search scope. Useful for complex repository structures or specific search behaviors. ```go repo, err := git.OpenRepositoryExtended( "/path/to/repo", git.RepositoryOpenNoSearch, "/home", ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Add File to Index by Path Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/index.md Adds a file to the index using its path relative to the repository root. Changes must be written to disk. ```go err := index.AddByPath("README.md") if err != nil { log.Fatal(err) } err = index.Write() if err != nil { log.Fatal(err) } ``` -------------------------------- ### OpenRepository Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Opens an existing git repository at the specified path. It returns a Repository handle or an error if the repository cannot be found or is in an invalid state. ```APIDOC ## OpenRepository ### Description Opens an existing git repository. ### Method `func OpenRepository(path string) (*Repository, error)` ### Parameters #### Path Parameters - **path** (string) - Required - Path to the repository directory ### Returns - `*Repository` - Open repository handle, or error if repository cannot be found ### Error Conditions - `ErrorCodeNotFound` - Repository not found at specified path - `ErrorClassRepository` - Invalid repository state ### Example ```go repo, err := git.OpenRepository("/path/to/repo") if err != nil { log.Fatal(err) } defer repo.Free() // Use repository... ``` ``` -------------------------------- ### Fetch from Remote with SSH Agent Credentials Source: https://github.com/libgit2/git2go/blob/main/_autodocs/README.md Fetches changes from the 'origin' remote using SSH key authentication via an agent. Requires the 'git' user for the SSH key. ```go origin, _ := repo.Remotes.Lookup("origin") // Fetch with credentials err := origin.Fetch( nil, &git.FetchOptions{ Callbacks: &git.RemoteCallbacks{ CredentialsCallback: func(url, user string, allowed git.CredentialType) (*git.Credential, error) { return git.NewCredentialSSHKeyFromAgent("git") }, }, }, ) ``` -------------------------------- ### LookupInt64 Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Looks up a configuration value as a 64-bit integer. Requires the configuration key as input. ```APIDOC ## LookupInt64 ### Description Looks up a configuration value as a 64-bit integer. ### Method (Implicitly a method on Config object) ### Parameters #### Path Parameters - **name** (string) - Required - Configuration key ### Returns - **int64** - Numeric value - **error** - Error if lookup fails ``` -------------------------------- ### Set Int32 Configuration Value Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Sets a configuration value as a 32-bit integer. Use this for numeric configuration settings that fit within a 32-bit integer range. ```go cfg.SetInt32("some.int.value", 123) ``` -------------------------------- ### RebaseOptions Struct Source: https://github.com/libgit2/git2go/blob/main/_autodocs/types.md Configuration options for rebase operations, including merge settings and callbacks. ```go type RebaseOptions struct { Version uint Quiet bool InMemoryIndex bool RewriteNotesRef string MergeOptions *MergeOptions CommitCreateCallback CommitCreateCallback PayloadUnsafe unsafe.Pointer } ``` -------------------------------- ### ConfigFindGlobal Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Returns the path to the current user's global Git configuration file. This file, usually located in the user's home directory, contains user-specific settings. ```APIDOC ## ConfigFindGlobal ### Description Returns the path to the user's global configuration file. ### Method func ConfigFindGlobal() (string, error) ### Returns - `string` - Global config file path (typically ~/.gitconfig) ### Example ```go globalPath, err := git.ConfigFindGlobal() if err != nil { log.Fatal(err) } fmt.Println(globalPath) ``` ``` -------------------------------- ### NewConfig Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/config.md Creates an empty configuration object. This is useful for creating a new configuration from scratch or for temporary in-memory configurations. ```APIDOC ## NewConfig ### Description Creates an empty configuration object. This is useful for creating a new configuration from scratch or for temporary in-memory configurations. ### Method func NewConfig() (*Config, error) ### Returns - `*Config` - New empty config ### Example ```go cfg, err := git.NewConfig() if err != nil { log.Fatal(err) } defer cfg.Free() err = cfg.SetString("user.name", "John Doe") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Create Git Blob from Disk Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/object.md Creates a new Git blob object by reading content from a file on disk. Ensure the file path is correct. ```go blobOid, err := repo.CreateBlobFromDisk("path/to/file") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Sign a Commit Using a Callback Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/commit.md Creates a new signed commit by providing a callback function for signing. The callback handles the actual signing process. ```go func (c *Commit) WithSignatureUsing(f CommitSigningCallback) (*Oid, error) ``` ```go newOid, err := commit.WithSignatureUsing(func(content string) (string, string, error) { sig := signWithGPG(content) return sig, "gpgsig", nil }) ``` -------------------------------- ### Git File Modes Source: https://github.com/libgit2/git2go/blob/main/_autodocs/quick-reference.md Lists the different file modes used in Git, such as for trees, blobs, and executables. ```go FilemodeTree, FilemodeBlob, FilemodeBlobExecutable, FilemodeLink, FilemodeCommit ``` -------------------------------- ### CheckoutOptions Struct Source: https://github.com/libgit2/git2go/blob/main/_autodocs/types.md Specifies options for checkout operations, including strategy, notification callbacks, and progress callbacks. ```go type CheckoutOptions struct { Strategy CheckoutStrategy NotifyCallback CheckoutNotifyCallback ProgressCallback CheckoutProgressCallback } ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/libgit2/git2go/blob/main/_autodocs/quick-reference.md Stage changes using `AddByPath`, write the index to a tree, and then create a new commit using the staged tree. Ensure all resources are freed. ```go index, _ := repo.Index() deferr index.Free() index.AddByPath("main.go") treeOid, _ := index.WriteTree(repo) index.Write() tree, _ := repo.LookupTree(treeOid) deferr tree.Free() sig := &git.Signature{Name: "User", Email: "user@example.com", When: time.Now()} repo.CreateCommit("HEAD", sig, sig, "message", tree) ``` -------------------------------- ### Initialize Rebase Operation Source: https://github.com/libgit2/git2go/blob/main/_autodocs/api-reference/repository.md Initializes an interactive rebase operation with specified upstream, onto, branch commits, and rebase options. ```go func (v *Repository) RebaseInit(upstream *Commit, onto *Commit, branch *Commit, opts *RebaseOptions) (*Rebase, error) ```