Skip to content

Commit e831254

Browse files
committed
fix
1 parent 54146e6 commit e831254

File tree

6 files changed

+91
-99
lines changed

6 files changed

+91
-99
lines changed

routers/api/v1/repo/file.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,12 @@ func GetRawFile(ctx *context.APIContext) {
5656
// required: true
5757
// - name: filepath
5858
// in: path
59-
// description: filepath of the file to get
59+
// description: path of the file to get, it should be "{ref}/{filepath}". If there is no ref could be inferred, it will be treated as the default branch
6060
// type: string
6161
// required: true
6262
// - name: ref
6363
// in: query
64-
// description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
64+
// description: "The name of the commit/branch/tag. Default the repository’s default branch"
6565
// type: string
6666
// required: false
6767
// responses:
@@ -109,12 +109,12 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
109109
// required: true
110110
// - name: filepath
111111
// in: path
112-
// description: filepath of the file to get
112+
// description: path of the file to get, it should be "{ref}/{filepath}". If there is no ref could be inferred, it will be treated as the default branch
113113
// type: string
114114
// required: true
115115
// - name: ref
116116
// in: query
117-
// description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
117+
// description: "The name of the commit/branch/tag. Default the repository’s default branch"
118118
// type: string
119119
// required: false
120120
// responses:

routers/web/web.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,7 +1323,7 @@ func registerRoutes(m *web.Router) {
13231323
m.Get(".rss", feedEnabled, repo.TagsListFeedRSS)
13241324
m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
13251325
}, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
1326-
repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, true))
1326+
repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, context.RepoRefByTypeOptions{IgnoreNotExistErr: true}))
13271327
m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
13281328
repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
13291329
}, ignSignIn, context.RepoAssignment, reqRepoCodeReader)
@@ -1337,7 +1337,7 @@ func registerRoutes(m *web.Router) {
13371337
m.Get(".rss", feedEnabled, repo.ReleasesFeedRSS)
13381338
m.Get(".atom", feedEnabled, repo.ReleasesFeedAtom)
13391339
}, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
1340-
repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, true))
1340+
repo.MustBeNotEmpty, context.RepoRefByType(context.RepoRefTag, context.RepoRefByTypeOptions{IgnoreNotExistErr: true}))
13411341
m.Get("/releases/attachments/{uuid}", repo.MustBeNotEmpty, repo.GetAttachment)
13421342
m.Get("/releases/download/{vTag}/{fileName}", repo.MustBeNotEmpty, repo.RedirectDownload)
13431343
m.Group("/releases", func() {
@@ -1535,7 +1535,7 @@ func registerRoutes(m *web.Router) {
15351535
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
15361536
m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
15371537
// "/*" route is deprecated, and kept for backward compatibility
1538-
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
1538+
m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.SingleDownloadOrLFS)
15391539
}, repo.MustBeNotEmpty)
15401540

15411541
m.Group("/raw", func() {
@@ -1544,7 +1544,7 @@ func registerRoutes(m *web.Router) {
15441544
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
15451545
m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
15461546
// "/*" route is deprecated, and kept for backward compatibility
1547-
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
1547+
m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.SingleDownload)
15481548
}, repo.MustBeNotEmpty)
15491549

15501550
m.Group("/render", func() {
@@ -1559,7 +1559,7 @@ func registerRoutes(m *web.Router) {
15591559
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
15601560
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
15611561
// "/*" route is deprecated, and kept for backward compatibility
1562-
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
1562+
m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.RefCommits)
15631563
}, repo.MustBeNotEmpty)
15641564

15651565
m.Group("/blame", func() {
@@ -1582,7 +1582,7 @@ func registerRoutes(m *web.Router) {
15821582
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
15831583
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
15841584
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
1585-
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home) // "/*" route is deprecated, and kept for backward compatibility
1585+
m.Get("/*", context.RepoRefByType(context.RepoRefUnknown), repo.Home) // "/*" route is deprecated, and kept for backward compatibility
15861586
}, repo.SetEditorconfigIfExists)
15871587

15881588
m.Get("/forks", context.RepoRef(), repo.Forks)

services/context/api.go

Lines changed: 2 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414
"code.gitea.io/gitea/models/unit"
1515
user_model "code.gitea.io/gitea/models/user"
1616
"code.gitea.io/gitea/modules/cache"
17-
"code.gitea.io/gitea/modules/git"
1817
"code.gitea.io/gitea/modules/gitrepo"
1918
"code.gitea.io/gitea/modules/httpcache"
2019
"code.gitea.io/gitea/modules/log"
@@ -306,24 +305,8 @@ func RepoRefForAPI(next http.Handler) http.Handler {
306305
return
307306
}
308307

309-
if ref := ctx.FormTrim("ref"); len(ref) > 0 {
310-
commit, err := ctx.Repo.GitRepo.GetCommit(ref)
311-
if err != nil {
312-
if git.IsErrNotExist(err) {
313-
ctx.NotFound()
314-
} else {
315-
ctx.Error(http.StatusInternalServerError, "GetCommit", err)
316-
}
317-
return
318-
}
319-
ctx.Repo.Commit = commit
320-
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
321-
ctx.Repo.TreePath = ctx.PathParam("*")
322-
next.ServeHTTP(w, req)
323-
return
324-
}
325-
326-
refName := getRefName(ctx.Base, ctx.Repo, RepoRefAny)
308+
// NOTICE: the "ref" here for internal usage only (e.g. woodpecker)
309+
refName, _ := getRefNameLegacy(ctx.Base, ctx.Repo, ctx.FormTrim("ref"))
327310
var err error
328311

329312
if ctx.Repo.GitRepo.IsBranchExist(refName) {

services/context/repo.go

Lines changed: 65 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -756,19 +756,11 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
756756
type RepoRefType int
757757

758758
const (
759-
// RepoRefLegacy unknown type, make educated guess and redirect.
760-
// for backward compatibility with previous URL scheme
761-
RepoRefLegacy RepoRefType = iota
762-
// RepoRefAny is for usage where educated guess is needed
763-
// but redirect can not be made
764-
RepoRefAny
765-
// RepoRefBranch branch
759+
// RepoRefUnknown is for legacy support, makes the code to "guess" the ref type
760+
RepoRefUnknown RepoRefType = iota
766761
RepoRefBranch
767-
// RepoRefTag tag
768762
RepoRefTag
769-
// RepoRefCommit commit
770763
RepoRefCommit
771-
// RepoRefBlob blob
772764
RepoRefBlob
773765
)
774766

@@ -781,22 +773,6 @@ func RepoRef() func(*Context) context.CancelFunc {
781773
return RepoRefByType(RepoRefBranch)
782774
}
783775

784-
// RefTypeIncludesBranches returns true if ref type can be a branch
785-
func (rt RepoRefType) RefTypeIncludesBranches() bool {
786-
if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch {
787-
return true
788-
}
789-
return false
790-
}
791-
792-
// RefTypeIncludesTags returns true if ref type can be a tag
793-
func (rt RepoRefType) RefTypeIncludesTags() bool {
794-
if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag {
795-
return true
796-
}
797-
return false
798-
}
799-
800776
func getRefNameFromPath(repo *Repository, path string, isExist func(string) bool) string {
801777
refName := ""
802778
parts := strings.Split(path, "/")
@@ -810,28 +786,50 @@ func getRefNameFromPath(repo *Repository, path string, isExist func(string) bool
810786
return ""
811787
}
812788

789+
func isStringLikelyCommitID(objFmt git.ObjectFormat, s string, minLength ...int) bool {
790+
minLen := util.OptionalArg(minLength, objFmt.FullLength())
791+
if len(s) < minLen || len(s) > objFmt.FullLength() {
792+
return false
793+
}
794+
for _, c := range s {
795+
isHex := (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
796+
if !isHex {
797+
return false
798+
}
799+
}
800+
return true
801+
}
802+
803+
func getRefNameLegacy(ctx *Base, repo *Repository, optionalExtraRef ...string) (string, RepoRefType) {
804+
extraRef := util.OptionalArg(optionalExtraRef)
805+
reqPath := ctx.PathParam("*")
806+
reqPath = path.Join(extraRef, reqPath)
807+
808+
if refName := getRefName(ctx, repo, RepoRefBranch); refName != "" {
809+
return refName, RepoRefBranch
810+
}
811+
if refName := getRefName(ctx, repo, RepoRefTag); refName != "" {
812+
return refName, RepoRefTag
813+
}
814+
815+
// For legacy support only full commit sha
816+
parts := strings.Split(reqPath, "/")
817+
if isStringLikelyCommitID(git.ObjectFormatFromName(repo.Repository.ObjectFormatName), parts[0]) {
818+
// FIXME: this logic is different from other types. Ideally, it should also try to GetCommit to check if it exists
819+
repo.TreePath = strings.Join(parts[1:], "/")
820+
return parts[0], RepoRefCommit
821+
}
822+
823+
if refName := getRefName(ctx, repo, RepoRefBlob); len(refName) > 0 {
824+
return refName, RepoRefBlob
825+
}
826+
repo.TreePath = reqPath
827+
return repo.Repository.DefaultBranch, RepoRefBranch
828+
}
829+
813830
func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string {
814831
path := ctx.PathParam("*")
815832
switch pathType {
816-
case RepoRefLegacy, RepoRefAny:
817-
if refName := getRefName(ctx, repo, RepoRefBranch); len(refName) > 0 {
818-
return refName
819-
}
820-
if refName := getRefName(ctx, repo, RepoRefTag); len(refName) > 0 {
821-
return refName
822-
}
823-
// For legacy and API support only full commit sha
824-
parts := strings.Split(path, "/")
825-
826-
if len(parts) > 0 && len(parts[0]) == git.ObjectFormatFromName(repo.Repository.ObjectFormatName).FullLength() {
827-
repo.TreePath = strings.Join(parts[1:], "/")
828-
return parts[0]
829-
}
830-
if refName := getRefName(ctx, repo, RepoRefBlob); len(refName) > 0 {
831-
return refName
832-
}
833-
repo.TreePath = path
834-
return repo.Repository.DefaultBranch
835833
case RepoRefBranch:
836834
ref := getRefNameFromPath(repo, path, repo.GitRepo.IsBranchExist)
837835
if len(ref) == 0 {
@@ -866,13 +864,13 @@ func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string {
866864
return getRefNameFromPath(repo, path, repo.GitRepo.IsTagExist)
867865
case RepoRefCommit:
868866
parts := strings.Split(path, "/")
869-
870-
if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= repo.GetObjectFormat().FullLength() {
867+
if isStringLikelyCommitID(repo.GetObjectFormat(), parts[0], 7) {
868+
// FIXME: this logic is different from other types. Ideally, it should also try to GetCommit to check if it exists
871869
repo.TreePath = strings.Join(parts[1:], "/")
872870
return parts[0]
873871
}
874872

875-
if len(parts) > 0 && parts[0] == headRefName {
873+
if parts[0] == headRefName {
876874
// HEAD ref points to last default branch commit
877875
commit, err := repo.GitRepo.GetBranchCommit(repo.Repository.DefaultBranch)
878876
if err != nil {
@@ -888,15 +886,21 @@ func getRefName(ctx *Base, repo *Repository, pathType RepoRefType) string {
888886
}
889887
return path
890888
default:
891-
log.Error("Unrecognized path type: %v", path)
889+
panic(fmt.Sprintf("Unrecognized path type: %v", pathType))
892890
}
893891
return ""
894892
}
895893

894+
type RepoRefByTypeOptions struct {
895+
IgnoreNotExistErr bool
896+
}
897+
896898
// RepoRefByType handles repository reference name for a specific type
897899
// of repository reference
898-
func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context) context.CancelFunc {
900+
func RepoRefByType(detectRefType RepoRefType, opts ...RepoRefByTypeOptions) func(*Context) context.CancelFunc {
901+
opt := util.OptionalArg(opts)
899902
return func(ctx *Context) (cancel context.CancelFunc) {
903+
refType := detectRefType
900904
// Empty repository does not have reference information.
901905
if ctx.Repo.Repository.IsEmpty {
902906
// assume the user is viewing the (non-existent) default branch
@@ -956,7 +960,12 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context
956960
}
957961
ctx.Repo.IsViewBranch = true
958962
} else {
959-
refName = getRefName(ctx.Base, ctx.Repo, refType)
963+
guessLegacyPath := refType == RepoRefUnknown
964+
if guessLegacyPath {
965+
refName, refType = getRefNameLegacy(ctx.Base, ctx.Repo)
966+
} else {
967+
refName = getRefName(ctx.Base, ctx.Repo, refType)
968+
}
960969
ctx.Repo.RefName = refName
961970
isRenamedBranch, has := ctx.Data["IsRenamedBranch"].(bool)
962971
if isRenamedBranch && has {
@@ -967,7 +976,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context
967976
return cancel
968977
}
969978

970-
if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
979+
if refType == RepoRefBranch && ctx.Repo.GitRepo.IsBranchExist(refName) {
971980
ctx.Repo.IsViewBranch = true
972981
ctx.Repo.BranchName = refName
973982

@@ -977,7 +986,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context
977986
return cancel
978987
}
979988
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
980-
} else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
989+
} else if refType == RepoRefTag && ctx.Repo.GitRepo.IsTagExist(refName) {
981990
ctx.Repo.IsViewTag = true
982991
ctx.Repo.TagName = refName
983992

@@ -991,7 +1000,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context
9911000
return cancel
9921001
}
9931002
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
994-
} else if len(refName) >= 7 && len(refName) <= ctx.Repo.GetObjectFormat().FullLength() {
1003+
} else if isStringLikelyCommitID(ctx.Repo.GetObjectFormat(), refName, 7) {
9951004
ctx.Repo.IsViewCommit = true
9961005
ctx.Repo.CommitID = refName
9971006

@@ -1006,14 +1015,14 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context
10061015
util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), util.PathEscapeSegments(refName), url.PathEscape(ctx.Repo.Commit.ID.String()), 1))))
10071016
}
10081017
} else {
1009-
if len(ignoreNotExistErr) > 0 && ignoreNotExistErr[0] {
1018+
if opt.IgnoreNotExistErr {
10101019
return cancel
10111020
}
10121021
ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
10131022
return cancel
10141023
}
10151024

1016-
if refType == RepoRefLegacy {
1025+
if guessLegacyPath {
10171026
// redirect from old URL scheme to new URL scheme
10181027
prefix := strings.TrimPrefix(setting.AppSubURL+strings.ToLower(strings.TrimSuffix(ctx.Req.URL.Path, ctx.PathParam("*"))), strings.ToLower(ctx.Repo.RepoLink))
10191028
redirect := path.Join(

templates/swagger/v1_json.tmpl

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/integration/links_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,18 +49,18 @@ func TestLinksNoLogin(t *testing.T) {
4949
func TestRedirectsNoLogin(t *testing.T) {
5050
defer tests.PrepareTestEnv(t)()
5151

52-
redirects := map[string]string{
53-
"/user2/repo1/commits/master": "/user2/repo1/commits/branch/master",
54-
"/user2/repo1/src/master": "/user2/repo1/src/branch/master",
55-
"/user2/repo1/src/master/file.txt": "/user2/repo1/src/branch/master/file.txt",
56-
"/user2/repo1/src/master/directory/file.txt": "/user2/repo1/src/branch/master/directory/file.txt",
57-
"/user/avatar/Ghost/-1": "/assets/img/avatar_default.png",
58-
"/api/v1/swagger": "/api/swagger",
52+
redirects := []struct{ from, to string }{
53+
{"/user2/repo1/commits/master", "/user2/repo1/commits/branch/master"},
54+
{"/user2/repo1/src/master", "/user2/repo1/src/branch/master"},
55+
{"/user2/repo1/src/master/file.txt", "/user2/repo1/src/branch/master/file.txt"},
56+
{"/user2/repo1/src/master/directory/file.txt", "/user2/repo1/src/branch/master/directory/file.txt"},
57+
{"/user/avatar/Ghost/-1", "/assets/img/avatar_default.png"},
58+
{"/api/v1/swagger", "/api/swagger"},
5959
}
60-
for link, redirectLink := range redirects {
61-
req := NewRequest(t, "GET", link)
60+
for _, c := range redirects {
61+
req := NewRequest(t, "GET", c.from)
6262
resp := MakeRequest(t, req, http.StatusSeeOther)
63-
assert.EqualValues(t, path.Join(setting.AppSubURL, redirectLink), test.RedirectURL(resp))
63+
assert.EqualValues(t, path.Join(setting.AppSubURL, c.to), test.RedirectURL(resp))
6464
}
6565
}
6666

0 commit comments

Comments
 (0)