diff options
author | Lauris BH <lauris@nix.lv> | 2020-11-25 22:07:39 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-11-25 15:07:39 -0500 |
commit | 57fa9b0f25e4aa45bd813b1bffedb7ba3c929942 (patch) | |
tree | f32760e0cc615f459997683473e39688c88e8169 /modules/context/repo.go | |
parent | 72e62ac12b682831300add5879f11e7e9568eecb (diff) | |
download | gitea-57fa9b0f25e4aa45bd813b1bffedb7ba3c929942.tar.gz gitea-57fa9b0f25e4aa45bd813b1bffedb7ba3c929942.zip |
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
Diffstat (limited to 'modules/context/repo.go')
-rw-r--r-- | modules/context/repo.go | 17 |
1 files changed, 13 insertions, 4 deletions
diff --git a/modules/context/repo.go b/modules/context/repo.go index 8a2b99c854..2aee6caca4 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/modules/markup/markdown" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/util" "gitea.com/macaron/macaron" "github.com/editorconfig/editorconfig-core-go/v2" @@ -672,8 +673,11 @@ func getRefName(ctx *Context, pathType RepoRefType) string { if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 { return refName } - if refName := getRefName(ctx, RepoRefCommit); len(refName) > 0 { - return refName + // For legacy and API support only full commit sha + parts := strings.Split(path, "/") + if len(parts) > 0 && len(parts[0]) == 40 { + ctx.Repo.TreePath = strings.Join(parts[1:], "/") + return parts[0] } if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 { return refName @@ -686,7 +690,7 @@ func getRefName(ctx *Context, pathType RepoRefType) string { return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist) case RepoRefCommit: parts := strings.Split(path, "/") - if len(parts) > 0 && len(parts[0]) == 40 { + if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= 40 { ctx.Repo.TreePath = strings.Join(parts[1:], "/") return parts[0] } @@ -778,7 +782,7 @@ func RepoRefByType(refType RepoRefType) macaron.Handler { return } ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() - } else if len(refName) == 40 { + } else if len(refName) >= 7 && len(refName) <= 40 { ctx.Repo.IsViewCommit = true ctx.Repo.CommitID = refName @@ -787,6 +791,11 @@ func RepoRefByType(refType RepoRefType) macaron.Handler { ctx.NotFound("GetCommit", err) return } + // If short commit ID add canonical link header + if len(refName) < 40 { + ctx.Header().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"", + util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), refName, ctx.Repo.Commit.ID.String(), 1)))) + } } else { ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName)) return |