Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main'
Browse files Browse the repository at this point in the history
* upstream/main:
  Fix install page context, make the install page tests really test (go-gitea#24858)
  Add validations.required check to dropdown field (go-gitea#24849)
  Use Go 1.20 for next release (go-gitea#24859)
  Add gitea manager reload-templates command (go-gitea#24843)
  Remove `In your repositories` link in milestones dashboard (go-gitea#24853)
  Fix 500 error when select `No assignee` filter in issue list page (go-gitea#24854)
  Add IsErrRepoFilesAlreadyExist check when fork repo (go-gitea#24678)
  Fix missing yes/no in delete time log modal (go-gitea#24851)
  Fix document and improve comment (go-gitea#24844)

# Conflicts:
#	web_src/css/base.css
  • Loading branch information
zjjhot committed May 23, 2023
2 parents 5884e1e + abcf5a7 commit f0522e1
Show file tree
Hide file tree
Showing 24 changed files with 135 additions and 57 deletions.
20 changes: 20 additions & 0 deletions cmd/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var (
Subcommands: []cli.Command{
subcmdShutdown,
subcmdRestart,
subcmdReloadTemplates,
subcmdFlushQueues,
subcmdLogging,
subCmdProcesses,
Expand All @@ -46,6 +47,16 @@ var (
},
Action: runRestart,
}
subcmdReloadTemplates = cli.Command{
Name: "reload-templates",
Usage: "Reload template files in the running process",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "debug",
},
},
Action: runReloadTemplates,
}
subcmdFlushQueues = cli.Command{
Name: "flush-queues",
Usage: "Flush queues in the running process",
Expand Down Expand Up @@ -115,6 +126,15 @@ func runRestart(c *cli.Context) error {
return handleCliResponseExtra(extra)
}

func runReloadTemplates(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()

setup(ctx, c.Bool("debug"))
extra := private.ReloadTemplates(ctx)
return handleCliResponseExtra(extra)
}

func runFlushQueues(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
Expand Down
4 changes: 1 addition & 3 deletions cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,8 @@ func runWeb(ctx *cli.Context) error {
return err
}
}
installCtx, cancel := context.WithCancel(graceful.GetManager().HammerContext())
c := install.Routes(installCtx)
c := install.Routes()
err := listen(c, false)
cancel()
if err != nil {
log.Critical("Unable to open listener for installer. Is Gitea already running?")
graceful.GetManager().DoGracefulShutdown()
Expand Down
4 changes: 2 additions & 2 deletions docs/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ params:
description: Git with a cup of tea
author: The Gitea Authors
website: https://docs.gitea.io
version: 1.19.0
minGoVersion: 1.19
version: 1.19.0 # FIXME: this version was used as "latest stable release", but it always gets outdated and doesn't make sense
minGoVersion: 1.20
goVersion: 1.20
minNodeVersion: 16
search: nav
Expand Down
2 changes: 1 addition & 1 deletion docs/content/doc/help/faq.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ A "login prohibited" user is a user that is not allowed to log in to Gitea anymo

## Setting up logging

- [Official Docs]({{< relref "doc/administration/logging-documentation.en-us.md" >}})
- [Official Docs]({{< relref "doc/administration/logging-config.en-us.md" >}})

## What is Swagger?

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module code.gitea.io/gitea

go 1.19
go 1.20

require (
code.gitea.io/actions-proto-go v0.2.1
Expand Down
2 changes: 1 addition & 1 deletion models/issues/issue_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func getIssueStatsChunk(opts *IssuesOptions, issueIDs []int64) (*IssueStats, err
if opts.AssigneeID > 0 {
applyAssigneeCondition(sess, opts.AssigneeID)
} else if opts.AssigneeID == db.NoConditionID {
sess.Where("id NOT IN (SELECT issue_id FROM issue_assignees)")
sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_assignees)")
}

if opts.PosterID > 0 {
Expand Down
12 changes: 6 additions & 6 deletions modules/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@ func (ctx *Context) TrHTMLEscapeArgs(msg string, args ...string) string {
return ctx.Locale.Tr(msg, trArgs...)
}

type contextKeyType struct{}
type webContextKeyType struct{}

var contextKey interface{} = contextKeyType{}
var WebContextKey = webContextKeyType{}

func GetContext(req *http.Request) *Context {
ctx, _ := req.Context().Value(contextKey).(*Context)
func GetWebContext(req *http.Request) *Context {
ctx, _ := req.Context().Value(WebContextKey).(*Context)
return ctx
}

Expand All @@ -86,7 +86,7 @@ type ValidateContext struct {
func GetValidateContext(req *http.Request) (ctx *ValidateContext) {
if ctxAPI, ok := req.Context().Value(apiContextKey).(*APIContext); ok {
ctx = &ValidateContext{Base: ctxAPI.Base}
} else if ctxWeb, ok := req.Context().Value(contextKey).(*Context); ok {
} else if ctxWeb, ok := req.Context().Value(WebContextKey).(*Context); ok {
ctx = &ValidateContext{Base: ctxWeb.Base}
} else {
panic("invalid context, expect either APIContext or Context")
Expand Down Expand Up @@ -135,7 +135,7 @@ func Contexter() func(next http.Handler) http.Handler {
ctx.PageData = map[string]any{}
ctx.Data["PageData"] = ctx.PageData

ctx.Base.AppendContextValue(contextKey, ctx)
ctx.Base.AppendContextValue(WebContextKey, ctx)
ctx.Base.AppendContextValueFunc(git.RepositoryContextKey, func() any { return ctx.Repo.GitRepo })

ctx.Csrf = PrepareCSRFProtector(csrfOpts, ctx)
Expand Down
2 changes: 1 addition & 1 deletion modules/context/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ func PackageContexter() func(next http.Handler) http.Handler {
}
defer baseCleanUp()

ctx.Base.AppendContextValue(contextKey, ctx)
ctx.Base.AppendContextValue(WebContextKey, ctx)
next.ServeHTTP(ctx.Resp, ctx.Req)
})
}
Expand Down
7 changes: 7 additions & 0 deletions modules/private/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ func Restart(ctx context.Context) ResponseExtra {
return requestJSONClientMsg(req, "Restarting")
}

// ReloadTemplates calls the internal reload-templates function
func ReloadTemplates(ctx context.Context) ResponseExtra {
reqURL := setting.LocalURL + "api/internal/manager/reload-templates"
req := newInternalRequest(ctx, reqURL, "POST")
return requestJSONClientMsg(req, "Reloaded")
}

// FlushOptions represents the options for the flush call
type FlushOptions struct {
Timeout time.Duration
Expand Down
12 changes: 9 additions & 3 deletions modules/templates/htmlrenderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ func HTMLRenderer() *HTMLRender {
return htmlRender
}

func ReloadHTMLTemplates() error {
if err := htmlRender.CompileTemplates(); err != nil {
log.Error("Template error: %v\n%s", err, log.Stack(2))
return err
}
return nil
}

func initHTMLRenderer() {
rendererType := "static"
if !setting.IsProd {
Expand All @@ -115,9 +123,7 @@ func initHTMLRenderer() {

if !setting.IsProd {
go AssetFS().WatchLocalChanges(graceful.GetManager().ShutdownContext(), func() {
if err := htmlRender.CompileTemplates(); err != nil {
log.Error("Template error: %v\n%s", err, log.Stack(2))
}
_ = ReloadHTMLTemplates()
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion modules/web/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type ResponseStatusProvider interface {
// TODO: decouple this from the context package, let the context package register these providers
var argTypeProvider = map[reflect.Type]func(req *http.Request) ResponseStatusProvider{
reflect.TypeOf(&context.APIContext{}): func(req *http.Request) ResponseStatusProvider { return context.GetAPIContext(req) },
reflect.TypeOf(&context.Context{}): func(req *http.Request) ResponseStatusProvider { return context.GetContext(req) },
reflect.TypeOf(&context.Context{}): func(req *http.Request) ResponseStatusProvider { return context.GetWebContext(req) },
reflect.TypeOf(&context.PrivateContext{}): func(req *http.Request) ResponseStatusProvider { return context.GetPrivateContext(req) },
}

Expand Down
4 changes: 3 additions & 1 deletion routers/api/v1/repo/fork.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package repo

import (
"errors"
"fmt"
"net/http"

Expand All @@ -15,6 +16,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/api/v1/utils"
"code.gitea.io/gitea/services/convert"
Expand Down Expand Up @@ -141,7 +143,7 @@ func CreateFork(ctx *context.APIContext) {
Description: repo.Description,
})
if err != nil {
if repo_service.IsErrForkAlreadyExist(err) || repo_model.IsErrRepoAlreadyExist(err) || repo_model.IsErrReachLimitOfRepo(err) {
if errors.Is(err, util.ErrAlreadyExist) || repo_model.IsErrReachLimitOfRepo(err) {
ctx.Error(http.StatusConflict, "ForkRepository", err)
} else {
ctx.Error(http.StatusInternalServerError, "ForkRepository", err)
Expand Down
3 changes: 2 additions & 1 deletion routers/install/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,15 @@ func Contexter() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
base, baseCleanUp := context.NewBaseContext(resp, req)
ctx := context.Context{
ctx := &context.Context{
Base: base,
Flash: &middleware.Flash{},
Render: rnd,
Session: session.GetSession(req),
}
defer baseCleanUp()

ctx.AppendContextValue(context.WebContextKey, ctx)
ctx.Data.MergeFrom(middleware.CommonTemplateContextData())
ctx.Data.MergeFrom(middleware.ContextData{
"locale": ctx.Locale,
Expand Down
3 changes: 1 addition & 2 deletions routers/install/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
package install

import (
goctx "context"
"fmt"
"html"
"net/http"
Expand All @@ -18,7 +17,7 @@ import (
)

// Routes registers the installation routes
func Routes(ctx goctx.Context) *web.Route {
func Routes() *web.Route {
base := web.NewRoute()
base.Use(common.ProtocolMiddlewares()...)
base.RouteMethods("/assets/*", "GET, HEAD", public.AssetsHandlerFunc("/assets/"))
Expand Down
41 changes: 29 additions & 12 deletions routers/install/routes_test.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
// Copyright 2021 The Gitea Authors. All rights reserved.
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package install

import (
"context"
"net/http/httptest"
"path/filepath"
"testing"

"code.gitea.io/gitea/models/unittest"

"github.com/stretchr/testify/assert"
)

func TestRoutes(t *testing.T) {
// TODO: this test seems not really testing the handlers
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
base := Routes(ctx)
assert.NotNil(t, base)
r := base.R.Routes()[1]
routes := r.SubRoutes.Routes()[0]
assert.EqualValues(t, "/", routes.Pattern)
assert.Nil(t, routes.SubRoutes)
assert.Len(t, routes.Handlers, 2)
r := Routes()
assert.NotNil(t, r)

w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
r.ServeHTTP(w, req)
assert.EqualValues(t, 200, w.Code)
assert.Contains(t, w.Body.String(), `class="page-content install"`)

w = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/no-such", nil)
r.ServeHTTP(w, req)
assert.EqualValues(t, 404, w.Code)

w = httptest.NewRecorder()
req = httptest.NewRequest("GET", "/assets/img/gitea.svg", nil)
r.ServeHTTP(w, req)
assert.EqualValues(t, 200, w.Code)
}

func TestMain(m *testing.M) {
unittest.MainTest(m, &unittest.TestOptions{
GiteaRootPath: filepath.Join("..", ".."),
})
}
1 change: 1 addition & 0 deletions routers/private/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func Routes() *web.Route {
r.Get("/serv/command/{keyid}/{owner}/{repo}", ServCommand)
r.Post("/manager/shutdown", Shutdown)
r.Post("/manager/restart", Restart)
r.Post("/manager/reload-templates", ReloadTemplates)
r.Post("/manager/flush-queues", bind(private.FlushOptions{}), FlushQueues)
r.Post("/manager/pause-logging", PauseLogging)
r.Post("/manager/resume-logging", ResumeLogging)
Expand Down
13 changes: 13 additions & 0 deletions routers/private/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,22 @@ import (
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/queue"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/web"
)

// ReloadTemplates reloads all the templates
func ReloadTemplates(ctx *context.PrivateContext) {
err := templates.ReloadHTMLTemplates()
if err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{
UserMsg: fmt.Sprintf("Template error: %v", err),
})
return
}
ctx.PlainText(http.StatusOK, "success")
}

// FlushQueues flushes all the Queues
func FlushQueues(ctx *context.PrivateContext) {
opts := web.GetForm(ctx).(*private.FlushOptions)
Expand Down
11 changes: 11 additions & 0 deletions routers/web/repo/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,17 @@ func ForkPost(ctx *context.Context) {
ctx.RenderWithErr(msg, tplFork, &form)
case repo_model.IsErrRepoAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form)
case repo_model.IsErrRepoFilesAlreadyExist(err):
switch {
case ctx.IsUserSiteAdmin() || (setting.Repository.AllowAdoptionOfUnadoptedRepositories && setting.Repository.AllowDeleteOfUnadoptedRepositories):
ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist.adopt_or_delete"), tplFork, form)
case setting.Repository.AllowAdoptionOfUnadoptedRepositories:
ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist.adopt"), tplFork, form)
case setting.Repository.AllowDeleteOfUnadoptedRepositories:
ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist.delete"), tplFork, form)
default:
ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist"), tplFork, form)
}
case db.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(db.ErrNameReserved).Name), tplFork, &form)
case db.IsErrNamePatternNotAllowed(err):
Expand Down
2 changes: 1 addition & 1 deletion routers/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -1405,7 +1405,7 @@ func registerRoutes(m *web.Route) {
}

m.NotFound(func(w http.ResponseWriter, req *http.Request) {
ctx := context.GetContext(req)
ctx := context.GetWebContext(req)
ctx.NotFound("", nil)
})
}
2 changes: 1 addition & 1 deletion services/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore
middleware.SetLocaleCookie(resp, user.Language, 0)

// Clear whatever CSRF has right now, force to generate a new one
if ctx := gitea_context.GetContext(req); ctx != nil {
if ctx := gitea_context.GetWebContext(req); ctx != nil {
ctx.Csrf.DeleteCookie(ctx)
}
}
2 changes: 2 additions & 0 deletions templates/repo/issue/fields/dropdown.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
<div class="ui fluid selection dropdown {{if .item.Attributes.multiple}}multiple clearable{{end}}">
<input type="hidden" name="form-field-{{.item.ID}}" value="0">
{{svg "octicon-triangle-down" 14 "dropdown icon"}}
{{if not .item.Validations.required}}
{{svg "octicon-x" 14 "remove icon"}}
{{end}}
<div class="default text"></div>
<div class="menu">
{{range $i, $opt := .item.Attributes.options}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
{{.ctxData.CsrfTokenHtml}}
</form>
<div class="header">{{.ctxData.locale.Tr "repo.issues.del_time"}}</div>
{{template "base/modal_actions_confirm" .}}
{{template "base/modal_actions_confirm" (dict "locale" .ctxData.locale)}}
</div>
<button class="ui icon button compact mini issue-delete-time" data-id="{{.comment.Time.ID}}" data-tooltip-content="{{.ctxData.locale.Tr "repo.issues.del_time"}}">
{{svg "octicon-trash"}}
Expand Down
4 changes: 2 additions & 2 deletions templates/user/dashboard/milestones.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
<div class="ui stackable grid">
<div class="four wide column">
<div class="ui secondary vertical filter menu gt-bg-transparent">
<a class="item" href="{{.Link}}?type=your_repositories&sort={{$.SortType}}&state={{.State}}&q={{$.Keyword}}">
<div class="item">
{{.locale.Tr "home.issues.in_your_repos"}}
<strong class="ui right">{{.Total}}</strong>
</a>
</div>
<div class="ui divider"></div>
{{range .Repos}}
{{with $Repo := .}}
Expand Down
Loading

0 comments on commit f0522e1

Please sign in to comment.