Skip to content

Commit 57fa9b0

Browse files
authored
Support shortened commit SHAs in URLs (#13686)
* Support shortened commit SHAs in URLs and API * Add test case for short sha * Fix format * Revert API support * Add canonical link headers for short commit ID URLs
1 parent 72e62ac commit 57fa9b0

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

modules/context/repo.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"code.gitea.io/gitea/modules/markup/markdown"
2020
"code.gitea.io/gitea/modules/setting"
2121
api "code.gitea.io/gitea/modules/structs"
22+
"code.gitea.io/gitea/modules/util"
2223

2324
"gitea.com/macaron/macaron"
2425
"github.com/editorconfig/editorconfig-core-go/v2"
@@ -672,8 +673,11 @@ func getRefName(ctx *Context, pathType RepoRefType) string {
672673
if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
673674
return refName
674675
}
675-
if refName := getRefName(ctx, RepoRefCommit); len(refName) > 0 {
676-
return refName
676+
// For legacy and API support only full commit sha
677+
parts := strings.Split(path, "/")
678+
if len(parts) > 0 && len(parts[0]) == 40 {
679+
ctx.Repo.TreePath = strings.Join(parts[1:], "/")
680+
return parts[0]
677681
}
678682
if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
679683
return refName
@@ -686,7 +690,7 @@ func getRefName(ctx *Context, pathType RepoRefType) string {
686690
return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
687691
case RepoRefCommit:
688692
parts := strings.Split(path, "/")
689-
if len(parts) > 0 && len(parts[0]) == 40 {
693+
if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= 40 {
690694
ctx.Repo.TreePath = strings.Join(parts[1:], "/")
691695
return parts[0]
692696
}
@@ -778,7 +782,7 @@ func RepoRefByType(refType RepoRefType) macaron.Handler {
778782
return
779783
}
780784
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
781-
} else if len(refName) == 40 {
785+
} else if len(refName) >= 7 && len(refName) <= 40 {
782786
ctx.Repo.IsViewCommit = true
783787
ctx.Repo.CommitID = refName
784788

@@ -787,6 +791,11 @@ func RepoRefByType(refType RepoRefType) macaron.Handler {
787791
ctx.NotFound("GetCommit", err)
788792
return
789793
}
794+
// If short commit ID add canonical link header
795+
if len(refName) < 40 {
796+
ctx.Header().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"",
797+
util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), refName, ctx.Repo.Commit.ID.String(), 1))))
798+
}
790799
} else {
791800
ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
792801
return

0 commit comments

Comments
 (0)