package git import ( "bytes" "fmt" "strings" ) // Tag is a tag ref in the repository. Commit is the commit the tag points // at (dereferenced for an annotated tag); Annotated reports whether the tag // is an annotated tag object rather than a lightweight ref. type Tag struct { Name string Commit string Annotated bool } // Tags lists refs/tags, sorted by name. for-each-ref's %(*objectname) // dereferences an annotated tag to the commit it names, so both tag kinds // report a commit SHA. func Tags(repoPath string) ([]Tag, error) { cmd := gitCommand(repoPath, "for-each-ref", "--format=%(refname:short) %(objecttype) %(objectname) %(*objectname)", "refs/tags/") var stderr bytes.Buffer cmd.Stderr = &stderr out, err := cmd.Output() if err != nil { return nil, fmt.Errorf("git for-each-ref refs/tags/ in %s: %w: %s", repoPath, err, strings.TrimSpace(stderr.String())) } var tags []Tag for _, line := range strings.Split(string(out), "\n") { fields := strings.Fields(line) if len(fields) < 3 { continue } tag := Tag{Name: fields[0], Annotated: fields[1] == "tag"} switch { case len(fields) >= 4: tag.Commit = fields[3] case tag.Annotated: // Annotated tag whose target is not a commit: resolve it. if sha, err := ResolveCommit(repoPath, fields[0]); err == nil { tag.Commit = sha } default: tag.Commit = fields[2] } tags = append(tags, tag) } return tags, nil }