Skip to content

Instantly share code, notes, and snippets.

@thrawn01
Created August 1, 2023 15:00
Show Gist options
  • Save thrawn01/a51d9bfaef73908280de342ead7aef2c to your computer and use it in GitHub Desktop.
Save thrawn01/a51d9bfaef73908280de342ead7aef2c to your computer and use it in GitHub Desktop.
Some golang code to search all commit hashes in a repo, including lost and unreachable hashes to find the string 'steve'.
package main
import (
"bytes"
"fmt"
"os/exec"
"sort"
"strings"
"time"
)
// Commit structure to hold commit hash and date
type Commit struct {
hash string
date time.Time
}
func main() {
cmd := exec.Command("git", "fsck", "--full", "--no-reflogs", "--unreachable", "--lost-found")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
panic(err)
}
lines := strings.Split(out.String(), "\n")
var commits []Commit
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) >= 3 && fields[1] == "commit" {
commitHash := fields[2]
// Get commit date
cmd := exec.Command("git", "show", "-s", "--format=%ci", commitHash)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
panic(err)
}
commitDate, err := time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(out.String()))
if err != nil {
panic(err)
}
commits = append(commits, Commit{hash: commitHash, date: commitDate})
}
}
// Sort commits by date in ascending order
sort.Slice(commits, func(i, j int) bool {
return commits[i].date.Before(commits[j].date)
})
// Search for "steve" in each commit and print matching commits
for _, commit := range commits {
cmd := exec.Command("git", "show", commit.hash)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
panic(err)
}
if strings.Contains(strings.ToLower(out.String()), "steve") {
cmd := exec.Command("git", "log", "--format=%B", "-n", "1", commit.hash)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
panic(err)
}
fmt.Printf("Commit: %s Message: %s", commit.hash, strings.TrimSuffix(out.String(), "\n"))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment