Less naked returns (#25713)

just a step towards  #25655

and some related refactoring
This commit is contained in:
6543 2023-07-07 07:31:56 +02:00 committed by GitHub
parent b1eb1676aa
commit 8995046110
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 254 additions and 239 deletions

View file

@ -219,7 +219,7 @@ func GetRawFileOrLFS(ctx *context.APIContext) {
common.ServeContentByReadSeeker(ctx.Base, ctx.Repo.TreePath, lastModified, lfsDataRc)
}
func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, entry *git.TreeEntry, lastModified time.Time) {
func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, entry *git.TreeEntry, lastModified *time.Time) {
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
if err != nil {
if git.IsErrNotExist(err) {
@ -227,23 +227,23 @@ func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, entry *git.TreeEn
} else {
ctx.Error(http.StatusInternalServerError, "GetTreeEntryByPath", err)
}
return
return nil, nil, nil
}
if entry.IsDir() || entry.IsSubModule() {
ctx.NotFound("getBlobForEntry", nil)
return
return nil, nil, nil
}
info, _, err := git.Entries([]*git.TreeEntry{entry}).GetCommitsInfo(ctx, ctx.Repo.Commit, path.Dir("/" + ctx.Repo.TreePath)[1:])
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetCommitsInfo", err)
return
return nil, nil, nil
}
if len(info) == 1 {
// Not Modified
lastModified = info[0].Commit.Committer.When
lastModified = &info[0].Commit.Committer.When
}
blob = entry.Blob()

View file

@ -298,26 +298,26 @@ func ClearIssueLabels(ctx *context.APIContext) {
ctx.Status(http.StatusNoContent)
}
func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption) (issue *issues_model.Issue, labels []*issues_model.Label, err error) {
issue, err = issues_model.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption) (*issues_model.Issue, []*issues_model.Label, error) {
issue, err := issues_model.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
if err != nil {
if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err)
}
return
return nil, nil, err
}
labels, err = issues_model.GetLabelsByIDs(form.Labels)
labels, err := issues_model.GetLabelsByIDs(form.Labels)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetLabelsByIDs", err)
return
return nil, nil, err
}
if !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) {
ctx.Status(http.StatusForbidden)
return
return nil, nil, nil
}
return issue, labels, err

View file

@ -15,7 +15,7 @@ import (
)
// ServeBlob download a git.Blob
func ServeBlob(ctx *context.Base, filePath string, blob *git.Blob, lastModified time.Time) error {
func ServeBlob(ctx *context.Base, filePath string, blob *git.Blob, lastModified *time.Time) error {
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return nil
}
@ -38,6 +38,6 @@ func ServeContentByReader(ctx *context.Base, filePath string, size int64, reader
httplib.ServeContentByReader(ctx.Req, ctx.Resp, filePath, size, reader)
}
func ServeContentByReadSeeker(ctx *context.Base, filePath string, modTime time.Time, reader io.ReadSeeker) {
func ServeContentByReadSeeker(ctx *context.Base, filePath string, modTime *time.Time, reader io.ReadSeeker) {
httplib.ServeContentByReadSeeker(ctx.Req, ctx.Resp, filePath, modTime, reader)
}

View file

@ -497,23 +497,23 @@ func createUserInContext(ctx *context.Context, tpl base.TplName, form any, u *us
hasUser, err = user_model.GetUser(user)
if !hasUser || err != nil {
ctx.ServerError("UserLinkAccount", err)
return
return false
}
}
// TODO: probably we should respect 'remember' user's choice...
linkAccount(ctx, user, *gothUser, true)
return // user is already created here, all redirects are handled
return false // user is already created here, all redirects are handled
} else if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingLogin {
showLinkingLogin(ctx, *gothUser)
return // user will be created only after linking login
return false // user will be created only after linking login
}
}
// handle error without template
if len(tpl) == 0 {
ctx.ServerError("CreateUser", err)
return
return false
}
// handle error with template
@ -542,7 +542,7 @@ func createUserInContext(ctx *context.Context, tpl base.TplName, form any, u *us
default:
ctx.ServerError("CreateUser", err)
}
return
return false
}
log.Trace("Account created: %s", u.Name)
return true
@ -559,7 +559,7 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.
u.SetLastLogin()
if err := user_model.UpdateUserCols(ctx, u, "is_admin", "is_active", "last_login_unix"); err != nil {
ctx.ServerError("UpdateUser", err)
return
return false
}
}
@ -577,7 +577,7 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.
if setting.Service.RegisterManualConfirm {
ctx.Data["ManualActivationOnly"] = true
ctx.HTML(http.StatusOK, TplActivate)
return
return false
}
mailer.SendActivateAccountMail(ctx.Locale, u)
@ -592,7 +592,7 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.
log.Error("Set cache(MailResendLimit) fail: %v", err)
}
}
return
return false
}
return true

View file

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/upload"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers/common"
"code.gitea.io/gitea/services/attachment"
repo_service "code.gitea.io/gitea/services/repository"
@ -148,7 +149,7 @@ func ServeAttachment(ctx *context.Context, uuid string) {
}
defer fr.Close()
common.ServeContentByReadSeeker(ctx.Base, attach.Name, attach.CreatedUnix.AsTime(), fr)
common.ServeContentByReadSeeker(ctx.Base, attach.Name, util.ToPointer(attach.CreatedUnix.AsTime()), fr)
}
// GetAttachment serve attachments

View file

@ -20,7 +20,7 @@ import (
)
// ServeBlobOrLFS download a git.Blob redirecting to LFS if necessary
func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified time.Time) error {
func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified *time.Time) error {
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return nil
}
@ -82,7 +82,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob, lastModified time.Time
return common.ServeBlob(ctx.Base, ctx.Repo.TreePath, blob, lastModified)
}
func getBlobForEntry(ctx *context.Context) (blob *git.Blob, lastModified time.Time) {
func getBlobForEntry(ctx *context.Context) (blob *git.Blob, lastModified *time.Time) {
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
if err != nil {
if git.IsErrNotExist(err) {
@ -90,23 +90,23 @@ func getBlobForEntry(ctx *context.Context) (blob *git.Blob, lastModified time.Ti
} else {
ctx.ServerError("GetTreeEntryByPath", err)
}
return
return nil, nil
}
if entry.IsDir() || entry.IsSubModule() {
ctx.NotFound("getBlobForEntry", nil)
return
return nil, nil
}
info, _, err := git.Entries([]*git.TreeEntry{entry}).GetCommitsInfo(ctx, ctx.Repo.Commit, path.Dir("/" + ctx.Repo.TreePath)[1:])
if err != nil {
ctx.ServerError("GetCommitsInfo", err)
return
return nil, nil
}
if len(info) == 1 {
// Not Modified
lastModified = info[0].Commit.Committer.When
lastModified = &info[0].Commit.Committer.When
}
blob = entry.Blob()
@ -148,7 +148,7 @@ func DownloadByID(ctx *context.Context) {
}
return
}
if err = common.ServeBlob(ctx.Base, ctx.Repo.TreePath, blob, time.Time{}); err != nil {
if err = common.ServeBlob(ctx.Base, ctx.Repo.TreePath, blob, nil); err != nil {
ctx.ServerError("ServeBlob", err)
}
}
@ -164,7 +164,7 @@ func DownloadByIDOrLFS(ctx *context.Context) {
}
return
}
if err = ServeBlobOrLFS(ctx, blob, time.Time{}); err != nil {
if err = ServeBlobOrLFS(ctx, blob, nil); err != nil {
ctx.ServerError("ServeBlob", err)
}
}

View file

@ -56,13 +56,13 @@ func CorsHandler() func(next http.Handler) http.Handler {
}
// httpBase implementation git smart HTTP protocol
func httpBase(ctx *context.Context) (h *serviceHandler) {
func httpBase(ctx *context.Context) *serviceHandler {
username := ctx.Params(":username")
reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
if ctx.FormString("go-get") == "1" {
context.EarlyResponseForGoGetMeta(ctx)
return
return nil
}
var isPull, receivePack bool
@ -101,7 +101,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
owner := ctx.ContextUser
if !owner.IsOrganization() && !owner.IsActive {
ctx.PlainText(http.StatusForbidden, "Repository cannot be accessed. You cannot push or open issues/pull-requests.")
return
return nil
}
repoExist := true
@ -110,19 +110,19 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
if repo_model.IsErrRepoNotExist(err) {
if redirectRepoID, err := repo_model.LookupRedirect(owner.ID, reponame); err == nil {
context.RedirectToRepo(ctx.Base, redirectRepoID)
return
return nil
}
repoExist = false
} else {
ctx.ServerError("GetRepositoryByName", err)
return
return nil
}
}
// Don't allow pushing if the repo is archived
if repoExist && repo.IsArchived && !isPull {
ctx.PlainText(http.StatusForbidden, "This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.")
return
return nil
}
// Only public pull don't need auth.
@ -136,7 +136,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
if isPublicPull {
if err := repo.LoadOwner(ctx); err != nil {
ctx.ServerError("LoadOwner", err)
return
return nil
}
askAuth = askAuth || (repo.Owner.Visibility != structs.VisibleTypePublic)
@ -149,12 +149,12 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
// TODO: support digit auth - which would be Authorization header with digit
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
ctx.Error(http.StatusUnauthorized)
return
return nil
}
context.CheckRepoScopedToken(ctx, repo, auth_model.GetScopeLevelFromAccessMode(accessMode))
if ctx.Written() {
return
return nil
}
if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && ctx.Data["IsActionsToken"] != true {
@ -162,16 +162,16 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
if err == nil {
// TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented
ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page")
return
return nil
} else if !auth_model.IsErrTwoFactorNotEnrolled(err) {
ctx.ServerError("IsErrTwoFactorNotEnrolled", err)
return
return nil
}
}
if !ctx.Doer.IsActive || ctx.Doer.ProhibitLogin {
ctx.PlainText(http.StatusForbidden, "Your account is disabled.")
return
return nil
}
environ = []string{
@ -193,23 +193,23 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
task, err := actions_model.GetTaskByID(ctx, taskID)
if err != nil {
ctx.ServerError("GetTaskByID", err)
return
return nil
}
if task.RepoID != repo.ID {
ctx.PlainText(http.StatusForbidden, "User permission denied")
return
return nil
}
if task.IsForkPullRequest {
if accessMode > perm.AccessModeRead {
ctx.PlainText(http.StatusForbidden, "User permission denied")
return
return nil
}
environ = append(environ, fmt.Sprintf("%s=%d", repo_module.EnvActionPerm, perm.AccessModeRead))
} else {
if accessMode > perm.AccessModeWrite {
ctx.PlainText(http.StatusForbidden, "User permission denied")
return
return nil
}
environ = append(environ, fmt.Sprintf("%s=%d", repo_module.EnvActionPerm, perm.AccessModeWrite))
}
@ -217,18 +217,18 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
p, err := access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
return nil
}
if !p.CanAccess(accessMode, unitType) {
ctx.PlainText(http.StatusNotFound, "Repository not found")
return
return nil
}
}
if !isPull && repo.IsMirror {
ctx.PlainText(http.StatusForbidden, "mirror repository is read-only")
return
return nil
}
}
@ -246,34 +246,34 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
if !repoExist {
if !receivePack {
ctx.PlainText(http.StatusNotFound, "Repository not found")
return
return nil
}
if isWiki { // you cannot send wiki operation before create the repository
ctx.PlainText(http.StatusNotFound, "Repository not found")
return
return nil
}
if owner.IsOrganization() && !setting.Repository.EnablePushCreateOrg {
ctx.PlainText(http.StatusForbidden, "Push to create is not enabled for organizations.")
return
return nil
}
if !owner.IsOrganization() && !setting.Repository.EnablePushCreateUser {
ctx.PlainText(http.StatusForbidden, "Push to create is not enabled for users.")
return
return nil
}
// Return dummy payload if GET receive-pack
if ctx.Req.Method == http.MethodGet {
dummyInfoRefs(ctx)
return
return nil
}
repo, err = repo_service.PushCreateRepo(ctx, ctx.Doer, owner, reponame)
if err != nil {
log.Error("pushCreateRepo: %v", err)
ctx.Status(http.StatusNotFound)
return
return nil
}
}
@ -282,11 +282,11 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
if _, err := repo.GetUnit(ctx, unit.TypeWiki); err != nil {
if repo_model.IsErrUnitTypeNotExist(err) {
ctx.PlainText(http.StatusForbidden, "repository wiki is disabled")
return
return nil
}
log.Error("Failed to get the wiki unit in %-v Error: %v", repo, err)
ctx.ServerError("GetUnit(UnitTypeWiki) for "+repo.FullName(), err)
return
return nil
}
}

View file

@ -1922,9 +1922,12 @@ func ViewIssue(ctx *context.Context) {
ctx.HTML(http.StatusOK, tplIssueView)
}
// checkBlockedByIssues return canRead and notPermitted
func checkBlockedByIssues(ctx *context.Context, blockers []*issues_model.DependencyInfo) (canRead, notPermitted []*issues_model.DependencyInfo) {
var lastRepoID int64
var lastPerm access_model.Permission
var (
lastRepoID int64
lastPerm access_model.Permission
)
for i, blocker := range blockers {
// Get the permissions for this repository
perm := lastPerm
@ -1936,7 +1939,7 @@ func checkBlockedByIssues(ctx *context.Context, blockers []*issues_model.Depende
perm, err = access_model.GetUserRepoPermission(ctx, &blocker.Repository, ctx.Doer)
if err != nil {
ctx.ServerError("GetUserRepoPermission", err)
return
return nil, nil
}
}
lastRepoID = blocker.Repository.ID

View file

@ -12,7 +12,6 @@ import (
"net/url"
"path/filepath"
"strings"
"time"
git_model "code.gitea.io/gitea/models/git"
repo_model "code.gitea.io/gitea/models/repo"
@ -671,7 +670,7 @@ func WikiRaw(ctx *context.Context) {
}
if entry != nil {
if err = common.ServeBlob(ctx.Base, ctx.Repo.TreePath, entry.Blob(), time.Time{}); err != nil {
if err = common.ServeBlob(ctx.Base, ctx.Repo.TreePath, entry.Blob(), nil); err != nil {
ctx.ServerError("ServeBlob", err)
}
return

View file

@ -1256,20 +1256,20 @@ func registerRoutes(m *web.Route) {
m.Group("/blob_excerpt", func() {
m.Get("/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
}, func(ctx *context.Context) (cancel gocontext.CancelFunc) {
}, func(ctx *context.Context) gocontext.CancelFunc {
if ctx.FormBool("wiki") {
ctx.Data["PageIsWiki"] = true
repo.MustEnableWiki(ctx)
return
return nil
}
reqRepoCodeReader(ctx)
if ctx.Written() {
return
return nil
}
cancel = context.RepoRef()(ctx)
cancel := context.RepoRef()(ctx)
if ctx.Written() {
return
return cancel
}
repo.MustBeNotEmpty(ctx)