From 341f624409f072e0a6ff6318e3fe95ab0b1d86b2 Mon Sep 17 00:00:00 2001 From: "James E. Blair" Date: Wed, 27 Mar 2019 11:36:18 -0700 Subject: [PATCH] Support shortened commit SHAs in URLs (#6450) This supports using a git SHA of any length between 7 and 40 characters in URLs (e.g. /src/commit/SHA/...). Previously only commit SHAs of the full 40 character length were supported. The RepoRefAny ref type is used in one place, in the /api/v1/user/repo/raw API endpoint where it is used to guess whether the remainder of the path is a ref name followed by a file path or merely a file path. There is no good way to guess whether a shortened SHA is intended in that circumstance (e.g., /raw/beefcafe/README.txt could be /README.txt in the beefcafe{..32} commit, or /beefcafe/README.txt on the master branch). For this case, we don't support shortened SHAs and only match on the full one. Signed-off-by: James E. Blair --- modules/context/repo.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/modules/context/repo.go b/modules/context/repo.go index 20a3d1942835e..4145cd2c0dd01 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -475,8 +475,10 @@ const ( RepoRefBranch // RepoRefTag tag RepoRefTag - // RepoRefCommit commit + // RepoRefCommit short or long commit RepoRefCommit + // RepoRefFullCommit long commit only + RepoRefFullCommit // RepoRefBlob blob RepoRefBlob ) @@ -511,7 +513,7 @@ 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 { + if refName := getRefName(ctx, RepoRefFullCommit); len(refName) > 0 { return refName } if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 { @@ -523,12 +525,18 @@ func getRefName(ctx *Context, pathType RepoRefType) string { return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist) case RepoRefTag: return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist) - case RepoRefCommit: + case RepoRefFullCommit: parts := strings.Split(path, "/") if len(parts) > 0 && len(parts[0]) == 40 { ctx.Repo.TreePath = strings.Join(parts[1:], "/") return parts[0] } + case RepoRefCommit: + parts := strings.Split(path, "/") + if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= 40 { + ctx.Repo.TreePath = strings.Join(parts[1:], "/") + return parts[0] + } case RepoRefBlob: _, err := ctx.Repo.GitRepo.GetBlob(path) if err != nil { @@ -611,7 +619,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