// Copyright 2026 The Gotea Authors. All rights reserved. // SPDX-License-Identifier: MIT package got import ( "context" "errors" "fmt" "os/exec" "strings" ) // validRefName rejects names that got would read as an option or that no // reference can have. Placement is the caller's job; this only keeps the // argument list intact and stops the obvious garbage. func validRefName(name string) bool { if name == "" || strings.HasPrefix(name, "-") || strings.ContainsAny(name, " \t\n\r") { return false } return true } // RefExists reports whether the repository has a reference with exactly that // name that resolves to an object, matching git show-ref --verify. Two got // behaviours make that harder than the exit status: // // - got exits 0 and prints nothing for an unknown name, so the answer is the // ": " line, not the command result. // - in an empty repository got still lists HEAD, as "HEAD: refs/heads/main", // pointing at a branch that does not exist yet. A symbolic entry therefore // only counts when its target resolves. // // A bare object ID is not a reference and answers false, again like // show-ref --verify; callers that pass a commit ID rely on that. func RefExists(ctx context.Context, path, name string) (bool, error) { for range maxSymbolicDepth { if !validRefName(name) { return false, nil } out, _, err := run(ctx, "ref", "-l", "-r", path, name) if err != nil { if strings.Contains(err.Error(), "bad reference name") { return false, nil } return false, err } prefix := name + ": " var value string var found bool for _, line := range strings.Split(out, "\n") { if v, ok := strings.CutPrefix(line, prefix); ok { value, found = strings.TrimSpace(v), true break } } if !found { return false, nil } if isObjectID(value) { return true, nil } name = value // symbolic: resolve its target before answering } return false, nil } // maxSymbolicDepth bounds symbolic reference chains; git limits them too, and // a loop must not hang the caller. const maxSymbolicDepth = 5 // RefObjectID returns the object a reference points at. A symbolic reference // reports its target instead of an object, which is an error here. func RefObjectID(ctx context.Context, path, name string) (string, error) { if !validRefName(name) { return "", fmt.Errorf("invalid reference name: %q", name) } out, _, err := run(ctx, "ref", "-l", "-r", path, name) if err != nil { return "", err } prefix := name + ": " for _, line := range strings.Split(out, "\n") { value, ok := strings.CutPrefix(line, prefix) if !ok { continue } value = strings.TrimSpace(value) if isObjectID(value) { return value, nil } return "", fmt.Errorf("reference %s is not an object: %s", name, value) } return "", ErrRefNotFound{Name: name} } // ObjectExists reports whether name resolves to an object known to the // repository. It accepts full and abbreviated object IDs, refs and tags, but it // does not resolve path names (got cat without -P). This matches git cat-file // -e semantics closely enough for gotea's IsReferenceExist callers, which pass // either refs or commit/object IDs. func ObjectExists(ctx context.Context, path, name string) (bool, error) { if strings.TrimSpace(name) == "" { return false, nil } _, stderr, err := run(ctx, "cat", "-r", path, name) if err == nil { return true, nil } if errors.Is(err, ErrNotInstalled) { return false, err } // got cat exits 1 for "not found"/unresolvable; other exit codes or // transport errors are real failures. msg := strings.ToLower(stderr) if strings.Contains(msg, "not found") || strings.Contains(msg, "no such") || strings.Contains(msg, "needed a single revision") || strings.Contains(msg, "reference ") { return false, nil } var exitErr *exec.ExitError if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 { return false, nil } return false, err } // ListRefs returns ": " lines for refs matching prefix. An empty // prefix lists all refs. func ListRefs(ctx context.Context, path, prefix string) ([]string, error) { args := []string{"ref", "-l", "-r", path} if prefix != "" { args = append(args, prefix) } out, _, err := run(ctx, args...) if err != nil { return nil, err } var lines []string for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) if line != "" { lines = append(lines, line) } } return lines, nil } // ResolveRefID returns the object ID a reference points at. It accepts full // ref names (refs/...) and HEAD. For annotated tags this is the tag object ID, // matching git show-ref / ref hash semantics. func ResolveRefID(ctx context.Context, path, name string) (string, error) { if strings.TrimSpace(name) == "" { return "", fmt.Errorf("empty reference") } id, err := RefObjectID(ctx, path, name) if err == nil { return id, nil } var notFound ErrRefNotFound if errors.As(err, ¬Found) { return "", err } msg := strings.ToLower(err.Error()) if strings.Contains(msg, "not found") || strings.Contains(msg, "reference ") { return "", ErrRefNotFound{Name: name} } return "", err } // ResolveCommitID returns the full commit ID for a revision argument. It accepts // full/abbreviated commit IDs, refs and symbolic refs such as HEAD. Only commit // objects are resolved; callers that need arbitrary object IDs should use // ObjectExists/another path. func ResolveCommitID(ctx context.Context, path, rev string) (string, error) { if strings.TrimSpace(rev) == "" { return "", fmt.Errorf("empty revision") } out, stderr, err := run(ctx, "log", "-r", path, "-c", rev, "-l1") if err != nil { msg := strings.ToLower(stderr + out) if strings.Contains(msg, "not found") || strings.Contains(msg, "no such") || strings.Contains(msg, "reference ") || strings.Contains(msg, "unknown") { return "", ErrRefNotFound{Name: rev} } var exitErr *exec.ExitError if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 { return "", ErrRefNotFound{Name: rev} } return "", err } for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "commit ") { continue } fields := strings.Fields(line) if len(fields) >= 2 && isObjectID(fields[1]) { return fields[1], nil } } return "", fmt.Errorf("got log: commit id not found for %q", rev) } // ErrRefNotFound reports a missing reference. type ErrRefNotFound struct { Name string } func (e ErrRefNotFound) Error() string { return "reference not found: " + e.Name }