From 2f1de6fc411596661050cb8ac51f80f83e069dcf Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Thu, 13 Jul 2023 11:51:07 +0300 Subject: [PATCH] Use merge-base as a starting point Set it to target branch and check only the commits we are interested in. If the commit is already in the branch, we just get an old behaviour. Signed-off-by: Evgenii Stratonikov --- main.go | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 3d10edf..95a7fe5 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "strings" git "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" gha "github.com/sethvargo/go-githubactions" ) @@ -37,14 +38,17 @@ func main() { } // Limit number of iterations. - from := gha.GetInput("from") + var lca *object.Commit + if from := gha.GetInput("from"); from != "" { + lca = getMergeBase(r, head, from) + } // Processing result. var fail bool _ = commits.ForEach(func(c *object.Commit) error { // Stop iterator when limit is reached. - if len(from) != 0 && strings.HasPrefix(c.ID().String(), from) { + if lca != nil && c.Hash == lca.Hash { return errors.New("stop") } @@ -81,3 +85,27 @@ func main() { os.Exit(1) } } + +func getMergeBase(r *git.Repository, head *plumbing.Reference, from string) *object.Commit { + h, err := r.ResolveRevision(plumbing.Revision(from)) + if err != nil { + log.Fatalf("Failed to resolve a reference: %v", err) + } + + to, err := r.CommitObject(*h) + if err != nil { + log.Fatalf("Failed to get commit object: %v", err) + } + + other, err := r.CommitObject(head.Hash()) + if err != nil { + log.Fatalf("Failed to get HEAD commit object: %v", err) + } + + cc, err := to.MergeBase(other) + if err != nil { + log.Fatalf("Failed to determine merge-base: %v", err) + } + + return cc[0] +}