2021-07-13 07:14:14 +00:00
|
|
|
// Copyright 2021 The Gitea Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2022-04-30 14:32:01 +00:00
|
|
|
"fmt"
|
2021-07-13 07:14:14 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"code.gitea.io/gitea/modules/context"
|
|
|
|
"code.gitea.io/gitea/modules/git"
|
2022-07-25 15:39:42 +00:00
|
|
|
"code.gitea.io/gitea/modules/log"
|
2021-07-13 07:14:14 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ResolveRefOrSha resolve ref to sha if exist
|
|
|
|
func ResolveRefOrSha(ctx *context.APIContext, ref string) string {
|
|
|
|
if len(ref) == 0 {
|
|
|
|
ctx.Error(http.StatusBadRequest, "ref not given", nil)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2022-07-25 15:39:42 +00:00
|
|
|
sha := ref
|
2021-07-13 07:14:14 +00:00
|
|
|
// Search branches and tags
|
|
|
|
for _, refType := range []string{"heads", "tags"} {
|
|
|
|
refSHA, lastMethodName, err := searchRefCommitByType(ctx, refType, ref)
|
|
|
|
if err != nil {
|
|
|
|
ctx.Error(http.StatusInternalServerError, lastMethodName, err)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
if refSHA != "" {
|
2022-07-25 15:39:42 +00:00
|
|
|
sha = refSHA
|
|
|
|
break
|
2021-07-13 07:14:14 +00:00
|
|
|
}
|
|
|
|
}
|
2022-07-25 15:39:42 +00:00
|
|
|
|
2022-07-30 08:09:04 +00:00
|
|
|
if ctx.Repo.GitRepo != nil {
|
|
|
|
err := ctx.Repo.GitRepo.AddLastCommitCache(ctx.Repo.Repository.GetCommitsCountCacheKey(ref, ref != sha), ctx.Repo.Repository.FullName(), sha)
|
2022-07-25 15:39:42 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Error("Unable to get commits count for %s in %s. Error: %v", sha, ctx.Repo.Repository.FullName(), err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sha
|
2021-07-13 07:14:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetGitRefs return git references based on filter
|
|
|
|
func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, string, error) {
|
|
|
|
if ctx.Repo.GitRepo == nil {
|
2022-04-30 14:32:01 +00:00
|
|
|
return nil, "", fmt.Errorf("no open git repo found in context")
|
2021-07-13 07:14:14 +00:00
|
|
|
}
|
|
|
|
if len(filter) > 0 {
|
|
|
|
filter = "refs/" + filter
|
|
|
|
}
|
|
|
|
refs, err := ctx.Repo.GitRepo.GetRefsFiltered(filter)
|
|
|
|
return refs, "GetRefsFiltered", err
|
|
|
|
}
|
|
|
|
|
|
|
|
func searchRefCommitByType(ctx *context.APIContext, refType, filter string) (string, string, error) {
|
2022-01-20 17:46:10 +00:00
|
|
|
refs, lastMethodName, err := GetGitRefs(ctx, refType+"/"+filter) // Search by type
|
2021-07-13 07:14:14 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", lastMethodName, err
|
|
|
|
}
|
|
|
|
if len(refs) > 0 {
|
2022-01-20 17:46:10 +00:00
|
|
|
return refs[0].Object.String(), "", nil // Return found SHA
|
2021-07-13 07:14:14 +00:00
|
|
|
}
|
|
|
|
return "", "", nil
|
|
|
|
}
|