Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Created December 30, 2020 12:48
Show Gist options
  • Save percybolmer/ee5ba09bcbaf6fded3969231d790d021 to your computer and use it in GitHub Desktop.
Save percybolmer/ee5ba09bcbaf6fded3969231d790d021 to your computer and use it in GitHub Desktop.
New repository struct
// Repository is a struct that holds an Opened github repository and the reference
type Repository struct {
path string
repo *git.Repository
ref *plumbing.Reference
}
// Open will open up a git repository
// and load the Head reference
func Open(path string) (*Repository, error) {
// Open the github repository
r, err := git.PlainOpen(path)
if err != nil {
return nil, fmt.Errorf("%v:%w", "Error opening Repository: ", err)
}
// Grab the Git HEAD reference
ref, err := r.Head()
if err != nil {
return nil, fmt.Errorf("%v:%w", "Unable to get repository HEAD:", err)
}
return &Repository{
path: path,
repo: r,
ref: ref,
}, nil
}
// GetCommits will extract commit history from the git repository
func (r *Repository) GetCommits() ([]*object.Commit, error) {
// Get the Commit history
cIter, err := r.repo.Log(&git.LogOptions{From: r.ref.Hash()})
if err != nil {
return nil, fmt.Errorf("%v:%w", "Unable to get repository commits:", err)
}
var commits []*object.Commit
err = cIter.ForEach(func(c *object.Commit) error {
commits = append(commits, c)
return nil
})
if err != nil {
return nil, fmt.Errorf("%v:%w", "Error getting commits :", err)
}
return commits, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment