simplegit

package git

import (
	"bytes"
	"fmt"
	"strings"
)

// tagMessageLimit bounds the tag object read; tag messages are small, and
// the cap exists to keep a corrupted or hostile tag from eating memory.
const tagMessageLimit = 64 << 10

// 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.SplitSeq(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
}

// TagMessage returns an annotated tag's subject (first message line) and
// body (the remaining lines, trimmed). For a missing or lightweight tag —
// or a tag with an empty message — found is false and there is no error.
// The tag object is read bounded so a hostile tag cannot exhaust memory.
func TagMessage(repoPath, name string) (subject, body string, found bool, err error) {
	exists, err := RefExists(repoPath, "refs/tags/"+name)
	if err != nil {
		return "", "", false, err
	}
	if !exists {
		return "", "", false, nil
	}

	cmd := gitCommand(repoPath, "cat-file", "-t", "refs/tags/"+name)
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	objType, err := cmd.Output()
	if err != nil {
		return "", "", false, fmt.Errorf("git cat-file -t %s in %s: %w: %s", name, repoPath, err, strings.TrimSpace(stderr.String()))
	}
	if strings.TrimSpace(string(objType)) != "tag" {
		return "", "", false, nil // lightweight tag: no tag object, no message
	}

	cmd = gitCommand(repoPath, "cat-file", "tag", "refs/tags/"+name)
	stderr.Reset()
	cmd.Stderr = &stderr
	out, oversized, err := runBounded(cmd, tagMessageLimit)
	if err != nil {
		return "", "", false, fmt.Errorf("git cat-file tag %s in %s: %w: %s", name, repoPath, err, strings.TrimSpace(stderr.String()))
	}
	if oversized {
		return "", "", false, fmt.Errorf("git cat-file tag %s in %s: tag object is too large", name, repoPath)
	}
	// A tag object is a header, a blank line, then the message. Everything
	// after the first blank line is the message.
	lines := strings.Split(string(out), "\n")
	start := -1
	for i, line := range lines {
		if line == "" {
			start = i + 1
			break
		}
	}
	if start < 0 || start >= len(lines) {
		return "", "", false, nil
	}
	message := strings.TrimRight(strings.Join(lines[start:], "\n"), "\n")
	if message == "" {
		return "", "", false, nil
	}
	subject = message
	if before, after, ok := strings.Cut(message, "\n"); ok {
		subject, body = before, strings.TrimSpace(after)
	}
	return subject, body, true, nil
}