From 4096e343f8c139316bab5fec6fba3d4365c3bef8 Mon Sep 17 00:00:00 2001 From: "Gabriel A. Giovanini" Date: Sun, 21 Jul 2024 16:51:40 +0200 Subject: feat: Sort tags --- pkg/git/git.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/pkg/git/git.go b/pkg/git/git.go index 7341c1b..a9c42ce 100644 --- a/pkg/git/git.go +++ b/pkg/git/git.go @@ -8,6 +8,7 @@ import ( "io" "io/fs" "path" + "sort" "time" "github.com/go-git/go-git/v5" @@ -26,10 +27,12 @@ type ( GitRepository struct { path string repository *git.Repository - - ref plumbing.Hash - // this is setRef when ref is setRef - setRef bool + ref plumbing.Hash + setRef bool + } + TagReference struct { + ref *plumbing.Reference + tag *object.Tag } infoWrapper struct { name string @@ -38,10 +41,9 @@ type ( modTime time.Time isDir bool } - - TagReference struct { - ref *plumbing.Reference - tag *object.Tag + tagList struct { + refs []*TagReference + r *git.Repository } ) @@ -152,6 +154,10 @@ func (g *GitRepository) Tags() ([]*TagReference, error) { return nil, err } + // tagList modify the underlying tag list. + tagList := &tagList{r: g.repository, refs: tags} + sort.Sort(tagList) + return tags, nil } @@ -395,3 +401,40 @@ func (t *TagReference) Message() string { return "" } + +func (self *tagList) Len() int { + return len(self.refs) +} + +func (self *tagList) Swap(i, j int) { + self.refs[i], self.refs[j] = self.refs[j], self.refs[i] +} + +func (self *tagList) Less(i, j int) bool { + var dateI time.Time + var dateJ time.Time + + if self.refs[i].tag != nil { + dateI = self.refs[i].tag.Tagger.When + } else { + c, err := self.r.CommitObject(self.refs[i].ref.Hash()) + if err != nil { + dateI = time.Now() + } else { + dateI = c.Committer.When + } + } + + if self.refs[j].tag != nil { + dateJ = self.refs[j].tag.Tagger.When + } else { + c, err := self.r.CommitObject(self.refs[j].ref.Hash()) + if err != nil { + dateJ = time.Now() + } else { + dateJ = c.Committer.When + } + } + + return dateI.After(dateJ) +} -- cgit v1.2.3