git

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: MIT Imports: 14 Imported by: 2

README

Gitz

Write fluent interactions to Git using the gitz library. Programmatically crafting git commands becomes a breeze! Verify your code using the inbuilt testing framework.

Badges

Build status License MIT Go Report Card Go Version DeepSource

Documentation

Check out the latest documentation

Documentation

Overview

Package git provides a simple lightweight library for performing fluent git operations against an existing cloned repository

Index

Constants

View Source
const (

	// RelativeAtRoot can be used to compare if a path is equivalent to the
	// root of a current git repository working directory
	RelativeAtRoot = "."

	// HeadRef is a pointer to the latest commit within a git repository
	HeadRef = "HEAD"
)

Variables

This section is empty.

Functions

func CheckConfigPath added in v0.4.0

func CheckConfigPath(path string) error

CheckConfigPath performs rudimentary checks to ensure the config path conforms to the git config specification. A config path is invalid if:

  • No dot separator exists, or the last character is a dot separator
  • First character after the last dot separator is not a letter
  • Path contains non-alphanumeric characters

func ToInlineConfig added in v0.6.0

func ToInlineConfig(pairs ...string) ([]string, error)

ToInlineConfig converts a series of config settings from path value notation into the corresponding inline config notation compatible with git commands

"user.name", "penguin" => []string{"-c user.name='penguin'"}

Types

type BlobDetails added in v0.6.0

type BlobDetails struct {
	// Diff contains the blobs contents
	Diff string

	// Ref contains the unique identifier associated with the blob
	Ref string
}

BlobDetails contains details about a specific blob within a repository

type CheckoutOption added in v0.6.0

type CheckoutOption func(*checkoutOptions)

CheckoutOption provides a way for setting specific options while attempting to checkout a branch. Each supported option can customize how a branch is checked out from the remote and integrated into the current repository (working directory)

func WithCheckoutConfig added in v0.6.0

func WithCheckoutConfig(kv ...string) CheckoutOption

WithCheckoutConfig allows temporary git config to be set while checking out a branch from the remote. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

type Client

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

Client provides a way of performing fluent operations against git. Any git operation exposed by this client are effectively handed-off to an installed git client on the current OS. Git operations will be mapped as closely as possible to the official Git specification

func NewClient

func NewClient() (*Client, error)

NewClient returns a new instance of the git client

func (*Client) Checkout added in v0.3.0

func (c *Client) Checkout(branch string, opts ...CheckoutOption) (string, error)

Checkout will attempt to checkout a branch with the given name. If the branch does not exist, it is created at the current working tree reference (or commit), and then switched to. If the branch does exist, then switching to it restores all working tree files

func (*Client) Clean added in v0.6.0

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

Clean determines if the current repository (working directory) is in a clean state. A repository is deemed clean, if it contains no changes

func (*Client) Clone added in v0.2.0

func (c *Client) Clone(url string, opts ...CloneOption) (string, error)

Clone a repository by its provided URL into a newly created directory. A default clone will ensure remote tracking branches are created for each branch within the repository with only the default branch being checked out fully. The cloned directory will mirror that of the repository name within its URL. Options can be provided to customize the clone behavior

func (*Client) Commit

func (c *Client) Commit(msg string, opts ...CommitOption) (string, error)

Commit a snapshot of changes within the current repository (working directory) and describe those changes with a given log message. Commit behavior can be customized through the use of options

func (*Client) Config added in v0.4.0

func (c *Client) Config() (map[string]string, error)

Config attempts to retrieve all git config for the current repository. A map is returned containing each config item and its corresponding latest value. Values are resolved from local, system and global config

func (*Client) ConfigG added in v0.5.0

func (c *Client) ConfigG(paths ...string) (map[string][]string, error)

ConfigG attempts to query a batch of global git config settings for their values. If multiple values have been set for any config item, all are returned, ordered by most recent value first. A partial batch is never returned, all config settings must exist

func (*Client) ConfigL added in v0.4.0

func (c *Client) ConfigL(paths ...string) (map[string][]string, error)

ConfigL attempts to query a batch of local git config settings for their values. If multiple values have been set for any config item, all are returned, ordered by most recent value first. A partial batch is never returned, all config settings must exist

func (*Client) ConfigS added in v0.5.0

func (c *Client) ConfigS(paths ...string) (map[string][]string, error)

ConfigS attempts to query a batch of system git config settings for their values. If multiple values have been set for any config item, all are returned, ordered by most recent value first. A partial batch is never returned, all config settings must exist

func (*Client) ConfigSetG added in v0.5.0

func (c *Client) ConfigSetG(pairs ...string) error

ConfigSetG attempts to batch assign values to a group of global git config settings. If any setting exists, a new line is added to the local git config, effectively assigning multiple values to the same setting. Basic validation is performed to minimize the possibility of a partial batch update

func (*Client) ConfigSetL added in v0.4.0

func (c *Client) ConfigSetL(pairs ...string) error

ConfigSetL attempts to batch assign values to a group of local git config settings. If any setting exists, a new line is added to the local git config, effectively assigning multiple values to the same setting. Basic validation is performed to minimize the possibility of a partial batch update

func (*Client) ConfigSetS added in v0.5.0

func (c *Client) ConfigSetS(pairs ...string) error

ConfigSetS attempts to batch assign values to a group of system git config settings. If any setting exists, a new line is added to the local git config, effectively assigning multiple values to the same setting. Basic validation is performed to minimize the possibility of a partial batch update

func (*Client) DeleteTag

func (c *Client) DeleteTag(tag string, opts ...DeleteTagsOption) (string, error)

DeleteTag a tag both locally and from the remote origin

func (*Client) DeleteTags added in v0.6.0

func (c *Client) DeleteTags(tags []string, opts ...DeleteTagsOption) (string, error)

DeleteTags will attempt to delete a series of tags from the current repository and push those deletions back to the remote

func (*Client) Fetch added in v0.7.0

func (c *Client) Fetch(opts ...FetchOption) (string, error)

Fetch all remote changes from a remote repository without integrating (merging) them into the current repository (working directory). Ensures the current repository only tracks the latest remote changes

func (*Client) Log

func (c *Client) Log(opts ...LogOption) (*Log, error)

Log retrieves the commit log of the current repository (working directory) in an easy-to-parse format. Options can be provided to customize log retrieval, creating a targeted snapshot. By default, the entire history from the repository HEAD (most recent commit) will be retrieved. The logs are generated using the default git options:

git log --pretty='format:> %H %B%-N' --no-color

func (*Client) PorcelainStatus added in v0.6.0

func (c *Client) PorcelainStatus() ([]FileStatus, error)

PorcelainStatus identifies if there are any changes within the current repository (working directory) and returns them in the parseable porcelain v1 format

func (*Client) Pull

func (c *Client) Pull(opts ...PullOption) (string, error)

Pull all changes from a remote repository and immediately update the current repository (working directory) with those changes. This ensures that your current repository keeps track of remote changes and stays in sync

func (*Client) Push

func (c *Client) Push(opts ...PushOption) (string, error)

Push (or upload) all local changes to the remote repository. By default, changes associated with the current branch will be pushed back to the remote. Options can be provided to configure branch and tag push semantics

func (*Client) PushRef added in v0.3.0

func (c *Client) PushRef(ref string) (string, error)

PushRef will push an individual reference to the remote repository Deprecated: use [Push] instead

func (*Client) Repository added in v0.2.0

func (c *Client) Repository() (Repository, error)

Repository captures and returns a snapshot of the current repository (working directory) state

func (*Client) ShowBlobs added in v0.6.0

func (c *Client) ShowBlobs(refs ...string) (map[string]BlobDetails, error)

ShowBlobs retrieves details about any number of blobs within the current repository (working directory)

func (*Client) ShowCommits added in v0.6.0

func (c *Client) ShowCommits(refs ...string) (map[string]CommitDetails, error)

ShowCommits retrieves details about any number of commits within the current repository (working directory)

func (*Client) ShowTags added in v0.6.0

func (c *Client) ShowTags(refs ...string) (map[string]TagDetails, error)

ShowTags retrieves details about any number of tags within the current repository (working directory)

func (*Client) ShowTrees added in v0.6.0

func (c *Client) ShowTrees(refs ...string) (map[string]TreeDetails, error)

ShowTrees retrieves details about any number of trees within the current repository (working directory)

func (*Client) Stage

func (c *Client) Stage(opts ...StageOption) (string, error)

Stage changes to any file or folder within the current repository (working directory) ready for inclusion in the next commit. Options can be provided to further configure stage semantics. By default, all changes will be staged ready for the next commit.

func (*Client) Staged added in v0.6.0

func (c *Client) Staged() ([]string, error)

Staged retrieves a list of all currently staged file changes within the current repository

func (*Client) Tag

func (c *Client) Tag(tag string, opts ...CreateTagOption) (string, error)

Tag a specific point within a repositories history and push it to the configured remote. Tagging comes in two flavours:

  • A lightweight tag, which points to a specific commit within the history and marks a specific point in time
  • An annotated tag, which is treated as a full object within git, and must include a tagging message (or annotation)

By default, a lightweight tag will be created, unless specific tag options are provided

func (*Client) TagBatch added in v0.8.0

func (c *Client) TagBatch(tags []string, opts ...CreateTagOption) (string, error)

TagBatch attempts to create a batch of tags against a specific point within a repositories history. All tags are created locally and then pushed in a single transaction to the remote. This behavior is enforced by explicitly enabling the WithLocalOnly option

func (*Client) TagBatchAt added in v0.8.0

func (c *Client) TagBatchAt(pairs []string, opts ...CreateTagOption) (string, error)

TagBatchAt attempts to create a batch of tags that target specific commits within a repositories history. Any number of pairs consisting of a tag and commit hash must be provided.

TagBatchAt([]string{"0.1.0", "740a8b9", "0.2.0", "9e7dfbb"})

All tags are created locally and then pushed in a single transaction to the remote. This behavior is enforced by explicitly enabling the WithLocalOnly option

func (*Client) Tags added in v0.3.0

func (c *Client) Tags(opts ...ListTagsOption) ([]string, error)

Tags retrieves all local tags from the current repository (working directory). By default, all tags are retrieved in ascending lexicographic order as implied through the RefName sort key. Options can be provided to customize retrieval

func (*Client) ToRelativePath added in v0.4.0

func (c *Client) ToRelativePath(path string) (string, error)

ToRelativePath determines if a path is relative to the working directory of the repository and returns the resolved relative path. A ErrGitNonRelativePath error will be returned if the path exists outside of the working directory. RelativeAtRoot is returned if the path and working directory are equivalent

func (*Client) VerifyCommit added in v0.5.0

func (c *Client) VerifyCommit(hash string) (*CommitVerification, error)

VerifyCommit validates that a given commit has a valid GPG signature and returns details about that signature

func (*Client) VerifyTag added in v0.5.0

func (c *Client) VerifyTag(ref string) (*TagVerification, error)

VerifyTag validates that a given tag has a valid GPG signature and returns details about that signature

func (*Client) Version

func (c *Client) Version() string

Version of git used by the client

type CloneOption added in v0.3.0

type CloneOption func(*cloneOptions)

CloneOption provides a way for setting specific options during a clone operation. Each supported option can customize the way in which the repository is cloned onto the file system into a target working directory

func WithCheckoutRef added in v0.3.0

func WithCheckoutRef(ref string) CloneOption

WithCheckoutRef changes the default checkout behavior after a clone succeeds. A branch or tag reference is supported. Checking out a tag will result in a detached HEAD. An empty string will be ignored

func WithCloneConfig added in v0.6.0

func WithCloneConfig(kv ...string) CloneOption

WithCloneConfig allows temporary git config to be set while cloning the remote into a newly created directory. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

func WithDepth added in v0.3.0

func WithDepth(depth int) CloneOption

WithDepth ensures the repository will be cloned at a specific depth, effectively truncating the history to the required number of commits. The result will be a shallow repository. Any depth less than one is ignored, resulting in a full clone of the history

func WithDirectory added in v0.3.0

func WithDirectory(dir string) CloneOption

WithDirectory provides a named directory for cloning the repository into. If the directory already exists, it must be empty for the clone to be successful. An empty string will be ignored

func WithNoTags added in v0.3.0

func WithNoTags() CloneOption

WithNoTags prevents any tags from being included during the clone

type CommitDetails added in v0.6.0

type CommitDetails struct {
	// Author represents a person who originally created the files
	// within the repository
	Author Person

	// AuthorDate contains the date and time of when the author
	// originally created the files within the repository
	AuthorDate time.Time

	// Committer represents a person who changed any existing files
	// within the repository
	Committer Person

	// CommitterDate contains the date and time of when the committer
	// changed any existing files within the repository
	CommitterDate time.Time

	// Message contains the message associated with the commit
	Message string

	// Ref contains the unique identifier associated with the commit
	Ref string

	// Signature contains details of the verified GPG signature
	Signature *Signature
}

CommitDetails contains details about a specific commit within a repository

type CommitOption added in v0.5.0

type CommitOption func(*commitOptions)

CommitOption provides a way for setting specific options during a commit operation. Each supported option can customize the way the commit is created against the current repository (working directory)

func WithAllowEmpty added in v0.5.0

func WithAllowEmpty() CommitOption

WithAllowEmpty allows a commit to be created without having to track any changes. This bypasses the default protection by git, preventing a commit from having the exact same tree as its parent

func WithCommitConfig added in v0.6.0

func WithCommitConfig(kv ...string) CommitOption

WithCommitConfig allows temporary git config to be set during the execution of the commit. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

func WithGpgSign added in v0.5.0

func WithGpgSign() CommitOption

WithGpgSign will create a GPG-signed commit using the GPG key associated with the committers email address. Overriding this behavior is possible through the user.signingkey config setting. This option does not need to be explicitly called if the commit.gpgSign config setting is set to true

func WithGpgSigningKey added in v0.5.0

func WithGpgSigningKey(key string) CommitOption

WithGpgSigningKey will create a GPG-signed commit using the provided GPG key ID, overridding any default GPG key set by the user.signingKey git config setting

func WithNoGpgSign added in v0.5.0

func WithNoGpgSign() CommitOption

WithNoGpgSign ensures the created commit will not be GPG signed regardless of the value assigned to the repositories commit.gpgSign git config setting

type CommitVerification added in v0.5.0

type CommitVerification struct {
	// Author represents a person who originally created the files
	// within the repository
	Author Person

	// Committer represents a person who changed any existing files
	// within the repository
	Committer Person

	// Hash contains the unique identifier associated with the commit
	Hash string

	// Message contains the message associated with the commit
	Message string

	// Signature contains details of the verified GPG signature
	Signature *Signature
}

CommitVerification contains details about a GPG signed commit

type CreateTagOption added in v0.3.0

type CreateTagOption func(*createTagOptions)

CreateTagOption provides a way for setting specific options during a tag creation operation. Each supported option can customize the way the tag is created against the current repository (working directory)

func WithAnnotation

func WithAnnotation(message string) CreateTagOption

WithAnnotation ensures the created tag is annotated with the provided message. This ultimately converts the standard lightweight tag into an annotated tag which is stored as a full object within the git database. Any leading and trailing whitespace will automatically be trimmed from the message. This allows empty messages to be ignored

func WithCommitRef added in v0.8.0

func WithCommitRef(ref string) CreateTagOption

WithCommitRef ensures the created tag points to a specific commit within the history of the repository. This changes the default behavior of creating a tag against the HEAD (or latest commit) within the repository

func WithLocalOnly added in v0.7.0

func WithLocalOnly() CreateTagOption

WithLocalOnly ensures the created tag will not be pushed back to the remote and be kept as a local tag only

func WithSigned added in v0.5.0

func WithSigned() CreateTagOption

WithSigned will create a GPG-signed tag using the GPG key associated with the taggers email address. Overriding this behavior is possible through the user.signingkey config setting. This option does not need to be explicitly called if the tag.gpgSign config setting is set to true. An annotated tag is mandatory when signing. A default annotation will be assigned, unless overridden with the WithAnnotation option:

created tag 0.1.0

func WithSigningKey added in v0.5.0

func WithSigningKey(key string) CreateTagOption

WithSigningKey will create a GPG-signed tag using the provided GPG key ID, overridding any default GPG key set by the user.signingKey config setting. An annotated tag is mandatory when signing. A default annotation will be assigned, unless overridden with the WithAnnotation option:

created tag 0.1.0

func WithSkipSigning added in v0.5.0

func WithSkipSigning() CreateTagOption

WithSkipSigning ensures the created tag will not be GPG signed regardless of the value assigned to the repositories tag.gpgSign git config setting

func WithTagConfig added in v0.6.0

func WithTagConfig(kv ...string) CreateTagOption

WithTagConfig allows temporary git config to be set during the creation of a tag. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

type DeleteTagsOption added in v0.6.0

type DeleteTagsOption func(*deleteTagsOptions)

DeleteTagsOption provides a way for setting specific options during a tag deletion operation

func WithLocalDelete added in v0.6.0

func WithLocalDelete() DeleteTagsOption

WithLocalDelete ensures the reference to the tag is deleted from the local index only and is not pushed back to the remote. Useful if working with temporary tags that need to be removed

type ErrGitExecCommand

type ErrGitExecCommand struct {
	// Cmd contains the command that caused the git client to error
	Cmd string

	// Out contains any raw output from the git client as a result
	// of the error
	Out string
}

ErrGitExecCommand is raised when a git command fails to execute

func (ErrGitExecCommand) Error

func (e ErrGitExecCommand) Error() string

Error returns a friendly formatted message of the current error

type ErrGitMissing

type ErrGitMissing struct {
	// PathEnv contains the value of the PATH environment variable
	PathEnv string
}

ErrGitMissing is raised when no git client was identified within the PATH environment variable on the current OS

func (ErrGitMissing) Error

func (e ErrGitMissing) Error() string

Error returns a friendly formatted message of the current error

type ErrGitNonRelativePath added in v0.4.0

type ErrGitNonRelativePath struct {
	// RootDir contains the root working directory of the repository
	RootDir string

	// TargetPath contains the path that was resolved against the
	// root working directory of the repository
	TargetPath string

	// RelativePath contains the resolved relative path which raised
	// the error
	RelativePath string
}

ErrGitNonRelativePath is raised when attempting to resolve a path within a git repository that isn't relative to the root of the working directory

func (ErrGitNonRelativePath) Error added in v0.4.0

func (e ErrGitNonRelativePath) Error() string

Error returns a friendly formatted message of the current error

type ErrInvalidConfigPath added in v0.4.0

type ErrInvalidConfigPath struct {
	// Path to the config setting
	Path string

	// Position of the first offending character within the path
	Position int

	// Reason why the path is invalid
	Reason string
}

ErrInvalidConfigPath is raised when a config setting is to be accessed with an invalid config path

func (ErrInvalidConfigPath) Error added in v0.4.0

func (e ErrInvalidConfigPath) Error() string

Error returns a friendly formatted message of the current error

type ErrMissingConfigValue added in v0.6.0

type ErrMissingConfigValue struct {
	// Path to the config setting
	Path string
}

ErrMissingConfigValue is raised when a git config path does not have a corresponding value

func (ErrMissingConfigValue) Error added in v0.6.0

func (e ErrMissingConfigValue) Error() string

Error returns a friendly formatted message of the current error

type ErrMissingTagCommitRef added in v0.8.0

type ErrMissingTagCommitRef struct {
	// Tag reference
	Tag string
}

ErrMissingTagCommitRef is raised when a git tag is missing an associated commit hash

func (ErrMissingTagCommitRef) Error added in v0.8.0

func (e ErrMissingTagCommitRef) Error() string

Error returns a friendly formatted message of the current error

type FetchOption added in v0.7.0

type FetchOption func(*fetchOptions)

FetchOption provides a way for setting specific options while fetching changes from the remote. Each supported option can customize how changes are fetched from the remote

func WithAll added in v0.7.0

func WithAll() FetchOption

WithAll will fetch the latest changes from all tracked remotes

func WithDepthTo added in v0.7.0

func WithDepthTo(depth int) FetchOption

WithDepthTo will limit the number of commits to be fetched from the remotes history to the specified depth. If fetching into a shallow clone of a repository, this can be used to shorten or deepen the existing history

func WithFetchConfig added in v0.7.0

func WithFetchConfig(kv ...string) FetchOption

WithFetchConfig allows temporary git config to be set while fetching changes from the remote. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

func WithFetchRefSpecs added in v0.7.0

func WithFetchRefSpecs(refs ...string) FetchOption

WithFetchRefSpecs allows remote references to be cherry-picked and fetched into the current repository (working copy). A reference (or refspec) can be as simple as a name, where git will automatically resolve any ambiguity, or as explicit as providing a source and destination for reference within the remote. Check out the official git documentation on how to write a more complex [refspec] [refspec]: https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt-ltrefspecgt

func WithForce added in v0.7.0

func WithForce() FetchOption

WithForce will force the fetching of a remote branch into a local branch with a different name (or refspec). Default behavior within git prevents such an operation. Typically used in conjunction with the WithFetchRefSpecs option

func WithIgnoreTags added in v0.7.0

func WithIgnoreTags() FetchOption

WithIgnoreTags disables local tracking of tags from the remote

func WithTags added in v0.7.0

func WithTags() FetchOption

WithTags will fetch all tags from the remote into local tag references with the same name

type FileStatus added in v0.6.0

type FileStatus struct {
	// Indicators is a two character array that contains
	// the current status of a file within both the current index
	// and the working repository tree.
	//
	// Examples:
	//
	// 	'??' - a file that is not tracked
	//	' A' - a file that has been added to the working tree
	//	'M ' - a file that has been modified within the index
	Indicators [2]FileStatusIndicator

	// Path of the file relative to the root of the
	// current repository
	Path string
}

FileStatus represents the status of a file within a repository

func (FileStatus) String added in v0.6.0

func (f FileStatus) String() string

String representation of a file status that adheres to the porcelain v1 format

type FileStatusIndicator added in v0.6.0

type FileStatusIndicator byte

FileStatusIndicator contains a single character that represents a files status within a git repository. Based on the git specification: https://git-scm.com/docs/git-status#_output

const (
	Added       FileStatusIndicator = 'A'
	Copied      FileStatusIndicator = 'C'
	Deleted     FileStatusIndicator = 'D'
	Ignored     FileStatusIndicator = '!'
	Modified    FileStatusIndicator = 'M'
	Renamed     FileStatusIndicator = 'R'
	TypeChanged FileStatusIndicator = 'T'
	Updated     FileStatusIndicator = 'U'
	Unmodified  FileStatusIndicator = ' '
	Untracked   FileStatusIndicator = '?'
)

type ListTagsOption added in v0.3.0

type ListTagsOption func(*listTagsOptions)

ListTagsOption provides a way for setting specific options during a list tags operation. Each supported option can customize the way in which the tags are queried and returned from the current repository (workng directory)

func WithCount added in v0.4.0

func WithCount(n int) ListTagsOption

WithCount limits the number of tags that are returned after all processing and filtering has been applied the retrieved list

func WithFilters added in v0.4.0

func WithFilters(filters ...TagFilter) ListTagsOption

WithFilters allows the retrieved list of tags to be processed with a set of user-defined filters. Each filter is applied in turn to the working set. Nil filters are ignored

func WithShellGlob added in v0.3.0

func WithShellGlob(patterns ...string) ListTagsOption

WithShellGlob limits the number of tags that will be retrieved, by only returning tags that match a given Shell Glob pattern. If multiple patterns are provided, tags will be retrieved if they match against a single pattern. All leading and trailing whitespace will be trimmed, allowing empty patterns to be ignored

func WithSortBy added in v0.3.0

func WithSortBy(keys ...SortKey) ListTagsOption

WithSortBy allows the retrieved order of tags to be changed by sorting against a reserved field name. By default, sorting will always be in ascending order. To change this behaviour, prefix a field name with a hyphen (-<fieldname>). You can sort tags against multiple fields, but this does change the expected behavior. The last field name is treated as the primary key for the entire sort. All leading and trailing whitespace will be trimmed, allowing empty field names to be ignored

type Log

type Log struct {
	// Raw contains the raw commit log
	Raw string

	// Commits contains the optionally parsed commit log. By default
	// the parsed history will always be present, unless the
	// [WithRawOnly] option is provided during retrieval
	Commits []LogEntry
}

Log represents a snapshot of commit history from a repository

type LogEntry

type LogEntry struct {
	// Hash contains the unique identifier associated with the commit
	Hash string

	// AbbrevHash contains the seven character abbreviated commit hash
	AbbrevHash string

	// Message contains the message associated with the commit
	Message string
}

LogEntry represents a single parsed entry from within the commit history of a repository

type LogOption

type LogOption func(*logOptions)

LogOption provides a way for setting specific options during a log operation. Each supported option can customize the way the log history of the current repository (working directory) is processed before retrieval

func WithGrep added in v0.2.0

func WithGrep(matches ...string) LogOption

WithGrep limits the number of commits that will be output within the log history to any with a log message that contains one of the provided matches (regular expressions). All leading and trailing whitespace will be trimmed, allowing empty matches to be ignored

func WithInvertGrep added in v0.2.0

func WithInvertGrep(matches ...string) LogOption

WithInvertGrep limits the number of commits that will be output within the log history to any with a log message that does not contain one of the provided matches (regular expressions). All leading and trailing whitespace will be trimmed, allowing empty matches to be ignored

func WithMatchAll added in v0.2.0

func WithMatchAll() LogOption

WithMatchAll when used in combination with git.WithGrep will limit the number of returned commits to those whose log message contains all of the provided matches (regular expressions)

func WithPaths

func WithPaths(paths ...string) LogOption

WithPaths allows the log history to be retrieved for any number of files and folders within the current repository (working directory). Only commits that have had a direct impact on those files and folders will be retrieved. Paths to files and folders are relative to the root of the repository. All leading and trailing whitespace will be trimmed from the file paths, allowing empty paths to be ignored.

A relative path can be resolved using [ToRelativePath].

func WithRawOnly

func WithRawOnly() LogOption

WithRawOnly ensures only the raw output from the git log of the current repository (working directory) is retrieved. No post-processing is carried out, resulting in an empty [Log.Commits] slice

func WithRef

func WithRef(ref string) LogOption

WithRef provides a starting point other than HEAD (most recent commit) when retrieving the log history of the current repository (working directory). Typically a reference can be either a commit hash, branch name or tag. The output of this option will typically be a shorter, fine-tuned history. This option is mutually exclusive with WithRefRange. All leading and trailing whitespace are trimmed from the reference, allowing empty references to be ignored

func WithRefRange

func WithRefRange(fromRef string, toRef string) LogOption

WithRefRange provides both a start and end point when retrieving a focused snapshot of the log history from the current repository (working directory). Typically a reference can be either a commit hash, branch name or tag. The output of this option will be a shorter, fine-tuned history, for example, the history between two tags. This option is mutually exclusive with WithRef. All leading and trailing whitespace are trimmed from the references, allowing empty references to be ignored

func WithSkip added in v0.2.0

func WithSkip(n int) LogOption

WithSkip skips any number of most recent commits from within the log history. A positive number (greater than zero) is expected. Skipping more commits than exists, will result in no history being retrieved. Skipping zero commits, will retrieve the entire log. This option has a higher order of precedence than git.WithTake

func WithTake added in v0.2.0

func WithTake(n int) LogOption

WithTake limits the number of commits that will be output within the log history. A positive number (greater than zero) is expected. Taking more commits than exists, has the same effect as retrieving the entire log. Taking zero commits, will retrieve an empty log. This option has a lower order of precedence than git.WithSkip

type Person added in v0.6.0

type Person struct {
	// Name of the person
	Name string

	// Email address associated with the person
	Email string
}

Person represents a human that has performed an interaction against a repository

type PullOption added in v0.6.0

type PullOption func(*pullOptions)

PullOption provides a way for setting specific options while pulling changes from the remote. Each supported option can customize how changes are pulled from the remote and integrated into the current repository (working directory)

func WithFetchAll added in v0.7.0

func WithFetchAll() PullOption

WithFetchAll will fetch the latest changes from all tracked remotes

func WithFetchDepthTo added in v0.7.0

func WithFetchDepthTo(depth int) PullOption

WithFetchDepthTo will limit the number of commits to be fetched from the remotes history. If fetching into a shallow clone of a repository, this can be used to shorten or deepen the existing history

func WithFetchForce added in v0.7.0

func WithFetchForce() PullOption

WithFetchForce will force the fetching of a remote branch into a local branch with a different name (or refspec). Default behavior within git prevents such an operation. Typically used in conjunction with the WithFetchRefSpecs option

func WithFetchIgnoreTags added in v0.7.0

func WithFetchIgnoreTags() PullOption

WithFetchIgnoreTags disables local tracking of tags from the remote

func WithFetchTags added in v0.7.0

func WithFetchTags() PullOption

WithFetchTags will fetch all tags from the remote into local tag references with the same name

func WithPullConfig added in v0.6.0

func WithPullConfig(kv ...string) PullOption

WithPullConfig allows temporary git config to be set while pulling changes from the remote. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

func WithPullRefSpecs added in v0.7.0

func WithPullRefSpecs(refs ...string) PullOption

WithPullRefSpecs allows remote references to be cherry-picked and fetched into the current repository (working copy) during a pull. A reference (or refspec) can be as simple as a name, where git will automatically resolve any ambiguity, or as explicit as providing a source and destination for reference within the remote. Check out the official git documentation on how to write a more complex [refspec] [refspec]: https://git-scm.com/docs/git-pull#Documentation/git-pull.txt-ltrefspecgt

type PushOption added in v0.3.0

type PushOption func(*pushOptions)

PushOption provides a way of setting specific options during a git push operation. Each supported option can customize the way in which references are pushed back to the remote

func WithAllBranches added in v0.3.0

func WithAllBranches() PushOption

WithAllBranches will push all locally created branch references back to the remote

func WithAllTags added in v0.3.0

func WithAllTags() PushOption

WithAllTags will push all locally created tag references back to the remote

func WithDeleteRefSpecs added in v0.6.0

func WithDeleteRefSpecs(refs ...string) PushOption

WithDeleteRefSpecs will trigger the deletion of any named references when pushed back to the remote

func WithPushConfig added in v0.6.0

func WithPushConfig(kv ...string) PushOption

WithPushConfig allows temporary git config to be set while pushing changes to the remote. Config set using this approach will override any config defined within existing git config files. Config must be provided as key value pairs, mismatched config will result in an ErrMissingConfigValue error. Any invalid paths will result in an ErrInvalidConfigPath error

func WithPushOptions added in v0.5.0

func WithPushOptions(options ...string) PushOption

WithPushOptions allows any number of aribitrary strings to be pushed to the remote server. All options are transmitted in their received order. A server must have the git config setting receive.advertisePushOptions set to true to receive push options

func WithRefSpecs added in v0.3.0

func WithRefSpecs(refs ...string) PushOption

WithRefSpecs allows local references to be cherry-picked and pushed back to the remote. A reference (or refspec) can be as simple as a name, where git will automatically resolve any ambiguity, or as explicit as providing a source and destination for each local reference within the remote. Check out the official git documentation on how to write a more complex refspec

type Repository added in v0.2.0

type Repository struct {
	// DetachedHead is true if the current repository HEAD points to a
	// specific commit, rather than a branch
	DetachedHead bool

	// DefaultBranch is the initial branch that is checked out when
	// a repository is cloned
	DefaultBranch string

	// Origin contains the URL of the remote which this repository
	// was cloned from
	Origin string

	// Remotes will contain all of the remotes and their URLs as
	// configured for this repository
	Remotes map[string]string

	// RootDir contains the path to the cloned directory
	RootDir string

	// ShallowClone is true if the current repository has been cloned
	// to a specified depth without the entire commit history
	ShallowClone bool
}

Repository provides a snapshot of the current state of a repository (working directory)

type Signature added in v0.6.0

type Signature struct {
	// Fingerprint contains the fingerprint of the private key used
	// during key verification
	Fingerprint string

	// Author represents the person associated with the private key
	Author *Person
}

Signature contains details about a GPG signature

type SortKey added in v0.3.0

type SortKey string

SortKey represents a structured field name that can be used as a sort key when analysing referenced objects such as tags

const (
	// CreatorDate sorts the reference in ascending order by the creation date
	// of the underlying commit
	CreatorDate SortKey = "creatordate"

	// CreatorDateDesc sorts the reference in descending order by the creation date
	// of the underlying commit
	CreatorDateDesc SortKey = "-creatordate"

	// RefName sorts the reference by its name in ascending lexicographic order
	RefName SortKey = "refname"

	// RefNameDesc sorts the reference by its name in descending lexicographic order
	RefNameDesc SortKey = "-refname"

	// TaggerDate sorts the reference in ascending order by its tag creation date
	TaggerDate SortKey = "taggerdate"

	// TaggerDateDesc sorts the reference in descending order by its tag
	// creation date
	TaggerDateDesc SortKey = "-taggerdate"

	// Version interpolates the references as a version number and sorts in
	// ascending order
	Version SortKey = "version:refname"

	// VersionDesc interpolates the references as a version number and sorts in
	// descending order
	VersionDesc SortKey = "-version:refname"
)

func (SortKey) String added in v0.3.0

func (k SortKey) String() string

String converts the sort key from an enum into its string counterpart

type StageOption added in v0.2.0

type StageOption func(*stageOptions)

StageOption provides a way for setting specific options during a stage operation. Each supported option can customize the way files are staged within the current repository (working directory)

func WithPathSpecs added in v0.2.0

func WithPathSpecs(specs ...string) StageOption

WithPathSpecs permits a series of PathSpecs (or globs) to be defined that will stage any matching files within the current repository (working directory). Paths to files and folders are relative to the root of the repository. All leading and trailing whitespace will be trimmed from the file paths, allowing empty paths to be ignored

type TagAnnotation added in v0.6.0

type TagAnnotation struct {
	// Tagger represents a person who created the tag
	Tagger Person

	// TaggerDate contains the date and time of when the tagger created
	// the tag within the repository
	TaggerDate time.Time

	// Message contains the annotated message associated with the tag
	Message string
}

TagAnnotation contains details about an annotation associated with a tag within a repository

type TagDetails added in v0.6.0

type TagDetails struct {
	// Annotation contains optional details about the annotation associated
	// with the tag
	Annotation *TagAnnotation

	// Commit contains details about the associated commit
	Commit CommitDetails

	// Ref contains the unique identifier associated with the tag
	Ref string
}

TagDetails contains details about a specific tag within a repository

type TagFilter added in v0.4.0

type TagFilter func(tag string) bool

TagFilter allows a tag to be filtered based on any user-defined criteria. If the filter returns true, the tag will be included within the filtered results:

componentFilter := func(tag string) bool {
	return strings.HasPrefix(tag, "component/")
}

type TagVerification added in v0.5.0

type TagVerification struct {
	// Annotation contains the annotated message associated with
	// the tag
	Annotation string

	// Ref contains the unique identifier associated with the tag
	Ref string

	// Signature contains details of the verified GPG signature
	Signature *Signature

	// Tagger represents a person who created the tag
	Tagger Person
}

TagVerification contains details about a GPG signed tag

type TreeDetails added in v0.6.0

type TreeDetails struct {
	// Entries contains the file and directory listing within a tree
	Entries []string

	// Ref contains the unique identifier associated with the tree
	Ref string
}

TreeDetails contains details about a specifc tree within a repository

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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