summaryrefslogtreecommitdiffstats
path: root/pkg/commands/loading_tags.go
blob: ae2f0ba1717963419b4b694d315414a073665d9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package commands

import (
	"regexp"
	"sort"
	"strings"

	"github.com/jesseduffield/lazygit/pkg/utils"
)

const semverRegex = `v?((\d+\.?)+)([^\d]?.*)`

func (c *GitCommand) GetTags() ([]*Tag, error) {
	// get remote branches
	remoteBranchesStr, err := c.OSCommand.RunCommandWithOutput(`git tag --list`)
	if err != nil {
		return nil, err
	}

	content := utils.TrimTrailingNewline(remoteBranchesStr)
	if content == "" {
		return nil, nil
	}

	split := strings.Split(content, "\n")

	// first step is to get our remotes from go-git
	tags := make([]*Tag, len(split))
	for i, tagName := range split {

		tags[i] = &Tag{
			Name: tagName,
		}
	}

	// now lets sort our tags by name numerically
	re := regexp.MustCompile(semverRegex)

	// the reason  this is complicated is because we're both sorting alphabetically
	// and when we're dealing with semver strings
	sort.Slice(tags, func(i, j int) bool {
		a := tags[i].Name
		b := tags[j].Name

		matchA := re.FindStringSubmatch(a)
		matchB := re.FindStringSubmatch(b)

		if len(matchA) > 0 && len(matchB) > 0 {
			numbersA := strings.Split(matchA[1], ".")
			numbersB := strings.Split(matchB[1], ".")
			k := 0
			for {
				if len(numbersA) == k && len(numbersB) == k {
					break
				}
				if len(numbersA) == k {
					return true
				}
				if len(numbersB) == k {
					return false
				}
				if mustConvertToInt(numbersA[k]) < mustConvertToInt(numbersB[k]) {
					return true
				}
				if mustConvertToInt(numbersA[k]) > mustConvertToInt(numbersB[k]) {
					return false
				}
				k++
			}

			return strings.ToLower(matchA[3]) < strings.ToLower(matchB[3])
		}

		return strings.ToLower(a) < strings.ToLower(b)
	})

	return tags, nil
}