// Copyright 2026 The Gotea Authors. All rights reserved. // SPDX-License-Identifier: MIT // Package got wraps the got(1) binary for repository operations that Gotea // has migrated off git. Keep all got process handling in this package. package got import ( "context" "errors" "fmt" "os" "os/exec" "path/filepath" "slices" "strings" "gotea.dev/modules/setting" ) // ErrNotInstalled means the configured got executable could not be started. var ErrNotInstalled = errors.New("got executable not found") // Executable returns the configured got path, defaulting to "got". func Executable() string { path := strings.TrimSpace(setting.Git.GotPath) if path == "" { return "got" } return path } // checkTarget validates a "-r" target first. got resolves "-r" by searching // upwards, so a directory that is not a repository - a fixture missing its // refs, a plain path - silently answers for whatever repository encloses it // and the caller reads another repository's refs. Refuse that instead. func checkTarget(path string) error { if err := ensureLayout(path); err != nil { return err } if IsRepository(path) { return nil } if _, err := os.Stat(filepath.Join(path, ".git")); err == nil { return nil // a work tree, got uses its .git directory } return fmt.Errorf("not a repository: %s", path) } func run(ctx context.Context, args ...string) (stdout, stderr string, err error) { if i := slices.Index(args, "-r"); i >= 0 && i+1 < len(args) { if err := checkTarget(args[i+1]); err != nil { return "", "", err } } cmd := exec.CommandContext(ctx, Executable(), args...) var out, errOut strings.Builder cmd.Stdout = &out cmd.Stderr = &errOut err = cmd.Run() if err != nil { if errors.Is(err, exec.ErrNotFound) { return out.String(), errOut.String(), ErrNotInstalled } return out.String(), errOut.String(), fmt.Errorf("got %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errOut.String())) } return out.String(), errOut.String(), nil } // Version returns the got version without the leading "got ". func Version(ctx context.Context) (string, error) { out, _, err := run(ctx, "--version") if err != nil { return "", err } fields := strings.Fields(strings.TrimSpace(out)) if len(fields) < 2 || fields[0] != "got" { return "", fmt.Errorf("unexpected got version output: %q", strings.TrimSpace(out)) } return fields[1], nil } // IsRepository reports whether path looks like a bare Git-format repository. func IsRepository(path string) bool { if st, err := os.Stat(filepath.Join(path, "HEAD")); err != nil || !st.Mode().IsRegular() { return false } if st, err := os.Stat(filepath.Join(path, "objects")); err != nil || !st.IsDir() { return false } return true } // InitBare creates a bare repository at path, or leaves an existing one alone. // objectFormat must be "sha1" or "sha256". func InitBare(ctx context.Context, path, objectFormat, defaultBranch string) error { if objectFormat == "" { objectFormat = "sha1" } if objectFormat != "sha1" && objectFormat != "sha256" { return fmt.Errorf("invalid got object format: %s", objectFormat) } if IsRepository(path) { return nil } if err := os.MkdirAll(path, 0o755); err != nil { return fmt.Errorf("create repository directory: %w", err) } if defaultBranch == "" { defaultBranch = "main" } _, _, err := run(ctx, "init", "-A", objectFormat, "-b", defaultBranch, path) return err } // ensureLayout creates the repository layout git tolerates but got requires: // existing objects/pack, refs/heads and refs/tags directories. A real // repository always has them (git init and got init both create them), but a // repository copied without empty directories - a test fixture checked into // git, an unpacked archive - loses them, and then got refuses the repository // and may resolve "-r" to an enclosing one. Creating those directories is // content-free and idempotent. func ensureLayout(path string) error { if !IsRepository(path) { return nil } for _, dir := range []string{ filepath.Join("objects", "pack"), filepath.Join("refs", "heads"), filepath.Join("refs", "tags"), } { full := filepath.Join(path, dir) if st, err := os.Stat(full); err == nil && st.IsDir() { continue } if err := os.MkdirAll(full, 0o755); err != nil { return fmt.Errorf("repair repository layout %s: %w", path, err) } } return nil } func isObjectID(s string) bool { if len(s) != 40 && len(s) != 64 { return false } for i := 0; i < len(s); i++ { c := s[i] if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { return false } } return true } // IsEmpty reports whether the repository has no reference pointing at an object. func IsEmpty(ctx context.Context, path string) (bool, error) { out, _, err := run(ctx, "ref", "-l", "-r", path) if err != nil { return false, err } for _, line := range strings.Split(out, "\n") { _, value, ok := strings.Cut(line, ": ") if ok && isObjectID(strings.TrimSpace(value)) { return false, nil } } return true, nil } // DefaultBranch returns the branch HEAD points at. func DefaultBranch(ctx context.Context, path string) (string, error) { out, _, err := run(ctx, "ref", "-l", "-r", path, "HEAD") if err != nil { return "", err } for _, line := range strings.Split(out, "\n") { ref, ok := strings.CutPrefix(line, "HEAD: ") if !ok { continue } ref = strings.TrimSpace(ref) if branch, ok := strings.CutPrefix(ref, "refs/heads/"); ok { return branch, nil } return "", fmt.Errorf("HEAD is not a branch: %s", ref) } return "", fmt.Errorf("HEAD not found") } func validBranchName(name string) bool { if name == "" || name == "@" || strings.HasPrefix(name, "-") || strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") || strings.HasSuffix(name, ".") || strings.HasSuffix(name, ".lock") || strings.Contains(name, "..") || strings.Contains(name, "//") || strings.Contains(name, "@{") { return false } for _, r := range name { if r <= ' ' || r == 0x7f || r == '~' || r == '^' || r == ':' || r == '?' || r == '*' || r == '[' || r == '\\' { return false } } return true } func writeHead(path, branch string) error { tmp, err := os.CreateTemp(path, ".HEAD-") if err != nil { return err } name := tmp.Name() defer os.Remove(name) if _, err := fmt.Fprintf(tmp, "ref: refs/heads/%s\n", branch); err != nil { tmp.Close() return err } if err := tmp.Sync(); err != nil { tmp.Close() return err } if err := tmp.Close(); err != nil { return err } if err := os.Chmod(name, 0o644); err != nil { return err } return os.Rename(name, filepath.Join(path, "HEAD")) } // SetDefaultBranch points HEAD at branch. got ref -s needs the target branch to // exist, so an unborn branch falls back to writing HEAD in the repository format. func SetDefaultBranch(ctx context.Context, path, branch string) error { if !validBranchName(branch) { return fmt.Errorf("invalid branch name: %s", branch) } if !IsRepository(path) { return fmt.Errorf("not a repository: %s", path) } out, _, err := run(ctx, "ref", "-l", "-r", path, "refs/heads/"+branch) if err != nil { if errors.Is(err, ErrNotInstalled) { return err } return writeHead(path, branch) } if strings.Contains(out, ": ") { _, _, err = run(ctx, "ref", "-s", "refs/heads/"+branch, "HEAD", "-r", path) return err } return writeHead(path, branch) } // BranchCommitID returns the object ID of the named local branch. func BranchCommitID(ctx context.Context, path, branch string) (string, error) { if !validBranchName(branch) { return "", fmt.Errorf("invalid branch name: %s", branch) } ref := "refs/heads/" + branch out, _, err := run(ctx, "ref", "-l", "-r", path, ref) if err != nil { return "", err } prefix := ref + ": " for _, line := range strings.Split(out, "\n") { id, ok := strings.CutPrefix(line, prefix) if ok { id = strings.TrimSpace(id) if isObjectID(id) { return id, nil } return "", fmt.Errorf("invalid object ID for %s: %s", ref, id) } } return "", fmt.Errorf("branch not found: %s", branch) }