diff --git a/modules/git/commit.go b/modules/git/commit.go index baad57045e..396ede32ec 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -12,6 +12,8 @@ import ( "strings" "gotea.dev/modules/git/gitcmd" + "gotea.dev/modules/git/gitrepo" + "gotea.dev/modules/got" "gotea.dev/modules/util" ) @@ -236,17 +238,21 @@ func (c *Commit) GetFileContent(ctx context.Context, gitRepo *Repository, filena // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository. func GetFullCommitID(ctx context.Context, repo RepositoryFacade, shortID string) (string, error) { - commitID, _, err := gitcmd.NewCommand("rev-parse"). - AddDynamicArguments(shortID). - WithRepo(repo). - RunStdString(ctx) + commitID, err := got.ResolveCommitID(ctx, gitrepo.RepoLocalPath(repo), shortID) if err != nil { - if gitcmd.IsErrorExitCode(err, 128) { + if errors.Is(err, got.ErrNotInstalled) { + return "", err + } + if _, ok := errors.AsType[got.ErrRefNotFound](err); ok { + return "", ErrNotExist{shortID, ""} + } + var refNF got.ErrRefNotFound + if errors.As(err, &refNF) { return "", ErrNotExist{shortID, ""} } return "", err } - return strings.TrimSpace(commitID), nil + return commitID, nil } func AddObjectMessageArgument(cmd *gitcmd.Command, typ ObjectType, message string) error { diff --git a/modules/got/ref.go b/modules/got/ref.go index 0261fdc84b..fb4b4012d6 100644 --- a/modules/got/ref.go +++ b/modules/got/ref.go @@ -124,6 +124,40 @@ func ObjectExists(ctx context.Context, path, name string) (bool, error) { return false, 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