Skip to content

Instantly share code, notes, and snippets.

@dipankardas011
Last active October 11, 2024 04:48
Show Gist options
  • Save dipankardas011/2a218f55944ab403a3f944ea6460a9d0 to your computer and use it in GitHub Desktop.
Save dipankardas011/2a218f55944ab403a3f944ea6460a9d0 to your computer and use it in GitHub Desktop.
git log without os exec
package main
import (
"fmt"
"sort"
"strconv"
"time"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
)
// CommitRef represents a commit hash and the date it was committed
type CommitRef struct {
DateTime time.Time `json:"datetime"`
Commit string `json:"commit"`
}
// GetFirstCommitEachWeek returns a slice of commit hashes,
// containing the first commit hash for each week of the given year.
func GetFirstCommitEachWeek(year string) ([]CommitRef, error) {
// Open the repository
repo, err := git.PlainOpen("........")
if err != nil {
return nil, fmt.Errorf("error opening repository: %v", err)
}
// Parse the year
yearInt, err := strconv.Atoi(year)
if err != nil {
return nil, fmt.Errorf("invalid year: %v", err)
}
// Construct date range for given year
since := time.Date(yearInt, 1, 1, 0, 0, 0, 0, time.UTC)
until := time.Date(yearInt+1, 1, 1, 0, 0, 0, 0, time.UTC)
// Get the HEAD reference
ref, err := repo.Head()
if err != nil {
return nil, fmt.Errorf("error getting HEAD: %v", err)
}
// Create a new LogOptions
logOptions := &git.LogOptions{
From: ref.Hash(),
Order: git.LogOrderCommitterTime,
Since: &since,
Until: &until,
}
// Get the commit iterator
iter, err := repo.Log(logOptions)
if err != nil {
return nil, fmt.Errorf("error creating log iterator: %v", err)
}
commits := make(map[int]CommitRef)
// Iterate through the commits
err = iter.ForEach(func(c *object.Commit) error {
_, week := c.Committer.When.ISOWeek()
if _, ok := commits[week]; !ok {
commits[week] = CommitRef{
DateTime: c.Committer.When,
Commit: c.Hash.String(),
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error iterating through commits: %v", err)
}
result := make([]CommitRef, 0, len(commits))
for _, commit := range commits {
result = append(result, commit)
}
sort.Slice(result, func(i, j int) bool {
return result[i].DateTime.Before(result[j].DateTime)
})
return result, nil
}
func main() {
year := "2024"
commits, err := GetFirstCommitEachWeek(year)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
for _, commit := range commits {
fmt.Printf("%v: %v\n", commit.DateTime.Format("2006-01-02"), commit.Commit)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment