From bbd30787d3d33fe66896c7e758e6922be459e252 Mon Sep 17 00:00:00 2001 From: Jelle Hulter Date: Thu, 20 Jan 2022 10:59:15 +0100 Subject: [PATCH 1/7] Updated Chroma to v0.10.0 (#18270) --- go.mod | 2 +- go.sum | 4 +- modules/highlight/highlight_test.go | 54 +++++++++++++------------- modules/markup/orgmode/orgmode_test.go | 8 ++-- services/gitdiff/gitdiff_test.go | 3 +- 5 files changed, 35 insertions(+), 36 deletions(-) diff --git a/go.mod b/go.mod index ce3be970bdfd..abb6a93fb7e3 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( github.com/NYTimes/gziphandler v1.1.1 github.com/ProtonMail/go-crypto v0.0.0-20210705153151-cc34b1f6908b // indirect github.com/PuerkitoBio/goquery v1.7.0 - github.com/alecthomas/chroma v0.9.4 + github.com/alecthomas/chroma v0.10.0 github.com/andybalholm/brotli v1.0.3 // indirect github.com/andybalholm/cascadia v1.2.0 // indirect github.com/blevesearch/bleve/v2 v2.3.0 diff --git a/go.sum b/go.sum index 22fdb0b7ac66..bccfe158eef1 100644 --- a/go.sum +++ b/go.sum @@ -94,8 +94,8 @@ github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4Rq github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= github.com/alecthomas/chroma v0.7.2-0.20200305040604-4f3623dce67a/go.mod h1:fv5SzZPFJbwp2NXJWpFIX7DZS4HgV1K4ew4Pc2OZD9s= github.com/alecthomas/chroma v0.8.2/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= -github.com/alecthomas/chroma v0.9.4 h1:YL7sOAE3p8HS96T9km7RgvmsZIctqbK1qJ0b7hzed44= -github.com/alecthomas/chroma v0.9.4/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= +github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= +github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s= github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= github.com/alecthomas/kong v0.2.1-0.20190708041108-0548c6b1afae/go.mod h1:+inYUSluD+p4L8KdviBSgzcqEjUQOfC5fQDRFuc36lI= github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= diff --git a/modules/highlight/highlight_test.go b/modules/highlight/highlight_test.go index 3f47b6a48f65..2f305bb589c9 100644 --- a/modules/highlight/highlight_test.go +++ b/modules/highlight/highlight_test.go @@ -40,20 +40,19 @@ steps: - go test -v -race -coverprofile=coverage.txt -covermode=atomic `, want: []string{ - `kind: pipeline`, - `name: default`, - ` -`, - `steps:`, - `- name: test`, - ` image: golang:1.13`, - ` environment:`, - ` GOPROXY: https://goproxy.cn`, - ` commands:`, - ` - go get -u`, - ` - go build -v`, - ` - go test -v -race -coverprofile=coverage.txt -covermode=atomic -`, + `kind: pipeline`, + `name: default`, + ``, + `steps:`, + `- name: test`, + ` image: golang:1.13`, + ` environment:`, + ` GOPROXY: https://goproxy.cn`, + ` commands:`, + ` - go get -u`, + ` - go build -v`, + ` - go test -v -race -coverprofile=coverage.txt -covermode=atomic +`, ` `, }, @@ -76,20 +75,19 @@ steps: - go test -v -race -coverprofile=coverage.txt -covermode=atomic `, want: []string{ - `kind: pipeline`, - `name: default `, - ` -`, - `steps:`, - `- name: test`, - ` image: golang:1.13`, - ` environment:`, - ` GOPROXY: https://goproxy.cn`, - ` commands:`, - ` - go get -u`, - ` - go build -v`, - ` - go test -v -race -coverprofile=coverage.txt -covermode=atomic`, - ` `, + `kind: pipeline`, + `name: default `, + ``, + `steps:`, + `- name: test`, + ` image: golang:1.13`, + ` environment:`, + ` GOPROXY: https://goproxy.cn`, + ` commands:`, + ` - go get -u`, + ` - go build -v`, + ` - go test -v -race -coverprofile=coverage.txt -covermode=atomic`, + ` `, }, }, } diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index 81d0d66a76c5..38c010ef68d9 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -77,9 +77,9 @@ func HelloWorld() { } #+end_src `, `
-
// HelloWorld prints "Hello World"
-func HelloWorld() {
-	fmt.Println("Hello World")
-}
+
// HelloWorld prints "Hello World"
+func HelloWorld() {
+	fmt.Println("Hello World")
+}
`) } diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index 2f8b8491cd74..57cbb74b2208 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -716,7 +716,8 @@ func TestDiffToHTML_14231(t *testing.T) { diffRecord := diffMatchPatch.DiffMain(highlight.Code("main.v", "", " run()\n"), highlight.Code("main.v", "", " run(db)\n"), true) diffRecord = diffMatchPatch.DiffCleanupEfficiency(diffRecord) - expected := ` run(db)` + expected := ` run(db) +` output := diffToHTML("main.v", diffRecord, DiffLineAdd) assertEqual(t, expected, output.Content) From 5bf8d5445e3e3ec6b2be156654dcb233d78a570e Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 20 Jan 2022 19:41:25 +0800 Subject: [PATCH 2/7] Refactor Router Logger (#17308) Make router logger more friendly, show the related function name/file/line. [BREAKING] This PR substantially changes the logging format of the router logger. If you use this logging for monitoring e.g. fail2ban you will need to update this to match the new format. --- cmd/web.go | 2 +- custom/conf/app.example.ini | 17 +- .../doc/advanced/config-cheat-sheet.en-us.md | 13 +- .../advanced/logging-documentation.en-us.md | 19 +- modules/log/colors_router.go | 11 +- modules/log/log.go | 4 + modules/public/public.go | 89 +++++---- modules/setting/log.go | 7 +- modules/setting/setting.go | 10 +- modules/web/route.go | 138 -------------- modules/web/routing/context.go | 51 ++++++ modules/web/routing/funcinfo.go | 171 ++++++++++++++++++ modules/web/routing/funcinfo_test.go | 81 +++++++++ modules/web/routing/logger.go | 106 +++++++++++ modules/web/routing/logger_manager.go | 122 +++++++++++++ modules/web/routing/requestrecord.go | 29 +++ modules/web/wrap.go | 117 ++++++++++++ modules/web/wrap_convert.go | 101 +++++++++++ routers/common/logger.go | 33 ---- routers/common/middleware.go | 13 +- routers/install/routes.go | 23 ++- routers/web/base.go | 9 +- routers/web/web.go | 9 +- 23 files changed, 910 insertions(+), 265 deletions(-) create mode 100644 modules/web/routing/context.go create mode 100644 modules/web/routing/funcinfo.go create mode 100644 modules/web/routing/funcinfo_test.go create mode 100644 modules/web/routing/logger.go create mode 100644 modules/web/routing/logger_manager.go create mode 100644 modules/web/routing/requestrecord.go create mode 100644 modules/web/wrap.go create mode 100644 modules/web/wrap_convert.go delete mode 100644 routers/common/logger.go diff --git a/cmd/web.go b/cmd/web.go index 137c56d96211..ec92ef242abe 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -88,7 +88,7 @@ func runWeb(ctx *cli.Context) error { } defer func() { if panicked := recover(); panicked != nil { - log.Fatal("PANIC: %v\n%s", panicked, string(log.Stack(2))) + log.Fatal("PANIC: %v\n%s", panicked, log.Stack(2)) } }() diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 586c924c4ab8..3343af95a975 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -455,26 +455,35 @@ APP_ID = ; e.g. http://localhost:3000/ ;; Use comma to separate multiple modes, e.g. "console, file" MODE = console ;; -;; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Trace" +;; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical" or "None", default is "Info" LEVEL = Info ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Router Logger ;; ;; Switch off the router log -;DISABLE_ROUTER_LOG= ; false +;DISABLE_ROUTER_LOG=false ;; ;; Set the log "modes" for the router log (if file is set the log file will default to router.log) ROUTER = console ;; -;; The level at which the router logs -;ROUTER_LOG_LEVEL = Info +;; The router will log different things at different levels. ;; +;; * started messages will be logged at TRACE level +;; * polling/completed routers will be logged at INFO +;; * slow routers will be logged at WARN +;; * failed routers will be logged at WARN +;; +;; The routing level will default to that of the system but individual router level can be set in +;; [log..router] LEVEL +;; + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Access Logger (Creates log in NCSA common log format) ;; ;ENABLE_ACCESS_LOG = false +;; ;; Set the log "modes" for the access log (if file is set the log file will default to access.log) ;ACCESS = file ;; diff --git a/docs/content/doc/advanced/config-cheat-sheet.en-us.md b/docs/content/doc/advanced/config-cheat-sheet.en-us.md index 6cbc9b91f985..d8a3b897cc01 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.en-us.md +++ b/docs/content/doc/advanced/config-cheat-sheet.en-us.md @@ -291,7 +291,6 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `MINIMUM_KEY_SIZE_CHECK`: **true**: Indicate whether to check minimum key size with corresponding type. - `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures. -- `DISABLE_ROUTER_LOG`: **false**: Mute printing of the router log. - `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. When chaining, the server certificate must come first, then intermediate CA certificates (if any). From 1.11 paths are relative to `CUSTOM_PATH`. - `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. From 1.11 paths are relative to `CUSTOM_PATH`. - `STATIC_ROOT_PATH`: **./**: Upper level of template and static files path. @@ -752,11 +751,16 @@ Default templates for project boards: - `MODE`: **console**: Logging mode. For multiple modes, use a comma to separate values. You can configure each mode in per mode log subsections `\[log.modename\]`. By default the file mode will log to `$ROOT_PATH/gitea.log`. - `LEVEL`: **Info**: General log level. \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\] - `STACKTRACE_LEVEL`: **None**: Default log level at which to log create stack traces. \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\] -- `ROUTER_LOG_LEVEL`: **Info**: The log level that the router should log at. (If you are setting the access log, its recommended to place this at Debug.) +- `ENABLE_SSH_LOG`: **false**: save ssh log to log file +- `ENABLE_XORM_LOG`: **true**: Set whether to perform XORM logging. Please note SQL statement logging can be disabled by setting `LOG_SQL` to false in the `[database]` section. + +### Router Log (`log`) +- `DISABLE_ROUTER_LOG`: **false**: Mute printing of the router log. - `ROUTER`: **console**: The mode or name of the log the router should log to. (If you set this to `,` it will log to default Gitea logger.) -NB: You must have `DISABLE_ROUTER_LOG` set to `false` for this option to take effect. Configure each mode in per mode log subsections `\[log.modename.router\]`. + NB: You must have `DISABLE_ROUTER_LOG` set to `false` for this option to take effect. Configure each mode in per mode log subsections `\[log.modename.router\]`. + +### Access Log (`log`) - `ENABLE_ACCESS_LOG`: **false**: Creates an access.log in NCSA common log format, or as per the following template -- `ENABLE_SSH_LOG`: **false**: save ssh log to log file - `ACCESS`: **file**: Logging mode for the access logger, use a comma to separate values. Configure each mode in per mode log subsections `\[log.modename.access\]`. By default the file mode will log to `$ROOT_PATH/access.log`. (If you set this to `,` it will log to the default Gitea logger.) - `ACCESS_LOG_TEMPLATE`: **`{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`**: Sets the template used to create the access log. - The following variables are available: @@ -765,7 +769,6 @@ NB: You must have `DISABLE_ROUTER_LOG` set to `false` for this option to take ef - `Start`: the start time of the request. - `ResponseWriter`: the responseWriter from the request. - You must be very careful to ensure that this template does not throw errors or panics as this template runs outside of the panic/recovery script. -- `ENABLE_XORM_LOG`: **true**: Set whether to perform XORM logging. Please note SQL statement logging can be disabled by setting `LOG_SQL` to false in the `[database]` section. ### Log subsections (`log.name`, `log.name.*`) diff --git a/docs/content/doc/advanced/logging-documentation.en-us.md b/docs/content/doc/advanced/logging-documentation.en-us.md index 534634c99136..dee1dbb6d664 100644 --- a/docs/content/doc/advanced/logging-documentation.en-us.md +++ b/docs/content/doc/advanced/logging-documentation.en-us.md @@ -68,16 +68,23 @@ multiple subloggers that will log to files. ### The "Router" logger -You can disable Router log by setting `DISABLE_ROUTER_LOG`. +The Router logger has been substantially changed in v1.17. If you are using the router logger for fail2ban or other monitoring +you will need to update this configuration. + +You can disable Router log by setting `DISABLE_ROUTER_LOG` or by setting all of its sublogger configurations to `none`. You can configure the outputs of this router log by setting the `ROUTER` value in the `[log]` section of the -configuration. `ROUTER` will default to `console` if unset. The Gitea -Router logs at the `Info` level by default, but this can be -changed if desired by setting the `ROUTER_LOG_LEVEL` value. +configuration. `ROUTER` will default to `console` if unset and will default to same level as main logger. + +The Router logger logs the following: + +- `started` messages will be logged at TRACE level +- `polling`/`completed` routers will be logged at INFO +- `slow` routers will be logged at WARN +- `failed` routers will be logged at WARN -Please note, setting the `LEVEL` of this logger to a level above -`ROUTER_LOG_LEVEL` will result in no router logs. +The logging level for the router will default to that of the main configuration. Set `[log..router]` `LEVEL` to change this. Each output sublogger for this logger is configured in `[log.sublogger.router]` sections. There are certain default values diff --git a/modules/log/colors_router.go b/modules/log/colors_router.go index 3064e005cfa9..888198d4e9aa 100644 --- a/modules/log/colors_router.go +++ b/modules/log/colors_router.go @@ -5,6 +5,7 @@ package log import ( + "fmt" "time" ) @@ -72,12 +73,16 @@ var ( wayTooLong = ColorBytes(BgMagenta) ) -// ColoredTime adds colors for time on log +// ColoredTime converts the provided time to a ColoredValue for logging. The duration is always formatted in milliseconds. func ColoredTime(duration time.Duration) *ColoredValue { + // the output of duration in Millisecond is more readable: + // * before: "100.1ms" "100.1μs" "100.1s" + // * better: "100.1ms" "0.1ms" "100100.0ms", readers can compare the values at first glance. + str := fmt.Sprintf("%.1fms", float64(duration.Microseconds())/1000) for i, k := range durations { if duration < k { - return NewColoredValueBytes(duration, &durationColors[i]) + return NewColoredValueBytes(str, &durationColors[i]) } } - return NewColoredValueBytes(duration, &wayTooLong) + return NewColoredValueBytes(str, &wayTooLong) } diff --git a/modules/log/log.go b/modules/log/log.go index cae24f53d87f..f805a36231bd 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -288,4 +288,8 @@ func (l *LoggerAsWriter) Log(msg string) { func init() { _, filename, _, _ := runtime.Caller(0) prefix = strings.TrimSuffix(filename, "modules/log/log.go") + if prefix == filename { + // in case the source code file is moved, we can not trim the suffix, the code above should also be updated. + panic("unable to detect correct package prefix, please update file: " + filename) + } } diff --git a/modules/public/public.go b/modules/public/public.go index a58709d86fc9..f4a769f27aef 100644 --- a/modules/public/public.go +++ b/modules/public/public.go @@ -23,8 +23,11 @@ type Options struct { CorsHandler func(http.Handler) http.Handler } -// AssetsHandler implements the static handler for serving custom or original assets. -func AssetsHandler(opts *Options) func(next http.Handler) http.Handler { +// AssetsURLPathPrefix is the path prefix for static asset files +const AssetsURLPathPrefix = "/assets/" + +// AssetsHandlerFunc implements the static handler for serving custom or original assets. +func AssetsHandlerFunc(opts *Options) http.HandlerFunc { var custPath = filepath.Join(setting.CustomPath, "public") if !filepath.IsAbs(custPath) { custPath = filepath.Join(setting.AppWorkPath, custPath) @@ -36,52 +39,46 @@ func AssetsHandler(opts *Options) func(next http.Handler) http.Handler { opts.Prefix += "/" } - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - if !strings.HasPrefix(req.URL.Path, opts.Prefix) { - next.ServeHTTP(resp, req) - return - } - if req.Method != "GET" && req.Method != "HEAD" { - resp.WriteHeader(http.StatusNotFound) - return - } - - file := req.URL.Path - file = file[len(opts.Prefix):] - if len(file) == 0 { - resp.WriteHeader(http.StatusNotFound) - return - } - if strings.Contains(file, "\\") { - resp.WriteHeader(http.StatusBadRequest) - return - } - file = "/" + file - - var written bool - if opts.CorsHandler != nil { - written = true - opts.CorsHandler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { - written = false - })).ServeHTTP(resp, req) - } - if written { - return - } - - // custom files - if opts.handle(resp, req, http.Dir(custPath), file) { - return - } - - // internal files - if opts.handle(resp, req, fileSystem(opts.Directory), file) { - return - } + return func(resp http.ResponseWriter, req *http.Request) { + if req.Method != "GET" && req.Method != "HEAD" { + resp.WriteHeader(http.StatusNotFound) + return + } + file := req.URL.Path + file = file[len(opts.Prefix):] + if len(file) == 0 { resp.WriteHeader(http.StatusNotFound) - }) + return + } + if strings.Contains(file, "\\") { + resp.WriteHeader(http.StatusBadRequest) + return + } + file = "/" + file + + var written bool + if opts.CorsHandler != nil { + written = true + opts.CorsHandler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + written = false + })).ServeHTTP(resp, req) + } + if written { + return + } + + // custom files + if opts.handle(resp, req, http.Dir(custPath), file) { + return + } + + // internal files + if opts.handle(resp, req, fileSystem(opts.Directory), file) { + return + } + + resp.WriteHeader(http.StatusNotFound) } } diff --git a/modules/setting/log.go b/modules/setting/log.go index b0ae5fb6464f..a53b43119632 100644 --- a/modules/setting/log.go +++ b/modules/setting/log.go @@ -126,6 +126,7 @@ func getStacktraceLogLevel(section *ini.Section, key, defaultValue string) strin func generateLogConfig(sec *ini.Section, name string, defaults defaultLogOptions) (mode, jsonConfig, levelName string) { level := getLogLevel(sec, "LEVEL", LogLevel) + levelName = level.String() stacktraceLevelName := getStacktraceLogLevel(sec, "STACKTRACE_LEVEL", StacktraceLogLevel) stacktraceLevel := log.FromString(stacktraceLevelName) mode = name @@ -254,8 +255,10 @@ func generateNamedLogger(key string, options defaultLogOptions) *LogDescription func newAccessLogService() { EnableAccessLog = Cfg.Section("log").Key("ENABLE_ACCESS_LOG").MustBool(false) AccessLogTemplate = Cfg.Section("log").Key("ACCESS_LOG_TEMPLATE").MustString( - `{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`) - Cfg.Section("log").Key("ACCESS").MustString("file") + `{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`, + ) + // the `MustString` updates the default value, and `log.ACCESS` is used by `generateNamedLogger("access")` later + _ = Cfg.Section("log").Key("ACCESS").MustString("file") if EnableAccessLog { options := newDefaultLogOptions() options.filename = filepath.Join(LogRootPath, "access.log") diff --git a/modules/setting/setting.go b/modules/setting/setting.go index abd6716c74e6..26eeda525fc7 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -333,13 +333,14 @@ var ( LogLevel log.Level StacktraceLogLevel string LogRootPath string - DisableRouterLog bool - RouterLogLevel log.Level - EnableAccessLog bool EnableSSHLog bool - AccessLogTemplate string EnableXORMLog bool + DisableRouterLog bool + + EnableAccessLog bool + AccessLogTemplate string + // Time settings TimeFormat string // UILocation is the location on the UI, so that we can display the time on UI. @@ -601,7 +602,6 @@ func loadFromConf(allowEmpty bool, extraConfig string) { StacktraceLogLevel = getStacktraceLogLevel(Cfg.Section("log"), "STACKTRACE_LEVEL", "None") LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log")) forcePathSeparator(LogRootPath) - RouterLogLevel = log.FromString(Cfg.Section("log").Key("ROUTER_LOG_LEVEL").MustString("Info")) sec := Cfg.Section("server") AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea") diff --git a/modules/web/route.go b/modules/web/route.go index 19193773d53a..86e407701c3c 100644 --- a/modules/web/route.go +++ b/modules/web/route.go @@ -18,144 +18,6 @@ import ( chi "github.com/go-chi/chi/v5" ) -// Wrap converts all kinds of routes to standard library one -func Wrap(handlers ...interface{}) http.HandlerFunc { - if len(handlers) == 0 { - panic("No handlers found") - } - - for _, handler := range handlers { - switch t := handler.(type) { - case http.HandlerFunc, func(http.ResponseWriter, *http.Request), - func(ctx *context.Context), - func(ctx *context.Context) goctx.CancelFunc, - func(*context.APIContext), - func(*context.APIContext) goctx.CancelFunc, - func(*context.PrivateContext), - func(*context.PrivateContext) goctx.CancelFunc, - func(http.Handler) http.Handler: - default: - panic(fmt.Sprintf("Unsupported handler type: %#v", t)) - } - } - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - for i := 0; i < len(handlers); i++ { - handler := handlers[i] - switch t := handler.(type) { - case http.HandlerFunc: - t(resp, req) - if r, ok := resp.(context.ResponseWriter); ok && r.Status() > 0 { - return - } - case func(http.ResponseWriter, *http.Request): - t(resp, req) - if r, ok := resp.(context.ResponseWriter); ok && r.Status() > 0 { - return - } - case func(ctx *context.Context) goctx.CancelFunc: - ctx := context.GetContext(req) - cancel := t(ctx) - if cancel != nil { - defer cancel() - } - if ctx.Written() { - return - } - case func(*context.APIContext) goctx.CancelFunc: - ctx := context.GetAPIContext(req) - cancel := t(ctx) - if cancel != nil { - defer cancel() - } - if ctx.Written() { - return - } - case func(*context.PrivateContext) goctx.CancelFunc: - ctx := context.GetPrivateContext(req) - cancel := t(ctx) - if cancel != nil { - defer cancel() - } - if ctx.Written() { - return - } - case func(ctx *context.Context): - ctx := context.GetContext(req) - t(ctx) - if ctx.Written() { - return - } - case func(*context.APIContext): - ctx := context.GetAPIContext(req) - t(ctx) - if ctx.Written() { - return - } - case func(*context.PrivateContext): - ctx := context.GetPrivateContext(req) - t(ctx) - if ctx.Written() { - return - } - case func(http.Handler) http.Handler: - var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) - if len(handlers) > i+1 { - next = Wrap(handlers[i+1:]...) - } - t(next).ServeHTTP(resp, req) - return - default: - panic(fmt.Sprintf("Unsupported handler type: %#v", t)) - } - } - }) -} - -// Middle wrap a context function as a chi middleware -func Middle(f func(ctx *context.Context)) func(netx http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - ctx := context.GetContext(req) - f(ctx) - if ctx.Written() { - return - } - next.ServeHTTP(ctx.Resp, ctx.Req) - }) - } -} - -// MiddleCancel wrap a context function as a chi middleware -func MiddleCancel(f func(ctx *context.Context) goctx.CancelFunc) func(netx http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - ctx := context.GetContext(req) - cancel := f(ctx) - if cancel != nil { - defer cancel() - } - if ctx.Written() { - return - } - next.ServeHTTP(ctx.Resp, ctx.Req) - }) - } -} - -// MiddleAPI wrap a context function as a chi middleware -func MiddleAPI(f func(ctx *context.APIContext)) func(netx http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - ctx := context.GetAPIContext(req) - f(ctx) - if ctx.Written() { - return - } - next.ServeHTTP(ctx.Resp, ctx.Req) - }) - } -} - // Bind binding an obj to a handler func Bind(obj interface{}) http.HandlerFunc { var tp = reflect.TypeOf(obj) diff --git a/modules/web/routing/context.go b/modules/web/routing/context.go new file mode 100644 index 000000000000..f57b2e9026a9 --- /dev/null +++ b/modules/web/routing/context.go @@ -0,0 +1,51 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package routing + +import ( + "context" + "net/http" +) + +type contextKeyType struct{} + +var contextKey contextKeyType + +//UpdateFuncInfo updates a context's func info +func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) { + record, ok := ctx.Value(contextKey).(*requestRecord) + if !ok { + return + } + + record.lock.Lock() + record.funcInfo = funcInfo + record.lock.Unlock() + +} + +// MarkLongPolling marks the reuqest is a long-polling request, and the logger may output different message for it +func MarkLongPolling(resp http.ResponseWriter, req *http.Request) { + record, ok := req.Context().Value(contextKey).(*requestRecord) + if !ok { + return + } + + record.lock.Lock() + record.isLongPolling = true + record.lock.Unlock() +} + +//UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that. +func UpdatePanicError(ctx context.Context, err interface{}) { + record, ok := ctx.Value(contextKey).(*requestRecord) + if !ok { + return + } + + record.lock.Lock() + record.panicError = err + record.lock.Unlock() +} diff --git a/modules/web/routing/funcinfo.go b/modules/web/routing/funcinfo.go new file mode 100644 index 000000000000..6d3986e364e7 --- /dev/null +++ b/modules/web/routing/funcinfo.go @@ -0,0 +1,171 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package routing + +import ( + "fmt" + "reflect" + "runtime" + "strings" + "sync" +) + +var funcInfoMap = map[uintptr]*FuncInfo{} +var funcInfoNameMap = map[string]*FuncInfo{} +var funcInfoMapMu sync.RWMutex + +// FuncInfo contains information about the function to be logged by the router log +type FuncInfo struct { + file string + shortFile string + line int + name string + shortName string +} + +// String returns a string form of the FuncInfo for logging +func (info *FuncInfo) String() string { + if info == nil { + return "unknown-handler" + } + return fmt.Sprintf("%s:%d(%s)", info.shortFile, info.line, info.shortName) +} + +// GetFuncInfo returns the FuncInfo for a provided function and friendlyname +func GetFuncInfo(fn interface{}, friendlyName ...string) *FuncInfo { + // ptr represents the memory position of the function passed in as v. + // This will be used as program counter in FuncForPC below + ptr := reflect.ValueOf(fn).Pointer() + + // if we have been provided with a friendlyName look for the named funcs + if len(friendlyName) == 1 { + name := friendlyName[0] + funcInfoMapMu.RLock() + info, ok := funcInfoNameMap[name] + funcInfoMapMu.RUnlock() + if ok { + return info + } + } + + // Otherwise attempt to get pre-cached information for this function pointer + funcInfoMapMu.RLock() + info, ok := funcInfoMap[ptr] + funcInfoMapMu.RUnlock() + + if ok { + if len(friendlyName) == 1 { + name := friendlyName[0] + info = copyFuncInfo(info) + info.shortName = name + + funcInfoNameMap[name] = info + funcInfoMapMu.Lock() + funcInfoNameMap[name] = info + funcInfoMapMu.Unlock() + } + return info + } + + // This is likely the first time we have seen this function + // + // Get the runtime.func for this function (if we can) + f := runtime.FuncForPC(ptr) + if f != nil { + info = convertToFuncInfo(f) + + // cache this info globally + funcInfoMapMu.Lock() + funcInfoMap[ptr] = info + + // if we have been provided with a friendlyName override the short name we've generated + if len(friendlyName) == 1 { + name := friendlyName[0] + info = copyFuncInfo(info) + info.shortName = name + funcInfoNameMap[name] = info + } + funcInfoMapMu.Unlock() + } + return info +} + +// convertToFuncInfo take a runtime.Func and convert it to a logFuncInfo, fill in shorten filename, etc +func convertToFuncInfo(f *runtime.Func) *FuncInfo { + file, line := f.FileLine(f.Entry()) + + info := &FuncInfo{ + file: strings.ReplaceAll(file, "\\", "/"), + line: line, + name: f.Name(), + } + + // only keep last 2 names in path, fall back to funcName if not + info.shortFile = shortenFilename(info.file, info.name) + + // remove package prefix. eg: "xxx.com/pkg1/pkg2.foo" => "pkg2.foo" + pos := strings.LastIndexByte(info.name, '/') + if pos >= 0 { + info.shortName = info.name[pos+1:] + } else { + info.shortName = info.name + } + + // remove ".func[0-9]*" suffix for anonymous func + info.shortName = trimAnonymousFunctionSuffix(info.shortName) + + return info +} + +func copyFuncInfo(l *FuncInfo) *FuncInfo { + return &FuncInfo{ + file: l.file, + shortFile: l.shortFile, + line: l.line, + name: l.name, + shortName: l.shortName, + } +} + +// shortenFilename generates a short source code filename from a full package path, eg: "code.gitea.io/routers/common/logger_context.go" => "common/logger_context.go" +func shortenFilename(filename, fallback string) string { + if filename == "" { + return fallback + } + if lastIndex := strings.LastIndexByte(filename, '/'); lastIndex >= 0 { + if secondLastIndex := strings.LastIndexByte(filename[:lastIndex], '/'); secondLastIndex >= 0 { + return filename[secondLastIndex+1:] + } + } + return filename +} + +// trimAnonymousFunctionSuffix trims ".func[0-9]*" from the end of anonymous function names, we only want to see the main function names in logs +func trimAnonymousFunctionSuffix(name string) string { + // if the name is an anonymous name, it should be like "{main-function}.func1", so the length can not be less than 7 + if len(name) < 7 { + return name + } + + funcSuffixIndex := strings.LastIndex(name, ".func") + if funcSuffixIndex < 0 { + return name + } + + hasFuncSuffix := true + + // len(".func") = 5 + for i := funcSuffixIndex + 5; i < len(name); i++ { + if name[i] < '0' || name[i] > '9' { + hasFuncSuffix = false + break + } + } + + if hasFuncSuffix { + return name[:funcSuffixIndex] + } + return name +} diff --git a/modules/web/routing/funcinfo_test.go b/modules/web/routing/funcinfo_test.go new file mode 100644 index 000000000000..9cea7e281789 --- /dev/null +++ b/modules/web/routing/funcinfo_test.go @@ -0,0 +1,81 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package routing + +import ( + "fmt" + "testing" +) + +func Test_shortenFilename(t *testing.T) { + tests := []struct { + filename string + fallback string + expected string + }{ + { + "code.gitea.io/routers/common/logger_context.go", + "NO_FALLBACK", + "common/logger_context.go", + }, + { + "common/logger_context.go", + "NO_FALLBACK", + "common/logger_context.go", + }, + { + "logger_context.go", + "NO_FALLBACK", + "logger_context.go", + }, + { + "", + "USE_FALLBACK", + "USE_FALLBACK", + }, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("shortenFilename('%s')", tt.filename), func(t *testing.T) { + if gotShort := shortenFilename(tt.filename, tt.fallback); gotShort != tt.expected { + t.Errorf("shortenFilename('%s'), expect '%s', but get '%s'", tt.filename, tt.expected, gotShort) + } + }) + } +} + +func Test_trimAnonymousFunctionSuffix(t *testing.T) { + tests := []struct { + name string + want string + }{ + { + "notAnonymous", + "notAnonymous", + }, + { + "anonymous.func1", + "anonymous", + }, + { + "notAnonymous.funca", + "notAnonymous.funca", + }, + { + "anonymous.func100", + "anonymous", + }, + { + "anonymous.func100.func6", + "anonymous.func100", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := trimAnonymousFunctionSuffix(tt.name); got != tt.want { + t.Errorf("trimAnonymousFunctionSuffix() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/web/routing/logger.go b/modules/web/routing/logger.go new file mode 100644 index 000000000000..cf3b50725d8b --- /dev/null +++ b/modules/web/routing/logger.go @@ -0,0 +1,106 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package routing + +import ( + "net/http" + "time" + + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/log" +) + +// NewLoggerHandler is a handler that will log routing to the router log taking account of +// routing information +func NewLoggerHandler() func(next http.Handler) http.Handler { + manager := requestRecordsManager{ + requestRecords: map[uint64]*requestRecord{}, + } + manager.startSlowQueryDetector(3 * time.Second) + + logger := log.GetLogger("router") + manager.print = logPrinter(logger) + return manager.handler +} + +var ( + startMessage = log.NewColoredValueBytes("started ", log.DEBUG.Color()) + slowMessage = log.NewColoredValueBytes("slow ", log.WARN.Color()) + pollingMessage = log.NewColoredValueBytes("polling ", log.INFO.Color()) + failedMessage = log.NewColoredValueBytes("failed ", log.WARN.Color()) + completedMessage = log.NewColoredValueBytes("completed", log.INFO.Color()) + unknownHandlerMessage = log.NewColoredValueBytes("completed", log.ERROR.Color()) +) + +func logPrinter(logger log.Logger) func(trigger Event, record *requestRecord) { + return func(trigger Event, record *requestRecord) { + if trigger == StartEvent { + if !logger.IsTrace() { + // for performance, if the "started" message shouldn't be logged, we just return as early as possible + // developers can set the router log level to TRACE to get the "started" request messages. + return + } + // when a request starts, we have no information about the handler function information, we only have the request path + req := record.request + logger.Trace("router: %s %v %s for %s", startMessage, log.ColoredMethod(req.Method), req.RequestURI, req.RemoteAddr) + return + } + + req := record.request + + // Get data from the record + record.lock.Lock() + handlerFuncInfo := record.funcInfo.String() + isLongPolling := record.isLongPolling + isUnknownHandler := record.funcInfo == nil + panicErr := record.panicError + record.lock.Unlock() + + if trigger == StillExecutingEvent { + message := slowMessage + level := log.WARN + if isLongPolling { + level = log.INFO + message = pollingMessage + } + _ = logger.Log(0, level, "router: %s %v %s for %s, elapsed %v @ %s", + message, + log.ColoredMethod(req.Method), req.RequestURI, req.RemoteAddr, + log.ColoredTime(time.Since(record.startTime)), + handlerFuncInfo, + ) + return + } + + if panicErr != nil { + _ = logger.Log(0, log.WARN, "router: %s %v %s for %s, panic in %v @ %s, err=%v", + failedMessage, + log.ColoredMethod(req.Method), req.RequestURI, req.RemoteAddr, + log.ColoredTime(time.Since(record.startTime)), + handlerFuncInfo, + panicErr, + ) + return + } + + var status int + if v, ok := record.responseWriter.(context.ResponseWriter); ok { + status = v.Status() + } + level := log.INFO + message := completedMessage + if isUnknownHandler { + level = log.ERROR + message = unknownHandlerMessage + } + + _ = logger.Log(0, level, "router: %s %v %s for %s, %v %v in %v @ %s", + message, + log.ColoredMethod(req.Method), req.RequestURI, req.RemoteAddr, + log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(status)), log.ColoredTime(time.Since(record.startTime)), + handlerFuncInfo, + ) + } +} diff --git a/modules/web/routing/logger_manager.go b/modules/web/routing/logger_manager.go new file mode 100644 index 000000000000..31fd09f31203 --- /dev/null +++ b/modules/web/routing/logger_manager.go @@ -0,0 +1,122 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package routing + +import ( + "context" + "net/http" + "sync" + "time" + + "code.gitea.io/gitea/modules/graceful" +) + +// Event indicates when the printer is triggered +type Event int + +const ( + //StartEvent at the beginning of a request + StartEvent Event = iota + + //StillExecutingEvent the request is still executing + StillExecutingEvent + + //EndEvent the request has ended (either completed or failed) + EndEvent +) + +// Printer is used to output the log for a request +type Printer func(trigger Event, record *requestRecord) + +type requestRecordsManager struct { + print Printer + + lock sync.Mutex + + requestRecords map[uint64]*requestRecord + count uint64 +} + +func (manager *requestRecordsManager) startSlowQueryDetector(threshold time.Duration) { + go graceful.GetManager().RunWithShutdownContext(func(baseCtx context.Context) { + // This go-routine checks all active requests every second. + // If a request has been running for a long time (eg: /user/events), we also print a log with "still-executing" message + // After the "still-executing" log is printed, the record will be removed from the map to prevent from duplicated logs in future + + // We do not care about accurate duration here. It just does the check periodically, 0.5s or 1.5s are all OK. + t := time.NewTicker(time.Second) + for { + select { + case <-baseCtx.Done(): + return + case <-t.C: + now := time.Now() + + var slowRequests []*requestRecord + + // find all slow requests with lock + manager.lock.Lock() + for index, record := range manager.requestRecords { + if now.Sub(record.startTime) < threshold { + continue + } + + slowRequests = append(slowRequests, record) + delete(manager.requestRecords, index) + } + manager.lock.Unlock() + + // print logs for slow requests + for _, record := range slowRequests { + manager.print(StillExecutingEvent, record) + } + } + } + }) +} + +func (manager *requestRecordsManager) handler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + record := &requestRecord{ + startTime: time.Now(), + request: req, + responseWriter: w, + } + + // generate a record index an insert into the map + manager.lock.Lock() + record.index = manager.count + manager.count++ + manager.requestRecords[record.index] = record + manager.lock.Unlock() + + defer func() { + // just in case there is a panic. now the panics are all recovered in middleware.go + localPanicErr := recover() + if localPanicErr != nil { + record.lock.Lock() + record.panicError = localPanicErr + record.lock.Unlock() + } + + // remove from the record map + manager.lock.Lock() + delete(manager.requestRecords, record.index) + manager.lock.Unlock() + + // log the end of the request + manager.print(EndEvent, record) + + if localPanicErr != nil { + // the panic wasn't recovered before us, so we should pass it up, and let the framework handle the panic error + panic(localPanicErr) + } + }() + + req = req.WithContext(context.WithValue(req.Context(), contextKey, record)) + manager.print(StartEvent, record) + next.ServeHTTP(w, req) + }) +} diff --git a/modules/web/routing/requestrecord.go b/modules/web/routing/requestrecord.go new file mode 100644 index 000000000000..5e225f32e4e4 --- /dev/null +++ b/modules/web/routing/requestrecord.go @@ -0,0 +1,29 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package routing + +import ( + "net/http" + "sync" + "time" +) + +type requestRecord struct { + // index of the record in the records map + index uint64 + + // immutable fields + startTime time.Time + request *http.Request + responseWriter http.ResponseWriter + + // mutex + lock sync.RWMutex + + // mutable fields + isLongPolling bool + funcInfo *FuncInfo + panicError interface{} +} diff --git a/modules/web/wrap.go b/modules/web/wrap.go new file mode 100644 index 000000000000..b55b87606983 --- /dev/null +++ b/modules/web/wrap.go @@ -0,0 +1,117 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package web + +import ( + goctx "context" + "net/http" + "strings" + + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/web/routing" +) + +// Wrap converts all kinds of routes to standard library one +func Wrap(handlers ...interface{}) http.HandlerFunc { + if len(handlers) == 0 { + panic("No handlers found") + } + + ourHandlers := make([]wrappedHandlerFunc, 0, len(handlers)) + + for _, handler := range handlers { + ourHandlers = append(ourHandlers, convertHandler(handler)) + } + return wrapInternal(ourHandlers) +} + +func wrapInternal(handlers []wrappedHandlerFunc) http.HandlerFunc { + return func(resp http.ResponseWriter, req *http.Request) { + var defers []func() + defer func() { + for i := len(defers) - 1; i >= 0; i-- { + defers[i]() + } + }() + for i := 0; i < len(handlers); i++ { + handler := handlers[i] + others := handlers[i+1:] + done, deferrable := handler(resp, req, others...) + if deferrable != nil { + defers = append(defers, deferrable) + } + if done { + return + } + } + } +} + +// Middle wrap a context function as a chi middleware +func Middle(f func(ctx *context.Context)) func(next http.Handler) http.Handler { + funcInfo := routing.GetFuncInfo(f) + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetContext(req) + f(ctx) + if ctx.Written() { + return + } + next.ServeHTTP(ctx.Resp, ctx.Req) + }) + } +} + +// MiddleCancel wrap a context function as a chi middleware +func MiddleCancel(f func(ctx *context.Context) goctx.CancelFunc) func(netx http.Handler) http.Handler { + funcInfo := routing.GetFuncInfo(f) + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetContext(req) + cancel := f(ctx) + if cancel != nil { + defer cancel() + } + if ctx.Written() { + return + } + next.ServeHTTP(ctx.Resp, ctx.Req) + }) + } +} + +// MiddleAPI wrap a context function as a chi middleware +func MiddleAPI(f func(ctx *context.APIContext)) func(next http.Handler) http.Handler { + funcInfo := routing.GetFuncInfo(f) + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetAPIContext(req) + f(ctx) + if ctx.Written() { + return + } + next.ServeHTTP(ctx.Resp, ctx.Req) + }) + } +} + +// WrapWithPrefix wraps a provided handler function at a prefix +func WrapWithPrefix(pathPrefix string, handler http.HandlerFunc, friendlyName ...string) func(next http.Handler) http.Handler { + funcInfo := routing.GetFuncInfo(handler, friendlyName...) + + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + if !strings.HasPrefix(req.URL.Path, pathPrefix) { + next.ServeHTTP(resp, req) + return + } + routing.UpdateFuncInfo(req.Context(), funcInfo) + handler(resp, req) + }) + } +} diff --git a/modules/web/wrap_convert.go b/modules/web/wrap_convert.go new file mode 100644 index 000000000000..f2e05de7c1d8 --- /dev/null +++ b/modules/web/wrap_convert.go @@ -0,0 +1,101 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package web + +import ( + goctx "context" + "fmt" + "net/http" + + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/web/routing" +) + +type wrappedHandlerFunc func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) + +func convertHandler(handler interface{}) wrappedHandlerFunc { + funcInfo := routing.GetFuncInfo(handler) + switch t := handler.(type) { + case http.HandlerFunc: + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + t(resp, req) + if r, ok := resp.(context.ResponseWriter); ok && r.Status() > 0 { + done = true + } + return + } + case func(http.ResponseWriter, *http.Request): + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + t(resp, req) + if r, ok := resp.(context.ResponseWriter); ok && r.Status() > 0 { + done = true + } + return + } + + case func(ctx *context.Context): + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetContext(req) + t(ctx) + done = ctx.Written() + return + } + case func(ctx *context.Context) goctx.CancelFunc: + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetContext(req) + deferrable = t(ctx) + done = ctx.Written() + return + } + case func(*context.APIContext): + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetAPIContext(req) + t(ctx) + done = ctx.Written() + return + } + case func(*context.APIContext) goctx.CancelFunc: + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetAPIContext(req) + deferrable = t(ctx) + done = ctx.Written() + return + } + case func(*context.PrivateContext): + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetPrivateContext(req) + t(ctx) + done = ctx.Written() + return + } + case func(*context.PrivateContext) goctx.CancelFunc: + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + routing.UpdateFuncInfo(req.Context(), funcInfo) + ctx := context.GetPrivateContext(req) + deferrable = t(ctx) + done = ctx.Written() + return + } + case func(http.Handler) http.Handler: + return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { + var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) + if len(others) > 0 { + next = wrapInternal(others) + } + routing.UpdateFuncInfo(req.Context(), funcInfo) + t(next).ServeHTTP(resp, req) + return + } + default: + panic(fmt.Sprintf("Unsupported handler type: %#v", t)) + } +} diff --git a/routers/common/logger.go b/routers/common/logger.go deleted file mode 100644 index bc1149543c94..000000000000 --- a/routers/common/logger.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2021 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package common - -import ( - "net/http" - "time" - - "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/log" -) - -// LoggerHandler is a handler that will log the routing to the default gitea log -func LoggerHandler(level log.Level) func(next http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - start := time.Now() - - _ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(req.Method), req.URL.RequestURI(), req.RemoteAddr) - - next.ServeHTTP(w, req) - - var status int - if v, ok := w.(context.ResponseWriter); ok { - status = v.Status() - } - - _ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(req.Method), req.URL.RequestURI(), log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(status)), log.ColoredTime(time.Since(start))) - }) - } -} diff --git a/routers/common/middleware.go b/routers/common/middleware.go index 3f535628aa30..2b6343b10f28 100644 --- a/routers/common/middleware.go +++ b/routers/common/middleware.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web/routing" "github.com/chi-middleware/proxy" "github.com/go-chi/chi/v5/middleware" @@ -49,11 +50,10 @@ func Middlewares() []func(http.Handler) http.Handler { handlers = append(handlers, middleware.StripSlashes) - if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE { - if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel { - handlers = append(handlers, LoggerHandler(setting.RouterLogLevel)) - } + if !setting.DisableRouterLog { + handlers = append(handlers, routing.NewLoggerHandler()) } + if setting.EnableAccessLog { handlers = append(handlers, context.AccessLogger()) } @@ -63,10 +63,11 @@ func Middlewares() []func(http.Handler) http.Handler { // Why we need this? The Recovery() will try to render a beautiful // error page for user, but the process can still panic again, and other // middleware like session also may panic then we have to recover twice - // and send a simple error page that should not panic any more. + // and send a simple error page that should not panic anymore. defer func() { if err := recover(); err != nil { - combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2))) + routing.UpdatePanicError(req.Context(), err) + combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, log.Stack(2)) log.Error("%v", combinedErr) if setting.IsProd { http.Error(resp, http.StatusText(500), 500) diff --git a/routers/install/routes.go b/routers/install/routes.go index ad0003a9e8e3..d7d8527cf5e6 100644 --- a/routers/install/routes.go +++ b/routers/install/routes.go @@ -38,8 +38,8 @@ func installRecovery() func(next http.Handler) http.Handler { // should not panic any more. defer func() { if err := recover(); err != nil { - combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2))) - log.Error(combinedErr) + combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, log.Stack(2)) + log.Error("%s", combinedErr) if setting.IsProd { http.Error(w, http.StatusText(500), 500) } else { @@ -49,8 +49,8 @@ func installRecovery() func(next http.Handler) http.Handler { }() if err := recover(); err != nil { - combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2))) - log.Error("%v", combinedErr) + combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, log.Stack(2)) + log.Error("%s", combinedErr) lc := middleware.Locale(w, req) var store = dataStore{ @@ -85,10 +85,10 @@ func Routes() *web.Route { r.Use(middle) } - r.Use(public.AssetsHandler(&public.Options{ + r.Use(web.WrapWithPrefix(public.AssetsURLPathPrefix, public.AssetsHandlerFunc(&public.Options{ Directory: path.Join(setting.StaticRootPath, "public"), - Prefix: "/assets", - })) + Prefix: public.AssetsURLPathPrefix, + }), "InstallAssetsHandler")) r.Use(session.Sessioner(session.Options{ Provider: setting.SessionConfig.Provider, @@ -106,8 +106,11 @@ func Routes() *web.Route { r.Use(Init) r.Get("/", Install) r.Post("/", web.Bind(forms.InstallForm{}), SubmitInstall) - r.NotFound(func(w http.ResponseWriter, req *http.Request) { - http.Redirect(w, req, setting.AppURL, http.StatusFound) - }) + + r.NotFound(web.Wrap(installNotFound)) return r } + +func installNotFound(w http.ResponseWriter, req *http.Request) { + http.Redirect(w, req, setting.AppURL, http.StatusFound) +} diff --git a/routers/web/base.go b/routers/web/base.go index 98713bc8818f..fd942d3c8786 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -21,12 +21,14 @@ import ( "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/modules/web/routing" "code.gitea.io/gitea/services/auth" "gitea.com/go-chi/session" ) func storageHandler(storageSetting setting.Storage, prefix string, objStore storage.ObjectStorage) func(next http.Handler) http.Handler { + funcInfo := routing.GetFuncInfo(storageHandler, prefix) return func(next http.Handler) http.Handler { if storageSetting.ServeDirect { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { @@ -39,6 +41,7 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor next.ServeHTTP(w, req) return } + routing.UpdateFuncInfo(req.Context(), funcInfo) rPath := strings.TrimPrefix(req.URL.RequestURI(), "/"+prefix) u, err := objStore.URL(rPath, path.Base(rPath)) @@ -73,6 +76,7 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor next.ServeHTTP(w, req) return } + routing.UpdateFuncInfo(req.Context(), funcInfo) rPath := strings.TrimPrefix(req.URL.EscapedPath(), "/"+prefix+"/") rPath = strings.TrimPrefix(rPath, "/") @@ -126,8 +130,9 @@ func Recovery() func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() { if err := recover(); err != nil { - combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2))) - log.Error("%v", combinedErr) + routing.UpdatePanicError(req.Context(), err) + combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, log.Stack(2)) + log.Error("%s", combinedErr) sessionStore := session.GetSession(req) diff --git a/routers/web/web.go b/routers/web/web.go index 55a64ee7d5dd..e934095b7914 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/modules/web/routing" "code.gitea.io/gitea/routers/api/v1/misc" "code.gitea.io/gitea/routers/web/admin" "code.gitea.io/gitea/routers/web/auth" @@ -73,11 +74,11 @@ func CorsHandler() func(next http.Handler) http.Handler { func Routes(sessioner func(http.Handler) http.Handler) *web.Route { routes := web.NewRoute() - routes.Use(public.AssetsHandler(&public.Options{ + routes.Use(web.WrapWithPrefix(public.AssetsURLPathPrefix, public.AssetsHandlerFunc(&public.Options{ Directory: path.Join(setting.StaticRootPath, "public"), - Prefix: "/assets", + Prefix: public.AssetsURLPathPrefix, CorsHandler: CorsHandler(), - })) + }), "AssetsHandler")) routes.Use(sessioner) @@ -293,7 +294,7 @@ func RegisterRoutes(m *web.Route) { }) }, reqSignOut) - m.Any("/user/events", events.Events) + m.Any("/user/events", routing.MarkLongPolling, events.Events) m.Group("/login/oauth", func() { m.Get("/authorize", bindIgnErr(forms.AuthorizationForm{}), auth.AuthorizeOAuth) From 16d378fefc0a569f2a7aed29e6c7f288b3d83f02 Mon Sep 17 00:00:00 2001 From: Gusted Date: Thu, 20 Jan 2022 16:18:46 +0100 Subject: [PATCH 3/7] Use correct translation key for errors (#18342) - Noted by: https://github.com/go-gitea/gitea/issues/17876#issuecomment-1017503614 --- routers/web/org/setting.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/routers/web/org/setting.go b/routers/web/org/setting.go index 081e103f79b5..747a5134b4be 100644 --- a/routers/web/org/setting.go +++ b/routers/web/org/setting.go @@ -74,10 +74,14 @@ func SettingsPost(ctx *context.Context) { ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSettingsOptions, &form) return } else if err = user_model.ChangeUserName(org.AsUser(), form.Name); err != nil { - if db.IsErrNameReserved(err) || db.IsErrNamePatternNotAllowed(err) { + switch { + case db.IsErrNameReserved(err): ctx.Data["OrgName"] = true - ctx.RenderWithErr(ctx.Tr("form.illegal_username"), tplSettingsOptions, &form) - } else { + ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(db.ErrNameReserved).Name), tplSettingsOptions, &form) + case db.IsErrNamePatternNotAllowed(err): + ctx.Data["OrgName"] = true + ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(db.ErrNamePatternNotAllowed).Pattern), tplSettingsOptions, &form) + default: ctx.ServerError("ChangeUserName", err) } return From 1d98d205f5825f40110e6628b61a97c91ac7f72d Mon Sep 17 00:00:00 2001 From: Gusted Date: Thu, 20 Jan 2022 18:00:38 +0100 Subject: [PATCH 4/7] Enable deprecation error for v1.17.0 (#18341) Co-authored-by: Andrew Thornton --- modules/indexer/issues/indexer.go | 2 +- modules/indexer/issues/indexer_test.go | 6 +-- modules/setting/indexer.go | 34 +++++----------- modules/setting/lfs.go | 2 + modules/setting/mailer.go | 6 ++- modules/setting/mirror.go | 5 ++- modules/setting/queue.go | 56 +++++++++++++++++--------- modules/setting/setting.go | 11 +++++ modules/setting/task.go | 13 ++++-- routers/web/auth/webauthn.go | 1 + 10 files changed, 84 insertions(+), 52 deletions(-) diff --git a/modules/indexer/issues/indexer.go b/modules/indexer/issues/indexer.go index 4db5091762c1..8530210628cb 100644 --- a/modules/indexer/issues/indexer.go +++ b/modules/indexer/issues/indexer.go @@ -110,7 +110,7 @@ func InitIssueIndexer(syncReindex bool) { return } - iData := make([]*IndexerData, 0, setting.Indexer.IssueQueueBatchNumber) + iData := make([]*IndexerData, 0, len(data)) for _, datum := range data { indexerData, ok := datum.(*IndexerData) if !ok { diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 866e3cc7c920..ba35e37fd872 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -34,12 +34,12 @@ func TestBleveSearchIssues(t *testing.T) { assert.Fail(t, "Unable to create temporary directory: %v", err) return } - oldQueueDir := setting.Indexer.IssueQueueDir + + setting.Cfg.Section("queue.issue_indexer").Key("DATADIR").MustString(path.Join(tmpIndexerDir, "issues.queue")) + oldIssuePath := setting.Indexer.IssuePath - setting.Indexer.IssueQueueDir = path.Join(tmpIndexerDir, "issues.queue") setting.Indexer.IssuePath = path.Join(tmpIndexerDir, "issues.queue") defer func() { - setting.Indexer.IssueQueueDir = oldQueueDir setting.Indexer.IssuePath = oldIssuePath util.RemoveAll(tmpIndexerDir) }() diff --git a/modules/setting/indexer.go b/modules/setting/indexer.go index 2e9d8b288356..f103a7464b81 100644 --- a/modules/setting/indexer.go +++ b/modules/setting/indexer.go @@ -14,32 +14,20 @@ import ( "github.com/gobwas/glob" ) -// enumerates all the indexer queue types -const ( - LevelQueueType = "levelqueue" - ChannelQueueType = "channel" - RedisQueueType = "redis" -) - var ( // Indexer settings Indexer = struct { - IssueType string - IssuePath string - IssueConnStr string - IssueIndexerName string - IssueQueueType string // DEPRECATED - replaced by queue.issue_indexer - IssueQueueDir string // DEPRECATED - replaced by queue.issue_indexer - IssueQueueConnStr string // DEPRECATED - replaced by queue.issue_indexer - IssueQueueBatchNumber int // DEPRECATED - replaced by queue.issue_indexer - StartupTimeout time.Duration + IssueType string + IssuePath string + IssueConnStr string + IssueIndexerName string + StartupTimeout time.Duration RepoIndexerEnabled bool RepoType string RepoPath string RepoConnStr string RepoIndexerName string - UpdateQueueLength int // DEPRECATED - replaced by queue.issue_indexer MaxIndexerFileSize int64 IncludePatterns []glob.Glob ExcludePatterns []glob.Glob @@ -49,7 +37,6 @@ var ( IssuePath: "indexers/issues.bleve", IssueConnStr: "", IssueIndexerName: "gitea_issues", - IssueQueueType: LevelQueueType, RepoIndexerEnabled: false, RepoType: "bleve", @@ -72,11 +59,12 @@ func newIndexerService() { Indexer.IssueIndexerName = sec.Key("ISSUE_INDEXER_NAME").MustString(Indexer.IssueIndexerName) // The following settings are deprecated and can be overridden by settings in [queue] or [queue.issue_indexer] - Indexer.IssueQueueType = sec.Key("ISSUE_INDEXER_QUEUE_TYPE").MustString("") - Indexer.IssueQueueDir = filepath.ToSlash(sec.Key("ISSUE_INDEXER_QUEUE_DIR").MustString("")) - Indexer.IssueQueueConnStr = sec.Key("ISSUE_INDEXER_QUEUE_CONN_STR").MustString("") - Indexer.IssueQueueBatchNumber = sec.Key("ISSUE_INDEXER_QUEUE_BATCH_NUMBER").MustInt(0) - Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(0) + // FIXME: DEPRECATED to be removed in v1.18.0 + deprecatedSetting("indexer", "ISSUE_INDEXER_QUEUE_TYPE", "queue.issue_indexer", "TYPE") + deprecatedSetting("indexer", "ISSUE_INDEXER_QUEUE_DIR", "queue.issue_indexer", "DATADIR") + deprecatedSetting("indexer", "ISSUE_INDEXER_QUEUE_CONN_STR", "queue.issue_indexer", "CONN_STR") + deprecatedSetting("indexer", "ISSUE_INDEXER_QUEUE_BATCH_NUMBER", "queue.issue_indexer", "BATCH_LENGTH") + deprecatedSetting("indexer", "UPDATE_BUFFER_LEN", "queue.issue_indexer", "LENGTH") Indexer.RepoIndexerEnabled = sec.Key("REPO_INDEXER_ENABLED").MustBool(false) Indexer.RepoType = sec.Key("REPO_INDEXER_TYPE").MustString("bleve") diff --git a/modules/setting/lfs.go b/modules/setting/lfs.go index a4bbd3c3ff37..7065ce638344 100644 --- a/modules/setting/lfs.go +++ b/modules/setting/lfs.go @@ -36,6 +36,8 @@ func newLFSService() { storageType := lfsSec.Key("STORAGE_TYPE").MustString("") // Specifically default PATH to LFS_CONTENT_PATH + //FIXME: DEPRECATED to be removed in v1.18.0 + deprecatedSetting("server", "LFS_CONTENT_PATH", "lfs", "PATH") lfsSec.Key("PATH").MustString( sec.Key("LFS_CONTENT_PATH").String()) diff --git a/modules/setting/mailer.go b/modules/setting/mailer.go index d7713f3b80be..5da520171e94 100644 --- a/modules/setting/mailer.go +++ b/modules/setting/mailer.go @@ -79,13 +79,15 @@ func newMailService() { MailService.From = sec.Key("FROM").MustString(MailService.User) MailService.EnvelopeFrom = sec.Key("ENVELOPE_FROM").MustString("") + // FIXME: DEPRECATED to be removed in v1.18.0 + deprecatedSetting("mailer", "ENABLE_HTML_ALTERNATIVE", "mailer", "SEND_AS_PLAIN_TEXT") if sec.HasKey("ENABLE_HTML_ALTERNATIVE") { - log.Warn("ENABLE_HTML_ALTERNATIVE is deprecated, use SEND_AS_PLAIN_TEXT") MailService.SendAsPlainText = !sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false) } + // FIXME: DEPRECATED to be removed in v1.18.0 + deprecatedSetting("mailer", "USE_SENDMAIL", "mailer", "MAILER_TYPE") if sec.HasKey("USE_SENDMAIL") { - log.Warn("USE_SENDMAIL is deprecated, use MAILER_TYPE=sendmail") if MailService.MailerType == "" && sec.Key("USE_SENDMAIL").MustBool(false) { MailService.MailerType = "sendmail" } diff --git a/modules/setting/mirror.go b/modules/setting/mirror.go index b0d5b2a4dcd7..e49393e39c6e 100644 --- a/modules/setting/mirror.go +++ b/modules/setting/mirror.go @@ -30,11 +30,12 @@ var ( func newMirror() { // Handle old configuration through `[repository]` `DISABLE_MIRRORS` // - please note this was badly named and only disabled the creation of new pull mirrors + // FIXME: DEPRECATED to be removed in v1.18.0 + deprecatedSetting("repository", "DISABLE_MIRRORS", "mirror", "ENABLED") if Cfg.Section("repository").Key("DISABLE_MIRRORS").MustBool(false) { - log.Warn("Deprecated DISABLE_MIRRORS config is used, please change your config and use the options within the [mirror] section") - // TODO: enable on v1.17.0: log.Error("Deprecated fallback used, will be removed in v1.18.0") Mirror.DisableNewPull = true } + if err := Cfg.Section("mirror").MapTo(&Mirror); err != nil { log.Fatal("Failed to map Mirror settings: %v", err) } diff --git a/modules/setting/queue.go b/modules/setting/queue.go index 56a036aeef58..cb86cbdfe05c 100644 --- a/modules/setting/queue.go +++ b/modules/setting/queue.go @@ -107,51 +107,71 @@ func NewQueueService() { Queue.SetName = sec.Key("SET_NAME").MustString("") // Now handle the old issue_indexer configuration + // FIXME: DEPRECATED to be removed in v1.18.0 section := Cfg.Section("queue.issue_indexer") directlySet := toDirectlySetKeysMap(section) if !directlySet["TYPE"] && defaultType == "" { - switch Indexer.IssueQueueType { - case LevelQueueType: + switch typ := Cfg.Section("indexer").Key("ISSUE_INDEXER_QUEUE_TYPE").MustString(""); typ { + case "levelqueue": _, _ = section.NewKey("TYPE", "level") - case ChannelQueueType: + case "channel": _, _ = section.NewKey("TYPE", "persistable-channel") - case RedisQueueType: + case "redis": _, _ = section.NewKey("TYPE", "redis") case "": _, _ = section.NewKey("TYPE", "level") default: - log.Fatal("Unsupported indexer queue type: %v", - Indexer.IssueQueueType) + log.Fatal("Unsupported indexer queue type: %v", typ) } } - if !directlySet["LENGTH"] && Indexer.UpdateQueueLength != 0 { - _, _ = section.NewKey("LENGTH", strconv.Itoa(Indexer.UpdateQueueLength)) + if !directlySet["LENGTH"] { + length := Cfg.Section("indexer").Key("UPDATE_BUFFER_LEN").MustInt(0) + if length != 0 { + _, _ = section.NewKey("LENGTH", strconv.Itoa(length)) + } } - if !directlySet["BATCH_LENGTH"] && Indexer.IssueQueueBatchNumber != 0 { - _, _ = section.NewKey("BATCH_LENGTH", strconv.Itoa(Indexer.IssueQueueBatchNumber)) + if !directlySet["BATCH_LENGTH"] { + fallback := Cfg.Section("indexer").Key("ISSUE_INDEXER_QUEUE_BATCH_NUMBER").MustInt(0) + if fallback != 0 { + _, _ = section.NewKey("BATCH_LENGTH", strconv.Itoa(fallback)) + } } - if !directlySet["DATADIR"] && Indexer.IssueQueueDir != "" { - _, _ = section.NewKey("DATADIR", Indexer.IssueQueueDir) + if !directlySet["DATADIR"] { + queueDir := filepath.ToSlash(Cfg.Section("indexer").Key("ISSUE_INDEXER_QUEUE_DIR").MustString("")) + if queueDir != "" { + _, _ = section.NewKey("DATADIR", queueDir) + } } - if !directlySet["CONN_STR"] && Indexer.IssueQueueConnStr != "" { - _, _ = section.NewKey("CONN_STR", Indexer.IssueQueueConnStr) + if !directlySet["CONN_STR"] { + connStr := Cfg.Section("indexer").Key("ISSUE_INDEXER_QUEUE_CONN_STR").MustString("") + if connStr != "" { + _, _ = section.NewKey("CONN_STR", connStr) + } } + // FIXME: DEPRECATED to be removed in v1.18.0 + // - will need to set default for [queue.*)] LENGTH appropriately though though + // Handle the old mailer configuration - handleOldLengthConfiguration("mailer", Cfg.Section("mailer").Key("SEND_BUFFER_LEN").MustInt(100)) + handleOldLengthConfiguration("mailer", "mailer", "SEND_BUFFER_LEN", 100) // Handle the old test pull requests configuration // Please note this will be a unique queue - handleOldLengthConfiguration("pr_patch_checker", Cfg.Section("repository").Key("PULL_REQUEST_QUEUE_LENGTH").MustInt(1000)) + handleOldLengthConfiguration("pr_patch_checker", "repository", "PULL_REQUEST_QUEUE_LENGTH", 1000) // Handle the old mirror queue configuration // Please note this will be a unique queue - handleOldLengthConfiguration("mirror", Cfg.Section("repository").Key("MIRROR_QUEUE_LENGTH").MustInt(1000)) + handleOldLengthConfiguration("mirror", "repository", "MIRROR_QUEUE_LENGTH", 1000) } // handleOldLengthConfiguration allows fallback to older configuration. `[queue.name]` `LENGTH` will override this configuration, but // if that is left unset then we should fallback to the older configuration. (Except where the new length woul be <=0) -func handleOldLengthConfiguration(queueName string, value int) { +func handleOldLengthConfiguration(queueName, oldSection, oldKey string, defaultValue int) { + if Cfg.Section(oldSection).HasKey(oldKey) { + log.Error("Deprecated fallback for %s queue length `[%s]` `%s` present. Use `[queue.%s]` `LENGTH`. This will be removed in v1.18.0", queueName, queueName, oldSection, oldKey) + } + value := Cfg.Section(oldSection).Key(oldKey).MustInt(defaultValue) + // Don't override with 0 if value <= 0 { return diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 26eeda525fc7..3c8e009daa3b 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -387,6 +387,7 @@ var ( MaxTokenLength: math.MaxInt16, } + // FIXME: DEPRECATED to be removed in v1.18.0 U2F = struct { AppID string }{} @@ -563,6 +564,12 @@ func LoadForTest(extraConfigs ...string) { } } +func deprecatedSetting(oldSection, oldKey, newSection, newKey string) { + if Cfg.Section(oldSection).HasKey(oldKey) { + log.Error("Deprecated fallback `[%s]` `%s` present. Use `[%s]` `%s` instead. This fallback will be removed in v1.18.0", oldSection, oldKey, newSection, newKey) + } +} + // loadFromConf initializes configuration context. // NOTE: do not print any log except error. func loadFromConf(allowEmpty bool, extraConfig string) { @@ -1022,6 +1029,10 @@ func loadFromConf(allowEmpty bool, extraConfig string) { UI.CustomEmojisMap[emoji] = ":" + emoji + ":" } + // FIXME: DEPRECATED to be removed in v1.18.0 + if Cfg.Section("U2F").HasKey("APP_ID") { + log.Error("Deprecated setting `[U2F]` `APP_ID` present. This fallback will be removed in v1.18.0") + } sec = Cfg.Section("U2F") U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimSuffix(AppURL, "/")) } diff --git a/modules/setting/task.go b/modules/setting/task.go index d9329dbb7608..c39d4411086e 100644 --- a/modules/setting/task.go +++ b/modules/setting/task.go @@ -4,14 +4,21 @@ package setting +// FIXME: DEPRECATED to be removed in v1.18.0 +// - will need to set default for [queue.task] LENGTH to 1000 though func newTaskService() { taskSec := Cfg.Section("task") queueTaskSec := Cfg.Section("queue.task") - switch taskSec.Key("QUEUE_TYPE").MustString(ChannelQueueType) { - case ChannelQueueType: + + deprecatedSetting("task", "QUEUE_TYPE", "queue.task", "TYPE") + deprecatedSetting("task", "QUEUE_CONN_STR", "queue.task", "CONN_STR") + deprecatedSetting("task", "QUEUE_LENGTH", "queue.task", "LENGTH") + + switch taskSec.Key("QUEUE_TYPE").MustString("channel") { + case "channel": queueTaskSec.Key("TYPE").MustString("persistable-channel") queueTaskSec.Key("CONN_STR").MustString(taskSec.Key("QUEUE_CONN_STR").MustString("")) - case RedisQueueType: + case "redis": queueTaskSec.Key("TYPE").MustString("redis") queueTaskSec.Key("CONN_STR").MustString(taskSec.Key("QUEUE_CONN_STR").MustString("addrs=127.0.0.1:6379 db=0")) } diff --git a/routers/web/auth/webauthn.go b/routers/web/auth/webauthn.go index b9e8de2ac0e0..77b1bee18a8b 100644 --- a/routers/web/auth/webauthn.go +++ b/routers/web/auth/webauthn.go @@ -67,6 +67,7 @@ func WebAuthnLoginAssertion(ctx *context.Context) { return } + // FIXME: DEPRECATED appid is deprecated and is planned to be removed in v1.18.0 assertion, sessionData, err := wa.WebAuthn.BeginLogin((*wa.User)(user), webauthn.WithAssertionExtensions(protocol.AuthenticationExtensions{ "appid": setting.U2F.AppID, })) From 54e9ee37a7a301dbe74d46fd3c87712e6120e9bf Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 20 Jan 2022 18:46:10 +0100 Subject: [PATCH 5/7] format with gofumpt (#18184) * gofumpt -w -l . * gofumpt -w -l -extra . * Add linter * manual fix * change make fmt --- .golangci.yml | 4 + Makefile | 6 +- build/code-batch-process.go | 2 +- build/codeformat/formatimports.go | 16 ++- build/generate-bindata.go | 5 +- build/generate-emoji.go | 12 +- build/generate-gitignores.go | 5 +- build/generate-licenses.go | 3 - build/gocovmerge.go | 2 +- cmd/admin.go | 10 +- cmd/admin_auth_ldap_test.go | 17 ++- cmd/cert.go | 2 +- cmd/doctor.go | 1 - cmd/dump.go | 2 +- cmd/dump_repo.go | 2 +- cmd/embedded.go | 13 +- cmd/manager.go | 3 +- cmd/serv.go | 2 +- cmd/web.go | 3 +- cmd/web_letsencrypt.go | 3 +- contrib/fixtures/fixture_generation.go | 2 +- contrib/pr/checkout.go | 35 +++--- integrations/api_admin_org_test.go | 6 +- integrations/api_branch_test.go | 1 - integrations/api_comment_test.go | 6 +- integrations/api_gpg_keys_test.go | 30 ++--- integrations/api_issue_label_test.go | 18 ++- integrations/api_issue_reaction_test.go | 20 ++-- integrations/api_issue_subscription_test.go | 1 - integrations/api_issue_test.go | 2 +- integrations/api_issue_tracked_time_test.go | 10 +- integrations/api_notification_test.go | 6 +- integrations/api_org_test.go | 8 +- integrations/api_private_serv_test.go | 2 - integrations/api_pull_review_test.go | 56 ++++----- integrations/api_repo_edit_test.go | 6 +- integrations/api_repo_git_commits_test.go | 1 - integrations/api_repo_lfs_locks_test.go | 14 +-- integrations/api_repo_test.go | 113 +++++++++++------- integrations/api_repo_topic_test.go | 1 - integrations/api_user_heatmap_test.go | 2 +- integrations/api_user_orgs_test.go | 2 +- integrations/attachment_test.go | 8 +- integrations/benchmarks_test.go | 2 +- integrations/cmd_keys_test.go | 7 +- integrations/dump_restore_test.go | 6 +- integrations/editor_test.go | 1 - integrations/eventsource_test.go | 2 +- .../git_helper_for_declarative_test.go | 11 +- integrations/git_smart_http_test.go | 2 +- integrations/git_test.go | 23 ++-- integrations/gpg_git_test.go | 4 +- integrations/integration_test.go | 18 +-- integrations/issue_test.go | 20 ++-- integrations/lfs_local_endpoint_test.go | 4 +- integrations/links_test.go | 10 +- integrations/migration-test/migration_test.go | 9 +- integrations/nonascii_branches_test.go | 1 - integrations/privateactivity_test.go | 6 +- integrations/pull_merge_test.go | 8 +- integrations/pull_update_test.go | 18 +-- integrations/repo_activity_test.go | 1 - integrations/repo_commits_test.go | 4 +- integrations/repofiles_update_test.go | 2 +- integrations/setting_test.go | 1 - integrations/ssh_key_test.go | 4 +- integrations/testlogger.go | 2 +- integrations/timetracking_test.go | 5 +- integrations/user_avatar_test.go | 2 +- integrations/user_test.go | 10 +- main.go | 2 +- models/auth/webauthn.go | 14 +-- models/avatars/avatar.go | 4 +- models/consistency.go | 1 - models/db/engine.go | 2 +- models/issue_test.go | 1 - models/issues/content_history.go | 1 - models/lfs.go | 2 +- models/migrate_test.go | 6 +- models/migrations/migrations_test.go | 8 +- models/migrations/testlogger_test.go | 2 +- models/migrations/v176_test.go | 1 - models/migrations/v177_test.go | 1 - models/migrations/v181_test.go | 2 +- models/migrations/v182_test.go | 4 +- models/migrations/v189_test.go | 2 - models/migrations/v191.go | 1 - models/migrations/v195_test.go | 4 +- models/migrations/v207.go | 1 - models/migrations/v208.go | 1 - models/repo.go | 8 +- models/repo/archiver.go | 4 +- models/repo/attachment.go | 2 +- models/repo/mirror.go | 6 +- models/repo/pushmirror.go | 6 +- models/review_test.go | 1 - models/unittest/testdb.go | 16 +-- models/user/email_address.go | 6 +- modules/activitypub/keypair_test.go | 1 - modules/appstate/db.go | 3 +- modules/auth/openid/discovery_cache_test.go | 4 +- modules/auth/openid/openid.go | 6 +- modules/auth/pam/pam.go | 1 - modules/auth/webauthn/webauthn.go | 14 +-- modules/avatar/avatar_test.go | 1 + modules/base/tool.go | 2 +- modules/cache/cache.go | 4 +- modules/cache/cache_test.go | 1 + modules/charset/charset.go | 2 +- modules/charset/charset_test.go | 96 ++++++++++----- modules/context/api.go | 21 ++-- modules/context/api_test.go | 2 +- modules/context/captcha.go | 6 +- modules/context/context.go | 14 +-- modules/context/csrf.go | 4 +- modules/context/private.go | 4 +- modules/context/repo.go | 1 - modules/context/response.go | 4 +- modules/convert/notification.go | 6 +- modules/convert/pull_test.go | 4 +- modules/convert/repository.go | 2 +- modules/convert/status.go | 1 - modules/csv/csv.go | 8 +- modules/csv/csv_test.go | 12 +- modules/doctor/fix16961.go | 1 - modules/doctor/misc.go | 1 - modules/doctor/paths.go | 2 +- modules/emoji/emoji.go | 3 - modules/git/command_test.go | 2 - modules/git/commit.go | 2 +- modules/git/commit_info_gogit.go | 2 +- modules/git/commit_info_nogogit.go | 2 +- modules/git/commit_info_test.go | 6 +- modules/git/commit_test.go | 1 - modules/git/git.go | 4 +- modules/git/hook.go | 8 +- modules/git/last_commit_cache_gogit.go | 1 - modules/git/lfs.go | 4 +- modules/git/parse_nogogit_test.go | 1 - modules/git/repo.go | 4 +- modules/git/repo_attribute.go | 2 +- modules/git/repo_attribute_test.go | 4 +- modules/git/repo_commit.go | 1 - modules/git/repo_commit_test.go | 6 +- modules/git/repo_language_stats.go | 6 +- modules/git/repo_object.go | 1 - modules/git/repo_tag.go | 2 +- modules/git/submodule_test.go | 2 +- modules/git/tag.go | 6 +- modules/git/tree_blob_gogit.go | 2 +- modules/git/tree_entry_mode.go | 10 +- modules/gitgraph/graph_test.go | 2 - modules/gitgraph/parser.go | 1 - modules/graceful/manager.go | 1 + modules/highlight/highlight.go | 6 +- modules/httpcache/httpcache_test.go | 3 +- modules/indexer/code/bleve.go | 12 +- modules/indexer/code/elastic_search.go | 10 +- modules/indexer/code/git.go | 2 +- modules/indexer/code/indexer.go | 4 +- modules/indexer/code/indexer_test.go | 78 ++++++------ modules/indexer/code/wrapped.go | 5 +- modules/indexer/issues/bleve.go | 6 +- modules/indexer/issues/bleve_test.go | 62 +++++----- modules/indexer/issues/db.go | 5 +- modules/indexer/issues/elastic_search.go | 8 +- modules/indexer/issues/indexer_test.go | 1 - modules/indexer/stats/db.go | 3 +- modules/lfs/endpoint_test.go | 2 +- modules/lfs/http_client_test.go | 7 +- modules/lfs/pointer_scanner_gogit.go | 1 - modules/log/colors.go | 11 +- modules/log/conn_test.go | 3 +- modules/log/file.go | 7 +- modules/log/file_test.go | 15 ++- modules/log/log_test.go | 1 - modules/log/logger.go | 1 - modules/log/stack.go | 4 +- modules/log/writer.go | 2 +- modules/markup/common/footnote.go | 11 +- modules/markup/common/html.go | 14 +-- modules/markup/common/linkify.go | 18 +-- modules/markup/csv/csv.go | 5 +- modules/markup/csv/csv_test.go | 2 +- modules/markup/html.go | 10 +- modules/markup/html_internal_test.go | 8 +- modules/markup/html_test.go | 32 ++--- modules/markup/markdown/goldmark.go | 2 +- modules/markup/markdown/markdown.go | 21 ++-- modules/markup/markdown/markdown_test.go | 9 +- modules/markup/mdstripper/mdstripper.go | 6 +- modules/markup/mdstripper/mdstripper_test.go | 3 +- modules/markup/orgmode/orgmode.go | 3 +- modules/markup/orgmode/orgmode_test.go | 8 +- modules/markup/sanitizer.go | 3 +- modules/markup/sanitizer_test.go | 1 - modules/metrics/collector.go | 1 - modules/migration/null_downloader.go | 7 +- modules/migration/retry_downloader.go | 4 +- modules/nosql/redis.go | 1 - modules/notification/action/action.go | 6 +- modules/notification/base/notifier.go | 14 +-- modules/notification/base/null.go | 9 +- modules/notification/indexer/indexer.go | 4 +- modules/notification/mail/mail.go | 4 +- modules/notification/notification.go | 6 +- modules/notification/ui/ui.go | 20 ++-- modules/notification/webhook/webhook.go | 7 +- modules/options/dynamic.go | 10 +- modules/options/static.go | 14 +-- modules/private/mail.go | 2 +- modules/private/manager.go | 1 - modules/private/restore_repo.go | 2 +- modules/private/serv.go | 1 - modules/process/manager.go | 1 - modules/process/manager_test.go | 2 - modules/public/public.go | 4 +- modules/public/public_test.go | 2 +- modules/public/static.go | 2 +- modules/queue/manager.go | 6 +- modules/queue/queue.go | 5 +- modules/queue/queue_bytefifo.go | 8 +- modules/queue/queue_disk_channel.go | 1 - modules/queue/queue_disk_channel_test.go | 1 - modules/queue/queue_wrapped.go | 2 +- modules/queue/unique_queue_disk_channel.go | 1 - modules/queue/workerpool.go | 2 +- modules/references/references.go | 1 - modules/references/references_test.go | 1 - modules/repository/generate.go | 4 +- modules/repository/hooks.go | 10 +- modules/repository/init.go | 6 +- modules/repository/repo.go | 4 +- modules/session/db.go | 1 - modules/setting/attachment.go | 34 +++--- modules/setting/cache.go | 50 ++++---- modules/setting/cors.go | 32 +++-- modules/setting/cron_test.go | 2 - modules/setting/database.go | 2 +- modules/setting/git.go | 110 +++++++++-------- modules/setting/indexer.go | 60 +++++----- modules/setting/indexer_test.go | 1 - modules/setting/lfs.go | 2 +- modules/setting/log.go | 10 +- modules/setting/mailer.go | 6 +- modules/setting/markup.go | 2 +- modules/setting/migrations.go | 26 ++-- modules/setting/mime_type_map.go | 18 ++- modules/setting/mirror.go | 30 +++-- modules/setting/proxy.go | 24 ++-- modules/setting/session.go | 52 ++++---- modules/setting/setting.go | 11 +- modules/setting/webhook.go | 40 +++---- modules/ssh/ssh.go | 5 +- modules/ssh/ssh_graceful.go | 1 - modules/storage/local.go | 4 +- modules/storage/minio.go | 4 +- modules/storage/storage.go | 6 +- modules/structs/hook.go | 6 +- modules/structs/repo.go | 24 ++-- modules/templates/base.go | 2 +- modules/templates/dynamic.go | 2 - modules/templates/helper.go | 16 +-- modules/templates/static.go | 6 +- modules/test/context_tests.go | 9 +- modules/timeutil/executable.go | 6 +- modules/timeutil/language.go | 12 +- modules/typesniffer/typesniffer.go | 6 +- modules/updatechecker/update_checker.go | 1 - modules/util/paginate_test.go | 2 +- modules/util/path_test.go | 2 +- modules/util/sanitize.go | 6 +- modules/util/sanitize_test.go | 6 +- modules/util/shellquote.go | 8 +- modules/util/truncate.go | 6 +- modules/util/util_test.go | 1 - modules/validation/binding.go | 11 +- modules/web/middleware/flash.go | 6 +- modules/web/middleware/locale.go | 2 +- modules/web/route.go | 34 +++--- modules/web/routing/context.go | 5 +- modules/web/routing/funcinfo.go | 8 +- modules/web/routing/logger_manager.go | 6 +- modules/web/wrap_convert.go | 2 +- routers/api/v1/admin/org.go | 2 +- routers/api/v1/admin/user.go | 2 +- routers/api/v1/api.go | 12 +- routers/api/v1/misc/markdown_test.go | 10 +- routers/api/v1/org/hook.go | 4 +- routers/api/v1/org/org.go | 4 +- routers/api/v1/repo/branch.go | 6 - routers/api/v1/repo/fork.go | 2 +- routers/api/v1/repo/issue.go | 2 +- routers/api/v1/repo/issue_reaction.go | 4 +- routers/api/v1/repo/issue_subscription.go | 4 +- routers/api/v1/repo/issue_tracked_time.go | 4 +- routers/api/v1/repo/migrate.go | 4 +- routers/api/v1/repo/milestone.go | 2 +- routers/api/v1/repo/pull.go | 1 - routers/api/v1/repo/release_attachment.go | 2 +- routers/api/v1/repo/repo.go | 6 +- routers/api/v1/repo/repo_test.go | 4 +- routers/api/v1/repo/status.go | 2 +- routers/api/v1/repo/wiki.go | 5 +- routers/api/v1/user/gpg_key.go | 10 +- routers/api/v1/user/watch.go | 1 - routers/api/v1/utils/git.go | 4 +- routers/common/middleware.go | 2 +- routers/install/install.go | 8 +- routers/install/routes.go | 4 +- routers/private/internal.go | 6 +- routers/private/manager_unix.go | 1 - routers/private/restore_repo.go | 2 +- routers/web/admin/admin.go | 2 +- routers/web/admin/admin_test.go | 2 +- routers/web/admin/emails.go | 5 +- routers/web/admin/users_test.go | 1 - routers/web/auth/auth.go | 6 +- routers/web/auth/linkaccount.go | 4 +- routers/web/auth/oauth.go | 1 - routers/web/auth/openid.go | 4 +- routers/web/auth/webauthn.go | 2 +- routers/web/base.go | 10 +- routers/web/explore/code.go | 4 +- routers/web/explore/user.go | 4 +- routers/web/org/home.go | 2 +- routers/web/org/members.go | 2 +- routers/web/org/setting.go | 3 +- routers/web/repo/attachment.go | 10 +- routers/web/repo/blame.go | 6 +- routers/web/repo/branch.go | 2 +- routers/web/repo/compare.go | 9 +- routers/web/repo/download.go | 2 +- routers/web/repo/editor_test.go | 2 +- routers/web/repo/http.go | 5 +- routers/web/repo/issue.go | 32 +++-- routers/web/repo/issue_content_history.go | 8 +- routers/web/repo/issue_lock.go | 1 - routers/web/repo/issue_test.go | 4 +- routers/web/repo/lfs.go | 4 +- routers/web/repo/migrate.go | 2 +- routers/web/repo/projects.go | 1 - routers/web/repo/pull.go | 23 ++-- routers/web/repo/release.go | 2 +- routers/web/repo/repo.go | 6 +- routers/web/repo/settings_test.go | 5 - routers/web/repo/topic.go | 4 +- routers/web/repo/view.go | 7 +- routers/web/repo/wiki.go | 8 +- routers/web/repo/wiki_test.go | 6 +- routers/web/user/home.go | 18 ++- routers/web/user/profile.go | 3 +- routers/web/user/setting/account_test.go | 6 +- routers/web/user/setting/keys.go | 1 - routers/web/user/setting/profile.go | 1 - routers/web/web.go | 9 +- services/auth/auth.go | 6 +- services/auth/auth_test.go | 1 - services/auth/basic.go | 3 +- services/auth/oauth2.go | 3 +- services/auth/reverseproxy.go | 3 +- services/auth/session.go | 3 +- services/auth/source/ldap/source_sync.go | 1 - services/auth/source/oauth2/jwtsigningkey.go | 2 +- services/auth/source/oauth2/providers.go | 6 +- .../auth/source/oauth2/providers_openid.go | 3 +- .../auth/source/oauth2/providers_simple.go | 1 - services/auth/source/oauth2/source_callout.go | 2 +- services/auth/source/smtp/auth.go | 6 +- services/comments/comments.go | 2 +- services/cron/cron.go | 1 - services/cron/tasks.go | 10 +- services/forms/repo_form_test.go | 2 - services/gitdiff/csv.go | 10 +- services/gitdiff/csv_test.go | 11 +- services/gitdiff/gitdiff.go | 20 ++-- services/gitdiff/gitdiff_test.go | 9 +- services/issue/issue.go | 4 +- services/issue/label_test.go | 4 +- services/lfs/locks.go | 6 +- services/lfs/server.go | 2 +- services/mailer/mail_issue.go | 1 - services/mailer/mail_test.go | 48 +++++--- services/mailer/mailer.go | 10 +- services/migrations/codebase.go | 12 +- services/migrations/dump.go | 12 +- services/migrations/error.go | 6 +- services/migrations/git.go | 4 +- services/migrations/gitbucket.go | 3 +- services/migrations/gitea_downloader.go | 21 ++-- services/migrations/gitea_uploader.go | 42 ++++--- services/migrations/github.go | 44 +++---- services/migrations/gitlab.go | 45 ++++--- services/migrations/gogs.go | 21 ++-- services/migrations/migrate.go | 12 +- services/migrations/onedev.go | 9 +- services/migrations/restore.go | 18 +-- services/mirror/mirror_pull.go | 4 +- services/pull/commit_status.go | 2 +- services/pull/merge.go | 4 +- services/pull/review.go | 1 - services/pull/temp_repo.go | 2 +- services/pull/update.go | 2 +- services/release/release.go | 4 +- services/release/release_test.go | 2 +- services/repository/adopt.go | 3 +- services/repository/adopt_test.go | 2 +- services/repository/archiver/archiver.go | 2 +- services/repository/archiver/archiver_test.go | 2 +- services/repository/push.go | 2 +- services/task/task.go | 2 +- services/webhook/deliver.go | 3 +- services/webhook/deliver_test.go | 2 +- services/webhook/dingtalk.go | 5 +- services/webhook/discord.go | 4 +- services/webhook/feishu.go | 6 +- services/webhook/matrix.go | 4 +- services/webhook/msteams.go | 4 +- services/webhook/slack.go | 4 +- services/webhook/telegram.go | 4 +- services/webhook/webhook.go | 70 ++++++----- services/webhook/wechatwork.go | 11 +- tools/fuzz.go | 18 ++- 423 files changed, 1586 insertions(+), 1759 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 235bb76715bd..9bba34a10cd7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,6 +17,7 @@ linters: - bidichk - ineffassign - revive + - gofumpt enable-all: false disable-all: true fast: false @@ -57,6 +58,9 @@ linters-settings: - name: errorf - name: duplicated-imports - name: modifies-value-receiver + gofumpt: + extra-rules: true + lang-version: 1.16 issues: exclude-rules: diff --git a/Makefile b/Makefile index 342366492c7b..d12f83d98b46 100644 --- a/Makefile +++ b/Makefile @@ -231,8 +231,10 @@ clean: .PHONY: fmt fmt: - @echo "Running gitea-fmt(with gofmt)..." - @$(GO) run build/code-batch-process.go gitea-fmt -s -w '{file-list}' + @hash xgogofumpt > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ + $(GO) install mvdan.cc/gofumpt@latest; \ + fi + gofumpt -w -l -extra -lang 1.16 . .PHONY: vet vet: diff --git a/build/code-batch-process.go b/build/code-batch-process.go index 1fd236abd586..02f54b9c0af2 100644 --- a/build/code-batch-process.go +++ b/build/code-batch-process.go @@ -136,7 +136,7 @@ func (fc *fileCollector) collectFiles() (res [][]string, err error) { } // substArgFiles expands the {file-list} to a real file list for commands -func substArgFiles(args []string, files []string) []string { +func substArgFiles(args, files []string) []string { for i, s := range args { if s == "{file-list}" { newArgs := append(args[:i], files...) diff --git a/build/codeformat/formatimports.go b/build/codeformat/formatimports.go index c6427f6a9985..fedc5cc0909c 100644 --- a/build/codeformat/formatimports.go +++ b/build/codeformat/formatimports.go @@ -20,8 +20,10 @@ var importPackageGroupOrders = map[string]int{ var errInvalidCommentBetweenImports = errors.New("comments between imported packages are invalid, please move comments to the end of the package line") -var importBlockBegin = []byte("\nimport (\n") -var importBlockEnd = []byte("\n)") +var ( + importBlockBegin = []byte("\nimport (\n") + importBlockEnd = []byte("\n)") +) type importLineParsed struct { group string @@ -59,8 +61,10 @@ func parseImportLine(line string) (*importLineParsed, error) { return il, nil } -type importLineGroup []*importLineParsed -type importLineGroupMap map[string]importLineGroup +type ( + importLineGroup []*importLineParsed + importLineGroupMap map[string]importLineGroup +) func formatGoImports(contentBytes []byte) ([]byte, error) { p1 := bytes.Index(contentBytes, importBlockBegin) @@ -153,7 +157,7 @@ func formatGoImports(contentBytes []byte) ([]byte, error) { return formattedBytes, nil } -//FormatGoImports format the imports by our rules (see unit tests) +// FormatGoImports format the imports by our rules (see unit tests) func FormatGoImports(file string) error { f, err := os.Open(file) if err != nil { @@ -177,7 +181,7 @@ func FormatGoImports(file string) error { if bytes.Equal(contentBytes, formattedBytes) { return nil } - f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0644) + f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0o644) if err != nil { return err } diff --git a/build/generate-bindata.go b/build/generate-bindata.go index 7941af60a162..7fdf9d761610 100644 --- a/build/generate-bindata.go +++ b/build/generate-bindata.go @@ -20,7 +20,7 @@ import ( "github.com/shurcooL/vfsgen" ) -func needsUpdate(dir string, filename string) (bool, []byte) { +func needsUpdate(dir, filename string) (bool, []byte) { needRegen := false _, err := os.Stat(filename) if err != nil { @@ -50,7 +50,6 @@ func needsUpdate(dir string, filename string) (bool, []byte) { newHash := hasher.Sum([]byte{}) if bytes.Compare(oldHash, newHash) != 0 { - return true, newHash } @@ -87,5 +86,5 @@ func main() { if err != nil { log.Fatalf("%v\n", err) } - _ = os.WriteFile(filename+".hash", newHash, 0666) + _ = os.WriteFile(filename+".hash", newHash, 0o666) } diff --git a/build/generate-emoji.go b/build/generate-emoji.go index aa56d45f7440..2f3536342d41 100644 --- a/build/generate-emoji.go +++ b/build/generate-emoji.go @@ -30,9 +30,7 @@ const ( maxUnicodeVersion = 12 ) -var ( - flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out") -) +var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out") // Gemoji is a set of emoji data. type Gemoji []Emoji @@ -68,7 +66,7 @@ func main() { } // write - err = os.WriteFile(*flagOut, buf, 0644) + err = os.WriteFile(*flagOut, buf, 0o644) if err != nil { log.Fatal(err) } @@ -109,7 +107,7 @@ func generate() ([]byte, error) { return nil, err } - var skinTones = make(map[string]string) + skinTones := make(map[string]string) skinTones["\U0001f3fb"] = "Light Skin Tone" skinTones["\U0001f3fc"] = "Medium-Light Skin Tone" @@ -119,7 +117,7 @@ func generate() ([]byte, error) { var tmp Gemoji - //filter out emoji that require greater than max unicode version + // filter out emoji that require greater than max unicode version for i := range data { val, _ := strconv.ParseFloat(data[i].UnicodeVersion, 64) if int(val) <= maxUnicodeVersion { @@ -158,7 +156,7 @@ func generate() ([]byte, error) { // write a JSON file to use with tribute (write before adding skin tones since we can't support them there yet) file, _ := json.Marshal(data) - _ = os.WriteFile("assets/emoji.json", file, 0644) + _ = os.WriteFile("assets/emoji.json", file, 0o644) // Add skin tones to emoji that support it var ( diff --git a/build/generate-gitignores.go b/build/generate-gitignores.go index 811953ee4a16..0f7d719d40b1 100644 --- a/build/generate-gitignores.go +++ b/build/generate-gitignores.go @@ -34,7 +34,6 @@ func main() { flag.Parse() file, err := os.CreateTemp(os.TempDir(), prefix) - if err != nil { log.Fatalf("Failed to create temp file. %s", err) } @@ -65,7 +64,6 @@ func main() { } gz, err := gzip.NewReader(file) - if err != nil { log.Fatalf("Failed to gunzip the archive. %s", err) } @@ -96,7 +94,6 @@ func main() { } out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore"))) - if err != nil { log.Fatalf("Failed to create new file. %s", err) } @@ -119,7 +116,7 @@ func main() { } // Write data to dst dst = path.Join(destination, dst) - err = os.WriteFile(dst, data, 0644) + err = os.WriteFile(dst, data, 0o644) if err != nil { log.Fatalf("Failed to write new file. %s", err) } diff --git a/build/generate-licenses.go b/build/generate-licenses.go index 75fb7cc8100a..0f9b9f369fec 100644 --- a/build/generate-licenses.go +++ b/build/generate-licenses.go @@ -34,7 +34,6 @@ func main() { flag.Parse() file, err := os.CreateTemp(os.TempDir(), prefix) - if err != nil { log.Fatalf("Failed to create temp file. %s", err) } @@ -66,7 +65,6 @@ func main() { } gz, err := gzip.NewReader(file) - if err != nil { log.Fatalf("Failed to gunzip the archive. %s", err) } @@ -100,7 +98,6 @@ func main() { continue } out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".txt"))) - if err != nil { log.Fatalf("Failed to create new file. %s", err) } diff --git a/build/gocovmerge.go b/build/gocovmerge.go index 6a1af5b58f79..1d2652129f9f 100644 --- a/build/gocovmerge.go +++ b/build/gocovmerge.go @@ -22,7 +22,7 @@ import ( "golang.org/x/tools/cover" ) -func mergeProfiles(p *cover.Profile, merge *cover.Profile) { +func mergeProfiles(p, merge *cover.Profile) { if p.Mode != merge.Mode { log.Fatalf("cannot merge profiles with different modes") } diff --git a/cmd/admin.go b/cmd/admin.go index 3042df8bb771..66c7959ab398 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -525,7 +525,7 @@ func runCreateUser(c *cli.Context) error { } // always default to true - var changePassword = true + changePassword := true // If this is the first user being created. // Take it as the admin and don't force a password update. @@ -577,7 +577,6 @@ func runListUsers(c *cli.Context) error { } users, err := user_model.GetAllUsers() - if err != nil { return err } @@ -601,7 +600,6 @@ func runListUsers(c *cli.Context) error { w.Flush() return nil - } func runDeleteUser(c *cli.Context) error { @@ -826,7 +824,6 @@ func runUpdateOauth(c *cli.Context) error { if c.IsSet("required-claim-name") { oAuth2Config.RequiredClaimName = c.String("required-claim-name") - } if c.IsSet("required-claim-value") { oAuth2Config.RequiredClaimValue = c.String("required-claim-value") @@ -843,7 +840,7 @@ func runUpdateOauth(c *cli.Context) error { } // update custom URL mapping - var customURLMapping = &oauth2.CustomURLMapping{} + customURLMapping := &oauth2.CustomURLMapping{} if oAuth2Config.CustomURLMapping != nil { customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL @@ -926,7 +923,7 @@ func runAddSMTP(c *cli.Context) error { if !c.IsSet("port") { return errors.New("port must be set") } - var active = true + active := true if c.IsSet("active") { active = c.BoolT("active") } @@ -994,7 +991,6 @@ func runListAuth(c *cli.Context) error { } authSources, err := auth.Sources() - if err != nil { return err } diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go index e1cd1c3244eb..f050b536fdf5 100644 --- a/cmd/admin_auth_ldap_test.go +++ b/cmd/admin_auth_ldap_test.go @@ -17,12 +17,12 @@ import ( func TestAddLdapBindDn(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string source *auth.Source errMsg string @@ -243,12 +243,12 @@ func TestAddLdapBindDn(t *testing.T) { func TestAddLdapSimpleAuth(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string authSource *auth.Source errMsg string @@ -474,12 +474,12 @@ func TestAddLdapSimpleAuth(t *testing.T) { func TestUpdateLdapBindDn(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string id int64 existingAuthSource *auth.Source @@ -907,12 +907,12 @@ func TestUpdateLdapBindDn(t *testing.T) { func TestUpdateLdapSimpleAuth(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string id int64 existingAuthSource *auth.Source @@ -1161,7 +1161,6 @@ func TestUpdateLdapSimpleAuth(t *testing.T) { authSource: &auth.Source{ Type: auth.DLDAP, Cfg: &ldap.Source{ - AttributeMail: "mail", }, }, diff --git a/cmd/cert.go b/cmd/cert.go index b62319f80854..162c4171bfb2 100644 --- a/cmd/cert.go +++ b/cmd/cert.go @@ -180,7 +180,7 @@ func runCert(c *cli.Context) error { } log.Println("Written cert.pem") - keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { log.Fatalf("Failed to open key.pem for writing: %v", err) } diff --git a/cmd/doctor.go b/cmd/doctor.go index 35cc305f4c2d..10f62f32c16b 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -121,7 +121,6 @@ func runRecreateTable(ctx *cli.Context) error { } return recreateTables(x) }) - } func runDoctor(ctx *cli.Context) error { diff --git a/cmd/dump.go b/cmd/dump.go index d6a5230060c5..418042559874 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -370,7 +370,7 @@ func runDump(ctx *cli.Context) error { fatal("Failed to save %s: %v", fileName, err) } - if err := os.Chmod(fileName, 0600); err != nil { + if err := os.Chmod(fileName, 0o600); err != nil { log.Info("Can't change file access permissions mask to 0600: %v", err) } } diff --git a/cmd/dump_repo.go b/cmd/dump_repo.go index 1a9344dbe18f..e980af30110a 100644 --- a/cmd/dump_repo.go +++ b/cmd/dump_repo.go @@ -107,7 +107,7 @@ func runDumpRepository(ctx *cli.Context) error { } serviceType = convert.ToGitServiceType(serviceStr) - var opts = base.MigrateOptions{ + opts := base.MigrateOptions{ GitServiceType: serviceType, CloneAddr: cloneAddr, AuthUsername: ctx.String("auth_username"), diff --git a/cmd/embedded.go b/cmd/embedded.go index c608667bf85a..2930e5d3077d 100644 --- a/cmd/embedded.go +++ b/cmd/embedded.go @@ -109,7 +109,6 @@ type asset struct { } func initEmbeddedExtractor(c *cli.Context) error { - // Silence the console logger log.DelNamedLogger("console") log.DelNamedLogger(log.DEFAULT) @@ -260,7 +259,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error { return fmt.Errorf("%s: %v", dir, err) } - perms := os.ModePerm & 0666 + perms := os.ModePerm & 0o666 fi, err := os.Lstat(dest) if err != nil { @@ -296,7 +295,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error { } func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset { - var results = make([]asset, 0, 64) + results := make([]asset, 0, 64) for _, name := range sec.Names() { if isdir, err := sec.IsDir(name); !isdir && err == nil { if sec.Path == "public" && @@ -307,9 +306,11 @@ func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset { matchName := sec.Path + "/" + name for _, g := range globs { if g.Match(matchName) { - results = append(results, asset{Section: sec, - Name: name, - Path: sec.Path + "/" + name}) + results = append(results, asset{ + Section: sec, + Name: name, + Path: sec.Path + "/" + name, + }) break } } diff --git a/cmd/manager.go b/cmd/manager.go index 99d283b4418e..50b66cc7f230 100644 --- a/cmd/manager.go +++ b/cmd/manager.go @@ -58,7 +58,8 @@ var ( Name: "timeout", Value: 60 * time.Second, Usage: "Timeout for the flushing process", - }, cli.BoolFlag{ + }, + cli.BoolFlag{ Name: "non-blocking", Usage: "Set to true to not wait for flush to complete before returning", }, diff --git a/cmd/serv.go b/cmd/serv.go index ab60358b53e0..e42213cb9854 100644 --- a/cmd/serv.go +++ b/cmd/serv.go @@ -247,7 +247,7 @@ func runServ(c *cli.Context) error { os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID)) os.Setenv(models.EnvAppURL, setting.AppURL) - //LFS token authentication + // LFS token authentication if verb == lfsAuthenticateVerb { url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName)) diff --git a/cmd/web.go b/cmd/web.go index ec92ef242abe..9a8d9dfa73c8 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -71,8 +71,7 @@ func runHTTPRedirector() { http.Redirect(w, r, target, http.StatusTemporaryRedirect) }) - var err = runHTTP("tcp", source, "HTTP Redirector", handler) - + err := runHTTP("tcp", source, "HTTP Redirector", handler) if err != nil { log.Fatal("Failed to start port redirection: %v", err) } diff --git a/cmd/web_letsencrypt.go b/cmd/web_letsencrypt.go index 866b88f7c9d5..517d71f0172c 100644 --- a/cmd/web_letsencrypt.go +++ b/cmd/web_letsencrypt.go @@ -17,7 +17,6 @@ import ( ) func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error { - // If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443. // Due to docker port mapping this can't be checked programmatically // TODO: these are placeholders until we add options for each in settings with appropriate warning @@ -77,7 +76,7 @@ func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) go func() { log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect) // all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here) - var err = runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler))) + err := runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler))) if err != nil { log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err) } diff --git a/contrib/fixtures/fixture_generation.go b/contrib/fixtures/fixture_generation.go index 74996a1f3599..66ff5c54e31b 100644 --- a/contrib/fixtures/fixture_generation.go +++ b/contrib/fixtures/fixture_generation.go @@ -66,7 +66,7 @@ func generate(name string) error { return err } path := filepath.Join(fixturesDir, name+".yml") - if err := os.WriteFile(path, []byte(data), 0644); err != nil { + if err := os.WriteFile(path, []byte(data), 0o644); err != nil { return fmt.Errorf("%s: %+v", path, err) } fmt.Printf("%s created.\n", path) diff --git a/contrib/pr/checkout.go b/contrib/pr/checkout.go index e9dd675d4dac..ceeba4de3b58 100644 --- a/contrib/pr/checkout.go +++ b/contrib/pr/checkout.go @@ -93,13 +93,13 @@ func runPR() { routers.InitGitServices() setting.Database.LogSQL = true - //x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared") + // x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared") db.InitEngineWithMigration(context.Background(), func(_ *xorm.Engine) error { return nil }) db.HasEngine = true - //x.ShowSQL(true) + // x.ShowSQL(true) err = unittest.InitFixtures( unittest.FixturesOptions{ Dir: path.Join(curDir, "models/fixtures/"), @@ -115,7 +115,7 @@ func runPR() { util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath) log.Printf("[PR] Setting up router\n") - //routers.GlobalInit() + // routers.GlobalInit() external.RegisterRenderers() markup.Init() c := routers.NormalRoutes() @@ -137,7 +137,7 @@ func runPR() { } */ - //Start the server + // Start the server http.ListenAndServe(":8080", c) log.Printf("[PR] Cleaning up ...\n") @@ -160,7 +160,7 @@ func runPR() { } func main() { - var runPRFlag = flag.Bool("run", false, "Run the PR code") + runPRFlag := flag.Bool("run", false, "Run the PR code") flag.Parse() if *runPRFlag { runPR() @@ -173,15 +173,15 @@ func main() { force = false } - //Otherwise checkout PR + // Otherwise checkout PR if len(os.Args) != 2 { log.Fatal("Need only one arg: the PR number") } pr := os.Args[1] - codeFilePath = filepath.FromSlash(codeFilePath) //Convert to running OS + codeFilePath = filepath.FromSlash(codeFilePath) // Convert to running OS - //Copy this file if it will not exist in the PR branch + // Copy this file if it will not exist in the PR branch dat, err := os.ReadFile(codeFilePath) if err != nil { log.Fatalf("Failed to cache this code file : %v", err) @@ -192,16 +192,16 @@ func main() { log.Fatalf("Failed to open the repo : %v", err) } - //Find remote upstream + // Find remote upstream remotes, err := repo.Remotes() if err != nil { log.Fatalf("Failed to list remotes of repo : %v", err) } - remoteUpstream := "origin" //Default + remoteUpstream := "origin" // Default for _, r := range remotes { if r.Config().URLs[0] == "https://github.com/go-gitea/gitea.git" || r.Config().URLs[0] == "https://github.com/go-gitea/gitea" || - r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { //fetch at index 0 + r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { // fetch at index 0 remoteUpstream = r.Config().Name break } @@ -212,7 +212,7 @@ func main() { log.Printf("Fetching PR #%s in %s\n", pr, branch) if runtime.GOOS == "windows" { - //Use git cli command for windows + // Use git cli command for windows runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch)) } else { ref := fmt.Sprintf("%s%s/head:%s", gitea_git.PullPrefix, pr, branchRef) @@ -240,22 +240,23 @@ func main() { log.Fatalf("Failed to checkout %s : %v", branch, err) } - //Copy this file if not exist + // Copy this file if not exist if _, err := os.Stat(codeFilePath); os.IsNotExist(err) { - err = os.MkdirAll(filepath.Dir(codeFilePath), 0755) + err = os.MkdirAll(filepath.Dir(codeFilePath), 0o755) if err != nil { log.Fatalf("Failed to duplicate this code file in PR : %v", err) } - err = os.WriteFile(codeFilePath, dat, 0644) + err = os.WriteFile(codeFilePath, dat, 0o644) if err != nil { log.Fatalf("Failed to duplicate this code file in PR : %v", err) } } - //Force build of js, css, bin, ... + // Force build of js, css, bin, ... runCmd("make", "build") - //Start with integration test + // Start with integration test runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run") } + func runCmd(cmd ...string) { log.Printf("Executing : %s ...\n", cmd) c := exec.Command(cmd[0], cmd[1:]...) diff --git a/integrations/api_admin_org_test.go b/integrations/api_admin_org_test.go index 4b5e2481e65d..8f36850a1a14 100644 --- a/integrations/api_admin_org_test.go +++ b/integrations/api_admin_org_test.go @@ -22,7 +22,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", Description: "This organization created by admin for user2", @@ -56,7 +56,7 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", Description: "This organization created by admin for user2", @@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", Description: "This organization created by admin for user2", diff --git a/integrations/api_branch_test.go b/integrations/api_branch_test.go index d898266afee4..54fe4a6edaec 100644 --- a/integrations/api_branch_test.go +++ b/integrations/api_branch_test.go @@ -106,7 +106,6 @@ func TestAPICreateBranch(t *testing.T) { } func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { - username := "user2" ctx := NewAPITestContext(t, username, "my-noo-repo") giteaURL.Path = ctx.GitPath() diff --git a/integrations/api_comment_test.go b/integrations/api_comment_test.go index 4c4c6308eeab..dde51b2d5321 100644 --- a/integrations/api_comment_test.go +++ b/integrations/api_comment_test.go @@ -44,10 +44,10 @@ func TestAPIListRepoComments(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID}) } - //test before and since filters + // test before and since filters query := url.Values{} - before := "2000-01-01T00:00:11+00:00" //unix: 946684811 - since := "2000-01-01T00:00:12+00:00" //unix: 946684812 + before := "2000-01-01T00:00:11+00:00" // unix: 946684811 + since := "2000-01-01T00:00:12+00:00" // unix: 946684812 query.Add("before", before) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) diff --git a/integrations/api_gpg_keys_test.go b/integrations/api_gpg_keys_test.go index 8fc4124a4898..38341aecff7f 100644 --- a/integrations/api_gpg_keys_test.go +++ b/integrations/api_gpg_keys_test.go @@ -28,15 +28,18 @@ func TestGPGKeys(t *testing.T) { token string results []int }{ - {name: "NoLogin", makeRequest: MakeRequest, token: "", + { + name: "NoLogin", makeRequest: MakeRequest, token: "", results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, }, - {name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, - results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}}, + { + name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, + results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}, + }, } for _, tc := range tt { - //Basic test on result code + // Basic test on result code t.Run(tc.name, func(t *testing.T) { t.Run("ViewOwnGPGKeys", func(t *testing.T) { testViewOwnGPGKeys(t, tc.makeRequest, tc.token, tc.results[0]) @@ -66,28 +69,27 @@ func TestGPGKeys(t *testing.T) { }) } - //Check state after basic add + // Check state after basic add t.Run("CheckState", func(t *testing.T) { - var keys []*api.GPGKey - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) //GET all keys + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) // GET all keys resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) assert.Len(t, keys, 1) - primaryKey1 := keys[0] //Primary key 1 + primaryKey1 := keys[0] // Primary key 1 assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID) assert.Len(t, primaryKey1.Emails, 1) assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email) assert.True(t, primaryKey1.Emails[0].Verified) - subKey := primaryKey1.SubsKey[0] //Subkey of 38EA3BCED732982C + subKey := primaryKey1.SubsKey[0] // Subkey of 38EA3BCED732982C assert.EqualValues(t, "70D7C694D17D03AD", subKey.KeyID) assert.Empty(t, subKey.Emails) var key api.GPGKey - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) //Primary key 1 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) // Primary key 1 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID) @@ -95,14 +97,14 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.True(t, key.Emails[0].Verified) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) //Subkey of 38EA3BCED732982C + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) // Subkey of 38EA3BCED732982C resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) assert.Empty(t, key.Emails) }) - //Check state after basic add + // Check state after basic add t.Run("CheckCommits", func(t *testing.T) { t.Run("NotSigned", func(t *testing.T) { var branch api.Branch @@ -182,7 +184,7 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz } func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - //User2 //primary & activated + // User2 //primary & activated testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW @@ -216,7 +218,7 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h } func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - //User2 //secondary and not activated + // User2 //secondary and not activated testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQGNBGC2K2cBDAC1+Xgk+8UfhASVgRngQi4rnQ8k0t+bWsBz4Czd26+cxVDRwlTT diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go index 42bfedf32ff8..94b487377ece 100644 --- a/integrations/api_issue_label_test.go +++ b/integrations/api_issue_label_test.go @@ -53,21 +53,21 @@ func TestAPIModifyLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //ListLabels + // ListLabels req = NewRequest(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 2) - //GetLabel + // GetLabel singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d?token=%s", owner.Name, repo.Name, dbLabel.ID, token) req = NewRequest(t, "GET", singleURLStr) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) - //EditLabel + // EditLabel newName := "LabelNewName" newColor := "09876a" newColorWrong := "09g76a" @@ -83,10 +83,9 @@ func TestAPIModifyLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //DeleteLabel + // DeleteLabel req = NewRequest(t, "DELETE", singleURLStr) session.MakeRequest(t, req, http.StatusNoContent) - } func TestAPIAddIssueLabels(t *testing.T) { @@ -173,21 +172,21 @@ func TestAPIModifyOrgLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //ListLabels + // ListLabels req = NewRequest(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 4) - //GetLabel + // GetLabel singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token) req = NewRequest(t, "GET", singleURLStr) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) - //EditLabel + // EditLabel newName := "LabelNewName" newColor := "09876a" newColorWrong := "09g76a" @@ -203,8 +202,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //DeleteLabel + // DeleteLabel req = NewRequest(t, "DELETE", singleURLStr) session.MakeRequest(t, req, http.StatusNoContent) - } diff --git a/integrations/api_issue_reaction_test.go b/integrations/api_issue_reaction_test.go index fa0f016ef2cd..aa6f46f8bd0c 100644 --- a/integrations/api_issue_reaction_test.go +++ b/integrations/api_issue_reaction_test.go @@ -33,19 +33,19 @@ func TestAPIIssuesReactions(t *testing.T) { urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) - //Try to add not allowed reaction + // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", }) session.MakeRequest(t, req, http.StatusForbidden) - //Delete not allowed reaction + // Delete not allowed reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "zzz", }) session.MakeRequest(t, req, http.StatusOK) - //Add allowed reaction + // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "rocket", }) @@ -53,10 +53,10 @@ func TestAPIIssuesReactions(t *testing.T) { var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) - //Add existing reaction + // Add existing reaction session.MakeRequest(t, req, http.StatusForbidden) - //Get end result of reaction list of issue #1 + // Get end result of reaction list of issue #1 req = NewRequestf(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction @@ -93,19 +93,19 @@ func TestAPICommentReactions(t *testing.T) { urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", owner.Name, issue.Repo.Name, comment.ID, token) - //Try to add not allowed reaction + // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", }) session.MakeRequest(t, req, http.StatusForbidden) - //Delete none existing reaction + // Delete none existing reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "eyes", }) session.MakeRequest(t, req, http.StatusOK) - //Add allowed reaction + // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "+1", }) @@ -113,10 +113,10 @@ func TestAPICommentReactions(t *testing.T) { var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) - //Add existing reaction + // Add existing reaction session.MakeRequest(t, req, http.StatusForbidden) - //Get end result of reaction list of issue #1 + // Get end result of reaction list of issue #1 req = NewRequestf(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction diff --git a/integrations/api_issue_subscription_test.go b/integrations/api_issue_subscription_test.go index dfc3edee8d74..e0bb388365a5 100644 --- a/integrations/api_issue_subscription_test.go +++ b/integrations/api_issue_subscription_test.go @@ -33,7 +33,6 @@ func TestAPIIssueSubscriptions(t *testing.T) { token := getTokenForLoggedInUser(t, session) testSubscription := func(issue *models.Issue, isWatching bool) { - issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token) diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go index 0912d1d82bfe..3957c102339d 100644 --- a/integrations/api_issue_test.go +++ b/integrations/api_issue_test.go @@ -210,7 +210,7 @@ func TestAPISearchIssues(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.EqualValues(t, "15", resp.Header().Get("X-Total-Count")) - assert.Len(t, apiIssues, 10) //there are more but 10 is page item limit + assert.Len(t, apiIssues, 10) // there are more but 10 is page item limit query.Add("limit", "20") link.RawQuery = query.Encode() diff --git a/integrations/api_issue_tracked_time_test.go b/integrations/api_issue_tracked_time_test.go index 94e569113c16..335fd2929a1f 100644 --- a/integrations/api_issue_tracked_time_test.go +++ b/integrations/api_issue_tracked_time_test.go @@ -48,8 +48,8 @@ func TestAPIGetTrackedTimes(t *testing.T) { } // test filter - since := "2000-01-01T00%3A00%3A02%2B00%3A00" //946684802 - before := "2000-01-01T00%3A00%3A12%2B00%3A00" //946684812 + since := "2000-01-01T00%3A00%3A02%2B00%3A00" // 946684802 + before := "2000-01-01T00%3A00%3A12%2B00%3A00" // 946684812 req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s&token=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before, token) resp = session.MakeRequest(t, req, http.StatusOK) @@ -71,17 +71,17 @@ func TestAPIDeleteTrackedTime(t *testing.T) { session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session) - //Deletion not allowed + // Deletion not allowed req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) session.MakeRequest(t, req, http.StatusForbidden) time3 := unittest.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime) req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token) session.MakeRequest(t, req, http.StatusNoContent) - //Delete non existing time + // Delete non existing time session.MakeRequest(t, req, http.StatusNotFound) - //Reset time of user 2 on issue 2 + // Reset time of user 2 on issue 2 trackedSeconds, err := models.GetTrackedSeconds(models.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) assert.NoError(t, err) assert.Equal(t, int64(3661), trackedSeconds) diff --git a/integrations/api_notification_test.go b/integrations/api_notification_test.go index 12b3bac42569..4bf18632ca07 100644 --- a/integrations/api_notification_test.go +++ b/integrations/api_notification_test.go @@ -30,7 +30,7 @@ func TestAPINotification(t *testing.T) { // -- GET /notifications -- // test filter - since := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 + since := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s&token=%s", since, token)) resp := session.MakeRequest(t, req, http.StatusOK) var apiNL []api.NotificationThread @@ -40,7 +40,7 @@ func TestAPINotification(t *testing.T) { assert.EqualValues(t, 5, apiNL[0].ID) // test filter - before := "2000-01-01T01%3A06%3A59%2B00%3A00" //946688819 + before := "2000-01-01T01%3A06%3A59%2B00%3A00" // 946688819 req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s&token=%s", "true", before, token)) resp = session.MakeRequest(t, req, http.StatusOK) @@ -113,7 +113,7 @@ func TestAPINotification(t *testing.T) { DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) - lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 <- only Notification 4 is in this filter ... + lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) session.MakeRequest(t, req, http.StatusResetContent) diff --git a/integrations/api_org_test.go b/integrations/api_org_test.go index 76979c674dc2..e33c010e88c2 100644 --- a/integrations/api_org_test.go +++ b/integrations/api_org_test.go @@ -23,7 +23,7 @@ func TestAPIOrgCreate(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user1_org", FullName: "User1's organization", Description: "This organization created by user1", @@ -80,7 +80,7 @@ func TestAPIOrgEdit(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.EditOrgOption{ + org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", Website: "https://try.gitea.io/new", @@ -107,7 +107,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.EditOrgOption{ + org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", Website: "https://try.gitea.io/new", @@ -126,7 +126,7 @@ func TestAPIOrgDeny(t *testing.T) { setting.Service.RequireSignInView = false }() - var orgName = "user1_org" + orgName := "user1_org" req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName) MakeRequest(t, req, http.StatusNotFound) diff --git a/integrations/api_private_serv_test.go b/integrations/api_private_serv_test.go index 68308bafc5a6..a58d927cb91c 100644 --- a/integrations/api_private_serv_test.go +++ b/integrations/api_private_serv_test.go @@ -150,7 +150,5 @@ func TestAPIPrivateServ(t *testing.T) { assert.Equal(t, "user15", results.OwnerName) assert.Equal(t, "big_test_private_2", results.RepoName) assert.Equal(t, int64(20), results.RepoID) - }) - } diff --git a/integrations/api_pull_review_test.go b/integrations/api_pull_review_test.go index df6dc75d5174..3f80dbdf9b37 100644 --- a/integrations/api_pull_review_test.go +++ b/integrations/api_pull_review_test.go @@ -80,22 +80,23 @@ func TestAPIPullReview(t *testing.T) { req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ Body: "body1", // Event: "" # will result in PENDING - Comments: []api.CreatePullReviewComment{{ - Path: "README.md", - Body: "first new line", - OldLineNum: 0, - NewLineNum: 1, - }, { - Path: "README.md", - Body: "first old line", - OldLineNum: 1, - NewLineNum: 0, - }, { - Path: "iso-8859-1.txt", - Body: "this line contains a non-utf-8 character", - OldLineNum: 0, - NewLineNum: 1, - }, + Comments: []api.CreatePullReviewComment{ + { + Path: "README.md", + Body: "first new line", + OldLineNum: 0, + NewLineNum: 1, + }, { + Path: "README.md", + Body: "first old line", + OldLineNum: 1, + NewLineNum: 0, + }, { + Path: "iso-8859-1.txt", + Body: "this line contains a non-utf-8 character", + OldLineNum: 0, + NewLineNum: 1, + }, }, }) resp = session.MakeRequest(t, req, http.StatusOK) @@ -147,17 +148,18 @@ func TestAPIPullReview(t *testing.T) { req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ // Body: "", Event: "COMMENT", - Comments: []api.CreatePullReviewComment{{ - Path: "README.md", - Body: "first new line", - OldLineNum: 0, - NewLineNum: 1, - }, { - Path: "README.md", - Body: "first old line", - OldLineNum: 1, - NewLineNum: 0, - }, + Comments: []api.CreatePullReviewComment{ + { + Path: "README.md", + Body: "first new line", + OldLineNum: 0, + NewLineNum: 1, + }, { + Path: "README.md", + Body: "first old line", + OldLineNum: 1, + NewLineNum: 0, + }, }, }) var commentReview api.PullReview diff --git a/integrations/api_repo_edit_test.go b/integrations/api_repo_edit_test.go index 91ec4c699e58..f3f0139d9538 100644 --- a/integrations/api_repo_edit_test.go +++ b/integrations/api_repo_edit_test.go @@ -175,7 +175,7 @@ func TestAPIRepoEdit(t *testing.T) { assert.Equal(t, *repoEditOption.Private, *repo1editedOption.Private) assert.Equal(t, *repoEditOption.HasWiki, *repo1editedOption.HasWiki) - //Test editing repo1 to use internal issue and wiki (default) + // Test editing repo1 to use internal issue and wiki (default) *repoEditOption.HasIssues = true repoEditOption.ExternalTracker = nil repoEditOption.InternalTracker = &api.InternalTracker{ @@ -199,7 +199,7 @@ func TestAPIRepoEdit(t *testing.T) { assert.Equal(t, *repo1editedOption.HasWiki, true) assert.Nil(t, repo1editedOption.ExternalWiki) - //Test editing repo1 to use external issue and wiki + // Test editing repo1 to use external issue and wiki repoEditOption.ExternalTracker = &api.ExternalTracker{ ExternalTrackerURL: "http://www.somewebsite.com", ExternalTrackerFormat: "http://www.somewebsite.com/{user}/{repo}?issue={index}", @@ -233,7 +233,7 @@ func TestAPIRepoEdit(t *testing.T) { req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //Test small repo change through API with issue and wiki option not set; They shall not be touched. + // Test small repo change through API with issue and wiki option not set; They shall not be touched. *repoEditOption.Description = "small change" repoEditOption.HasIssues = nil repoEditOption.ExternalTracker = nil diff --git a/integrations/api_repo_git_commits_test.go b/integrations/api_repo_git_commits_test.go index 2099d568f769..f5a64490b9ed 100644 --- a/integrations/api_repo_git_commits_test.go +++ b/integrations/api_repo_git_commits_test.go @@ -130,7 +130,6 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) { assert.EqualValues(t, "From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 \nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n", resp.Body.String()) - } func TestGetFileHistory(t *testing.T) { diff --git a/integrations/api_repo_lfs_locks_test.go b/integrations/api_repo_lfs_locks_test.go index 3e0b40f5116c..ca7bd35001e5 100644 --- a/integrations/api_repo_lfs_locks_test.go +++ b/integrations/api_repo_lfs_locks_test.go @@ -53,8 +53,8 @@ func TestAPILFSLocksNotLogin(t *testing.T) { func TestAPILFSLocksLogged(t *testing.T) { defer prepareTestEnv(t)() setting.LFS.StartServer = true - user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) //in org 3 - user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) //in org 3 + user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // in org 3 + user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // in org 3 repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // own by org 3 @@ -101,7 +101,7 @@ func TestAPILFSLocksLogged(t *testing.T) { lockID string }{} - //create locks + // create locks for _, test := range tests { session := loginUser(t, test.user.Name) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks", test.repo.FullName()), map[string]string{"path": test.path}) @@ -111,14 +111,14 @@ func TestAPILFSLocksLogged(t *testing.T) { if len(test.addTime) > 0 { var lfsLock api.LFSLockResponse DecodeJSON(t, resp, &lfsLock) - assert.EqualValues(t, lfsLock.Lock.LockedAt.Format(time.RFC3339), lfsLock.Lock.LockedAt.Format(time.RFC3339Nano)) //locked at should be rounded to second + assert.EqualValues(t, lfsLock.Lock.LockedAt.Format(time.RFC3339), lfsLock.Lock.LockedAt.Format(time.RFC3339Nano)) // locked at should be rounded to second for _, id := range test.addTime { resultsTests[id].locksTimes = append(resultsTests[id].locksTimes, time.Now()) } } } - //check creation + // check creation for _, test := range resultsTests { session := loginUser(t, test.user.Name) req := NewRequestf(t, "GET", "/%s.git/info/lfs/locks", test.repo.FullName()) @@ -130,7 +130,7 @@ func TestAPILFSLocksLogged(t *testing.T) { for i, lock := range lfsLocks.Locks { assert.EqualValues(t, test.locksOwners[i].DisplayName(), lock.Owner.Name) assert.WithinDuration(t, test.locksTimes[i], lock.LockedAt, 10*time.Second) - assert.EqualValues(t, lock.LockedAt.Format(time.RFC3339), lock.LockedAt.Format(time.RFC3339Nano)) //locked at should be rounded to second + assert.EqualValues(t, lock.LockedAt.Format(time.RFC3339), lock.LockedAt.Format(time.RFC3339Nano)) // locked at should be rounded to second } req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/verify", test.repo.FullName()), map[string]string{}) @@ -154,7 +154,7 @@ func TestAPILFSLocksLogged(t *testing.T) { } } - //remove all locks + // remove all locks for _, test := range deleteTests { session := loginUser(t, test.user.Name) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/%s/unlock", test.repo.FullName(), test.lockID), map[string]string{}) diff --git a/integrations/api_repo_test.go b/integrations/api_repo_test.go index c909e96f06c5..52764a3a6909 100644 --- a/integrations/api_repo_test.go +++ b/integrations/api_repo_test.go @@ -79,76 +79,99 @@ func TestAPISearchRepo(t *testing.T) { name, requestURL string expectedResults }{ - {name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{ - nil: {count: 30}, - user: {count: 30}, - user2: {count: 30}}, + { + name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{ + nil: {count: 30}, + user: {count: 30}, + user2: {count: 30}, + }, }, - {name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{ - nil: {count: 10}, - user: {count: 10}, - user2: {count: 10}}, + { + name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{ + nil: {count: 10}, + user: {count: 10}, + user2: {count: 10}, + }, }, - {name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{ - nil: {count: 10}, - user: {count: 10}, - user2: {count: 10}}, + { + name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{ + nil: {count: 10}, + user: {count: 10}, + user2: {count: 10}, + }, }, - {name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{ - nil: {count: 7, repoName: "big_test_"}, - user: {count: 7, repoName: "big_test_"}, - user2: {count: 7, repoName: "big_test_"}}, + { + name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{ + nil: {count: 7, repoName: "big_test_"}, + user: {count: 7, repoName: "big_test_"}, + user2: {count: 7, repoName: "big_test_"}, + }, }, - {name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{ - nil: {count: 5}, - user: {count: 9, includesPrivate: true}, - user2: {count: 6, includesPrivate: true}}, + { + name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{ + nil: {count: 5}, + user: {count: 9, includesPrivate: true}, + user2: {count: 6, includesPrivate: true}, + }, }, - {name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{ - nil: {count: 1}, - user: {count: 2, includesPrivate: true}, - user2: {count: 2, includesPrivate: true}, - user4: {count: 1}}, + { + name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{ + nil: {count: 1}, + user: {count: 2, includesPrivate: true}, + user2: {count: 2, includesPrivate: true}, + user4: {count: 1}, + }, }, - {name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{ - nil: {count: 1}, - user: {count: 4, includesPrivate: true}, - user2: {count: 3, includesPrivate: true}, - user3: {count: 4, includesPrivate: true}}, + { + name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{ + nil: {count: 1}, + user: {count: 4, includesPrivate: true}, + user2: {count: 3, includesPrivate: true}, + user3: {count: 4, includesPrivate: true}, + }, }, - {name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{ - nil: {count: 1, repoOwnerID: orgUser.ID}, - user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true}, - user2: {count: 1, repoOwnerID: orgUser.ID}}, + { + name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{ + nil: {count: 1, repoOwnerID: orgUser.ID}, + user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true}, + user2: {count: 1, repoOwnerID: orgUser.ID}, + }, }, {name: "RepositoriesAccessibleAndRelatedToUser4", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user4.ID), expectedResults: expectedResults{ nil: {count: 3}, user: {count: 4, includesPrivate: true}, - user4: {count: 7, includesPrivate: true}}}, + user4: {count: 7, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeSource", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "source"), expectedResults: expectedResults{ nil: {count: 0}, user: {count: 1, includesPrivate: true}, - user4: {count: 1, includesPrivate: true}}}, + user4: {count: 1, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "fork"), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 1}, - user4: {count: 2, includesPrivate: true}}}, + user4: {count: 2, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "fork"), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 1}, - user4: {count: 2, includesPrivate: true}}}, + user4: {count: 2, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "mirror"), expectedResults: expectedResults{ nil: {count: 2}, user: {count: 2}, - user4: {count: 4, includesPrivate: true}}}, + user4: {count: 4, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "mirror"), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 1}, - user4: {count: 2, includesPrivate: true}}}, + user4: {count: 2, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeCollaborative", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "collaborative"), expectedResults: expectedResults{ nil: {count: 0}, user: {count: 1, includesPrivate: true}, - user4: {count: 1, includesPrivate: true}}}, + user4: {count: 1, includesPrivate: true}, + }}, } for _, testCase := range testCases { @@ -464,7 +487,7 @@ func TestAPIRepoTransfer(t *testing.T) { defer prepareTestEnv(t)() - //create repo to move + // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -480,7 +503,7 @@ func TestAPIRepoTransfer(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, apiRepo) - //start testing + // start testing for _, testCase := range testCases { user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}).(*user_model.User) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository) @@ -493,13 +516,13 @@ func TestAPIRepoTransfer(t *testing.T) { session.MakeRequest(t, req, testCase.expectedStatus) } - //cleanup + // cleanup repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository) _ = models.DeleteRepository(user, repo.OwnerID, repo.ID) } func transfer(t *testing.T) *repo_model.Repository { - //create repo to move + // create repo to move user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_topic_test.go b/integrations/api_repo_topic_test.go index c417b3a9d236..b7f9a5a5a689 100644 --- a/integrations/api_repo_topic_test.go +++ b/integrations/api_repo_topic_test.go @@ -155,5 +155,4 @@ func TestAPIRepoTopic(t *testing.T) { // Test add a topic to repo with write access (requires repo admin access) req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user3.Name, repo3.Name, "topicName", token4) session.MakeRequest(t, req, http.StatusForbidden) - } diff --git a/integrations/api_user_heatmap_test.go b/integrations/api_user_heatmap_test.go index 019cf7dcac58..69f4ff2249bf 100644 --- a/integrations/api_user_heatmap_test.go +++ b/integrations/api_user_heatmap_test.go @@ -22,7 +22,7 @@ func TestUserHeatmap(t *testing.T) { normalUsername := "user2" session := loginUser(t, adminUsername) - var fakeNow = time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local) + fakeNow := time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local) timeutil.Set(fakeNow) defer timeutil.Unset() diff --git a/integrations/api_user_orgs_test.go b/integrations/api_user_orgs_test.go index 09272726f663..219bd273c99c 100644 --- a/integrations/api_user_orgs_test.go +++ b/integrations/api_user_orgs_test.go @@ -54,7 +54,7 @@ func TestUserOrgs(t *testing.T) { } func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) { - var token = "" + token := "" session := emptyTestSession(t) if len(userDoer) != 0 { session = loginUser(t, userDoer) diff --git a/integrations/attachment_test.go b/integrations/attachment_test.go index 481104d73f58..25243feb3c2e 100644 --- a/integrations/attachment_test.go +++ b/integrations/attachment_test.go @@ -32,7 +32,7 @@ func generateImg() bytes.Buffer { func createAttachment(t *testing.T, session *TestSession, repoURL, filename string, buff bytes.Buffer, expectedStatus int) string { body := &bytes.Buffer{} - //Setup multi-part + // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", filename) assert.NoError(t, err) @@ -86,7 +86,7 @@ func TestCreateIssueAttachment(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusFound) test.RedirectURL(resp) // check that redirect URL exists - //Validate that attachment is available + // Validate that attachment is available req = NewRequest(t, "GET", "/attachments/"+uuid) session.MakeRequest(t, req, http.StatusOK) } @@ -120,12 +120,12 @@ func TestGetAttachment(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - //Write empty file to be available for response + // Write empty file to be available for response if tc.createFile { _, err := storage.Attachments.Save(repo_model.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world"), -1) assert.NoError(t, err) } - //Actual test + // Actual test req := NewRequest(t, "GET", "/attachments/"+tc.uuid) tc.session.MakeRequest(t, req, tc.want) }) diff --git a/integrations/benchmarks_test.go b/integrations/benchmarks_test.go index 517e7f005d98..ffae471307d2 100644 --- a/integrations/benchmarks_test.go +++ b/integrations/benchmarks_test.go @@ -58,7 +58,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) { req := NewRequestf(b, "GET", "/api/v1/repos/%s/branches", repo.FullName()) resp := session.MakeRequest(b, req, http.StatusOK) DecodeJSON(b, resp, &branches) - b.ResetTimer() //We measure from here + b.ResetTimer() // We measure from here if len(branches) != 0 { for i := 0; i < b.N; i++ { req := NewRequestf(b, "GET", "/api/v1/repos/%s/commits?sha=%s", repo.FullName(), branches[i%len(branches)].Name) diff --git a/integrations/cmd_keys_test.go b/integrations/cmd_keys_test.go index d33765c44531..3d4194c33142 100644 --- a/integrations/cmd_keys_test.go +++ b/integrations/cmd_keys_test.go @@ -29,7 +29,8 @@ func Test_CmdKeys(t *testing.T) { }{ {"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""}, {"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""}, - {"with_key", + { + "with_key", []string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="}, false, "# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + util.ShellEscape(setting.CustomConf) + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,no-user-rc,restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n", @@ -38,7 +39,7 @@ func Test_CmdKeys(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - realStdout := os.Stdout //Backup Stdout + realStdout := os.Stdout // Backup Stdout r, w, _ := os.Pipe() os.Stdout = w @@ -56,7 +57,7 @@ func Test_CmdKeys(t *testing.T) { if tt.expectedOutput != commandOutput { t.Errorf("expectedOutput: %#v, commandOutput: %#v", tt.expectedOutput, commandOutput) } - //Restore stdout + // Restore stdout os.Stdout = realStdout }) } diff --git a/integrations/dump_restore_test.go b/integrations/dump_restore_test.go index f35af43a91fe..053ca4785558 100644 --- a/integrations/dump_restore_test.go +++ b/integrations/dump_restore_test.go @@ -55,7 +55,7 @@ func TestDumpRestore(t *testing.T) { // ctx := context.Background() - var opts = migrations.MigrateOptions{ + opts := migrations.MigrateOptions{ GitServiceType: structs.GiteaService, Issues: true, Labels: true, @@ -109,11 +109,11 @@ func TestDumpRestore(t *testing.T) { beforeBytes, err := os.ReadFile(filepath.Join(d, "issue.yml")) assert.NoError(t, err) - var before = make([]*base.Issue, 0, 10) + before := make([]*base.Issue, 0, 10) assert.NoError(t, yaml.Unmarshal(beforeBytes, &before)) afterBytes, err := os.ReadFile(filepath.Join(newd, "issue.yml")) assert.NoError(t, err) - var after = make([]*base.Issue, 0, 10) + after := make([]*base.Issue, 0, 10) assert.NoError(t, yaml.Unmarshal(afterBytes, &after)) assert.EqualValues(t, len(before), len(after)) diff --git a/integrations/editor_test.go b/integrations/editor_test.go index a46712293e86..05892aa90684 100644 --- a/integrations/editor_test.go +++ b/integrations/editor_test.go @@ -120,7 +120,6 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa } func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *httptest.ResponseRecorder { - // Get to the 'edit this file' page req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath)) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/integrations/eventsource_test.go b/integrations/eventsource_test.go index 8984c1fcb029..ff3298863485 100644 --- a/integrations/eventsource_test.go +++ b/integrations/eventsource_test.go @@ -69,7 +69,7 @@ func TestEventSourceManagerRun(t *testing.T) { DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) - lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 <- only Notification 4 is in this filter ... + lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) session.MakeRequest(t, req, http.StatusResetContent) diff --git a/integrations/git_helper_for_declarative_test.go b/integrations/git_helper_for_declarative_test.go index 282bdd04a9d6..b13c912fd79d 100644 --- a/integrations/git_helper_for_declarative_test.go +++ b/integrations/git_helper_for_declarative_test.go @@ -27,12 +27,11 @@ import ( ) func withKeyFile(t *testing.T, keyname string, callback func(string)) { - tmpDir, err := os.MkdirTemp("", "key-file") assert.NoError(t, err) defer util.RemoveAll(tmpDir) - err = os.Chmod(tmpDir, 0700) + err = os.Chmod(tmpDir, 0o700) assert.NoError(t, err) keyFile := filepath.Join(tmpDir, keyname) @@ -40,10 +39,10 @@ func withKeyFile(t *testing.T, keyname string, callback func(string)) { assert.NoError(t, err) err = os.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+ - "ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0700) + "ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0o700) assert.NoError(t, err) - //Setup ssh wrapper + // Setup ssh wrapper os.Setenv("GIT_SSH", path.Join(tmpDir, "ssh")) os.Setenv("GIT_SSH_COMMAND", "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i \""+keyFile+"\"") @@ -103,7 +102,7 @@ func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ... }() go s.Serve(listener) - //Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs) + // Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs) callback(t, u) } @@ -142,7 +141,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) { // forcibly set default branch to master _, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath) assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644)) + assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", diff --git a/integrations/git_smart_http_test.go b/integrations/git_smart_http_test.go index c049f71c303d..b6043fe70668 100644 --- a/integrations/git_smart_http_test.go +++ b/integrations/git_smart_http_test.go @@ -18,7 +18,7 @@ func TestGitSmartHTTP(t *testing.T) { } func testGitSmartHTTP(t *testing.T, u *url.URL) { - var kases = []struct { + kases := []struct { p string code int }{ diff --git a/integrations/git_test.go b/integrations/git_test.go index 0d33c786aaef..243cca2e55bd 100644 --- a/integrations/git_test.go +++ b/integrations/git_test.go @@ -32,8 +32,8 @@ import ( ) const ( - littleSize = 1024 //1ko - bigSize = 128 * 1024 * 1024 //128Mo + littleSize = 1024 // 1ko + bigSize = 128 * 1024 * 1024 // 128Mo ) func TestGit(t *testing.T) { @@ -96,15 +96,15 @@ func testGit(t *testing.T, u *url.URL) { t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, perm.AccessModeRead)) t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username)) - //Setup key the user ssh key + // Setup key the user ssh key withKeyFile(t, keyname, func(keyFile string) { t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile)) - //Setup remote link - //TODO: get url from api + // Setup remote link + // TODO: get url from api sshURL := createSSHUrl(sshContext.GitPath(), u) - //Setup clone folder + // Setup clone folder dstPath, err := os.MkdirTemp("", sshContext.Reponame) assert.NoError(t, err) defer util.RemoveAll(dstPath) @@ -135,7 +135,6 @@ func ensureAnonymousClone(t *testing.T, u *url.URL) { assert.NoError(t, err) defer util.RemoveAll(dstLocalPath) t.Run("CloneAnonymous", doGitClone(dstLocalPath, u)) - } func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) { @@ -300,13 +299,13 @@ func lockFileTest(t *testing.T, filename, repoPath string) { func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string { name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix) assert.NoError(t, err) - _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push + _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) // Push assert.NoError(t, err) return name } func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) { - //Generate random file + // Generate random file bufSize := 4 * 1024 if bufSize > size { bufSize = size @@ -339,7 +338,7 @@ func generateCommitWithNewData(size int, repoPath, email, fullName, prefix strin return "", err } - //Commit + // Commit // Now here we should explicitly allow lfs filters to run globalArgs := allowLFSFilters() err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name())) @@ -639,7 +638,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch)) t.Run("AddCommit", func(t *testing.T) { - err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666) + err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666) if !assert.NoError(t, err) { return } @@ -713,7 +712,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB } t.Run("AddCommit2", func(t *testing.T) { - err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666) + err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666) if !assert.NoError(t, err) { return } diff --git a/integrations/gpg_git_test.go b/integrations/gpg_git_test.go index 8478f53c0e94..461f3c503d55 100644 --- a/integrations/gpg_git_test.go +++ b/integrations/gpg_git_test.go @@ -32,7 +32,7 @@ func TestGPGGit(t *testing.T) { assert.NoError(t, err) defer util.RemoveAll(tmpDir) - err = os.Chmod(tmpDir, 0700) + err = os.Chmod(tmpDir, 0o700) assert.NoError(t, err) oldGNUPGHome := os.Getenv("GNUPGHOME") @@ -257,7 +257,6 @@ func TestGPGGit(t *testing.T) { } assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email) })) - }) }, false) var pr api.PullRequest @@ -321,7 +320,6 @@ func TestGPGGit(t *testing.T) { assert.NotNil(t, branch.Commit.Verification) assert.True(t, branch.Commit.Verification.Verified) })) - }) }, false) } diff --git a/integrations/integration_test.go b/integrations/integration_test.go index 527d4b951ad2..dfa5bade785e 100644 --- a/integrations/integration_test.go +++ b/integrations/integration_test.go @@ -268,10 +268,10 @@ func prepareTestEnv(t testing.TB, skip ...int) func() { assert.NoError(t, err, "unable to read the new repo root: %v\n", err) } for _, repoDir := range repoDirs { - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755) } } @@ -395,7 +395,7 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession return session } -//token has to be unique this counter take care of +// token has to be unique this counter take care of var tokenCounter int64 func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { @@ -564,10 +564,10 @@ func resetFixtures(t *testing.T) { assert.NoError(t, err, "unable to read the new repo root: %v\n", err) } for _, repoDir := range repoDirs { - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755) } } } diff --git a/integrations/issue_test.go b/integrations/issue_test.go index a2c74d4bdd8f..29de774ee4d2 100644 --- a/integrations/issue_test.go +++ b/integrations/issue_test.go @@ -121,7 +121,6 @@ func TestNoLoginViewIssue(t *testing.T) { } func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content string) string { - req := NewRequest(t, "GET", path.Join(user, repo, "issues", "new")) resp := session.MakeRequest(t, req, http.StatusOK) @@ -149,7 +148,6 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content } func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, status string) int64 { - req := NewRequest(t, "GET", issueURL) resp := session.MakeRequest(t, req, http.StatusOK) @@ -244,7 +242,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNone}) + RefAction: references.XRefActionNone, + }) // Edit title, neuter ref testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref") @@ -254,7 +253,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNeutered}) + RefAction: references.XRefActionNeutered, + }) // Ref from issue content issueRefURL, issueRef = testIssueWithBean(t, "user2", 1, "TitleXRef", fmt.Sprintf("Description ref #%d", issueBase.Index)) @@ -264,7 +264,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNone}) + RefAction: references.XRefActionNone, + }) // Edit content, neuter ref testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref") @@ -274,7 +275,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNeutered}) + RefAction: references.XRefActionNeutered, + }) // Ref from a comment session := loginUser(t, "user2") @@ -285,7 +287,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: commentID, RefIsPull: false, - RefAction: references.XRefActionNone} + RefAction: references.XRefActionNone, + } unittest.AssertExistsAndLoadBean(t, comment) // Ref from a different repository @@ -296,7 +299,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNone}) + RefAction: references.XRefActionNone, + }) } func testIssueWithBean(t *testing.T, user string, repoID int64, title, content string) (string, *models.Issue) { diff --git a/integrations/lfs_local_endpoint_test.go b/integrations/lfs_local_endpoint_test.go index 7e0166b38189..9de0ec18c90d 100644 --- a/integrations/lfs_local_endpoint_test.go +++ b/integrations/lfs_local_endpoint_test.go @@ -29,13 +29,13 @@ func TestDetermineLocalEndpoint(t *testing.T) { rootdotgit, _ := os.MkdirTemp("", "lfs_test") defer os.RemoveAll(rootdotgit) - os.Mkdir(filepath.Join(rootdotgit, ".git"), 0700) + os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700) lfsroot, _ := os.MkdirTemp("", "lfs_test") defer os.RemoveAll(lfsroot) // Test cases - var cases = []struct { + cases := []struct { cloneurl string lfsurl string expected *url.URL diff --git a/integrations/links_test.go b/integrations/links_test.go index d1d90cd5e3cc..f514aa7757b2 100644 --- a/integrations/links_test.go +++ b/integrations/links_test.go @@ -20,7 +20,7 @@ import ( func TestLinksNoLogin(t *testing.T) { defer prepareTestEnv(t)() - var links = []string{ + links := []string{ "/explore/repos", "/explore/repos?q=test&tab=", "/explore/users", @@ -49,7 +49,7 @@ func TestLinksNoLogin(t *testing.T) { func TestRedirectsNoLogin(t *testing.T) { defer prepareTestEnv(t)() - var redirects = map[string]string{ + redirects := map[string]string{ "/user2/repo1/commits/master": "/user2/repo1/commits/branch/master", "/user2/repo1/src/master": "/user2/repo1/src/branch/master", "/user2/repo1/src/master/file.txt": "/user2/repo1/src/branch/master/file.txt", @@ -67,7 +67,7 @@ func TestRedirectsNoLogin(t *testing.T) { func TestNoLoginNotExist(t *testing.T) { defer prepareTestEnv(t)() - var links = []string{ + links := []string{ "/user5/repo4/projects", "/user5/repo4/projects/3", } @@ -79,7 +79,7 @@ func TestNoLoginNotExist(t *testing.T) { } func testLinksAsUser(userName string, t *testing.T) { - var links = []string{ + links := []string{ "/explore/repos", "/explore/repos?q=test&tab=", "/explore/users", @@ -138,7 +138,7 @@ func testLinksAsUser(userName string, t *testing.T) { var apiRepos []*api.Repository DecodeJSON(t, respAPI, &apiRepos) - var repoLinks = []string{ + repoLinks := []string{ "", "/issues", "/pulls", diff --git a/integrations/migration-test/migration_test.go b/integrations/migration-test/migration_test.go index 266170412250..0518dd117989 100644 --- a/integrations/migration-test/migration_test.go +++ b/integrations/migration-test/migration_test.go @@ -74,10 +74,10 @@ func initMigrationTest(t *testing.T) func() { assert.NoError(t, err, "unable to read the new repo root: %v\n", err) } for _, repoDir := range repoDirs { - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755) } } @@ -315,6 +315,5 @@ func TestMigrations(t *testing.T) { t.Run(fmt.Sprintf("Migrate-%s-%s", dialect, version), func(t *testing.T) { doMigrationTest(t, version) }) - } } diff --git a/integrations/nonascii_branches_test.go b/integrations/nonascii_branches_test.go index 71d0ee3cb106..f2992ecc1f88 100644 --- a/integrations/nonascii_branches_test.go +++ b/integrations/nonascii_branches_test.go @@ -210,5 +210,4 @@ func TestNonasciiBranches(t *testing.T) { } setDefaultBranch(t, session, user, repo, "master") - } diff --git a/integrations/privateactivity_test.go b/integrations/privateactivity_test.go index 7969339644eb..44df39b6e004 100644 --- a/integrations/privateactivity_test.go +++ b/integrations/privateactivity_test.go @@ -18,8 +18,10 @@ import ( "github.com/stretchr/testify/assert" ) -const privateActivityTestAdmin = "user1" -const privateActivityTestUser = "user2" +const ( + privateActivityTestAdmin = "user1" + privateActivityTestUser = "user2" +) // user3 is an organization so it is not usable here const privateActivityTestOtherUser = "user4" diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index ed34a0f6d689..49e7dc04ecaa 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -65,7 +65,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str func TestPullMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -87,7 +87,7 @@ func TestPullMerge(t *testing.T) { func TestPullRebase(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -109,7 +109,7 @@ func TestPullRebase(t *testing.T) { func TestPullRebaseMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -131,7 +131,7 @@ func TestPullRebaseMerge(t *testing.T) { func TestPullSquash(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) diff --git a/integrations/pull_update_test.go b/integrations/pull_update_test.go index b80b85fbeb3e..dc2803aca034 100644 --- a/integrations/pull_update_test.go +++ b/integrations/pull_update_test.go @@ -23,12 +23,12 @@ import ( func TestAPIPullUpdate(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - //Create PR to test + // Create PR to test user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User) pr := createOutdatedPR(t, user, org26) - //Test GetDiverging + // Test GetDiverging diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr) assert.NoError(t, err) assert.EqualValues(t, 1, diffCount.Behind) @@ -41,7 +41,7 @@ func TestAPIPullUpdate(t *testing.T) { req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) - //Test GetDiverging after update + // Test GetDiverging after update diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr) assert.NoError(t, err) assert.EqualValues(t, 0, diffCount.Behind) @@ -51,12 +51,12 @@ func TestAPIPullUpdate(t *testing.T) { func TestAPIPullUpdateByRebase(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - //Create PR to test + // Create PR to test user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User) pr := createOutdatedPR(t, user, org26) - //Test GetDiverging + // Test GetDiverging diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr) assert.NoError(t, err) assert.EqualValues(t, 1, diffCount.Behind) @@ -69,7 +69,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) - //Test GetDiverging after update + // Test GetDiverging after update diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr) assert.NoError(t, err) assert.EqualValues(t, 0, diffCount.Behind) @@ -98,7 +98,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul assert.NoError(t, err) assert.NotEmpty(t, headRepo) - //create a commit on base Repo + // create a commit on base Repo _, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, baseRepo, actor, &files_service.UpdateRepoFileOptions{ TreePath: "File_A", Message: "Add File A", @@ -121,7 +121,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul }) assert.NoError(t, err) - //create a commit on head Repo + // create a commit on head Repo _, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, headRepo, actor, &files_service.UpdateRepoFileOptions{ TreePath: "File_B", Message: "Add File on PR branch", @@ -144,7 +144,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul }) assert.NoError(t, err) - //create Pull + // create Pull pullIssue := &models.Issue{ RepoID: baseRepo.ID, Title: "Test Pull -to-update-", diff --git a/integrations/repo_activity_test.go b/integrations/repo_activity_test.go index 66cc8dcfe2b9..a10ec7f2d3d8 100644 --- a/integrations/repo_activity_test.go +++ b/integrations/repo_activity_test.go @@ -18,7 +18,6 @@ import ( func TestRepoActivity(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - session := loginUser(t, "user1") // Create PRs (1 merged & 2 proposed) diff --git a/integrations/repo_commits_test.go b/integrations/repo_commits_test.go index 4be1e4ec8e47..b53d988c58b7 100644 --- a/integrations/repo_commits_test.go +++ b/integrations/repo_commits_test.go @@ -71,12 +71,12 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { assert.True(t, sel.HasClass(class)) } - //By SHA + // By SHA req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/statuses") reqOne := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/status") testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state) - //By Ref + // By Ref req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses") reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/status") testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state) diff --git a/integrations/repofiles_update_test.go b/integrations/repofiles_update_test.go index 97cdd67ba340..46c73b48f6bf 100644 --- a/integrations/repofiles_update_test.go +++ b/integrations/repofiles_update_test.go @@ -399,7 +399,7 @@ func TestCreateOrUpdateRepoFileErrors(t *testing.T) { t.Run("create file that already exists", func(t *testing.T) { opts := getCreateRepoFileOptions(repo) - opts.TreePath = "README.md" //already exists + opts.TreePath = "README.md" // already exists fileResponse, err := files_service.CreateOrUpdateRepoFile(git.DefaultContext, repo, doer, opts) assert.Nil(t, fileResponse) assert.Error(t, err) diff --git a/integrations/setting_test.go b/integrations/setting_test.go index eb495acb2445..c0455a452023 100644 --- a/integrations/setting_test.go +++ b/integrations/setting_test.go @@ -77,7 +77,6 @@ func TestSettingShowUserEmailProfile(t *testing.T) { htmlDoc.doc.Find(".user.profile").Text(), "user2@example.com", ) - } func TestSettingLandingPage(t *testing.T) { diff --git a/integrations/ssh_key_test.go b/integrations/ssh_key_test.go index f9c807413ad4..e0ff13543e53 100644 --- a/integrations/ssh_key_test.go +++ b/integrations/ssh_key_test.go @@ -28,7 +28,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) { return func(t *testing.T) { - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0644)) + assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", @@ -67,7 +67,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { t.Run("InitTestRepository", doGitInitTestRepository(dstPath)) - //Setup remote link + // Setup remote link sshURL := createSSHUrl(ctx.GitPath(), u) t.Run("AddRemote", doGitAddRemote(dstPath, "origin", sshURL)) diff --git a/integrations/testlogger.go b/integrations/testlogger.go index 69db480c159f..246f6fe7d02a 100644 --- a/integrations/testlogger.go +++ b/integrations/testlogger.go @@ -185,7 +185,7 @@ func (log *TestLogger) Init(config string) error { func (log *TestLogger) Flush() { } -//ReleaseReopen does nothing +// ReleaseReopen does nothing func (log *TestLogger) ReleaseReopen() error { return nil } diff --git a/integrations/timetracking_test.go b/integrations/timetracking_test.go index 7cf5f9bc8f0e..17e9174e5d91 100644 --- a/integrations/timetracking_test.go +++ b/integrations/timetracking_test.go @@ -19,15 +19,16 @@ func TestViewTimetrackingControls(t *testing.T) { defer prepareTestEnv(t)() session := loginUser(t, "user2") testViewTimetrackingControls(t, session, "user2", "repo1", "1", true) - //user2/repo1 + // user2/repo1 } func TestNotViewTimetrackingControls(t *testing.T) { defer prepareTestEnv(t)() session := loginUser(t, "user5") testViewTimetrackingControls(t, session, "user2", "repo1", "1", false) - //user2/repo1 + // user2/repo1 } + func TestViewTimetrackingControlsDisabled(t *testing.T) { defer prepareTestEnv(t)() session := loginUser(t, "user2") diff --git a/integrations/user_avatar_test.go b/integrations/user_avatar_test.go index d1005bce078b..7c2267885aeb 100644 --- a/integrations/user_avatar_test.go +++ b/integrations/user_avatar_test.go @@ -42,7 +42,7 @@ func TestUserAvatar(t *testing.T) { body := &bytes.Buffer{} - //Setup multi-part + // Setup multi-part writer := multipart.NewWriter(body) writer.WriteField("source", "local") part, err := writer.CreateFormFile("avatar", "avatar-for-testuseravatar.png") diff --git a/integrations/user_test.go b/integrations/user_test.go index 8552993217a7..c12c2be40e62 100644 --- a/integrations/user_test.go +++ b/integrations/user_test.go @@ -119,15 +119,15 @@ func TestRenameReservedUsername(t *testing.T) { func TestExportUserGPGKeys(t *testing.T) { defer prepareTestEnv(t)() - //Export empty key list + // Export empty key list testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK----- =twTO -----END PGP PUBLIC KEY BLOCK----- `) - //Import key - //User1 + // Import key + // User1 session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK----- @@ -161,7 +161,7 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH =DDXw -----END PGP PUBLIC KEY BLOCK----- `) - //Export new key + // Export new key testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK----- xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo @@ -200,6 +200,6 @@ func testExportUserGPGKeys(t *testing.T, user, expected string) { t.Logf("Testing username %s export gpg keys", user) req := NewRequest(t, "GET", "/"+user+".gpg") resp := session.MakeRequest(t, req, http.StatusOK) - //t.Log(resp.Body.String()) + // t.Log(resp.Body.String()) assert.Equal(t, expected, resp.Body.String()) } diff --git a/main.go b/main.go index 6cbdc244018b..19b9dd63275f 100644 --- a/main.go +++ b/main.go @@ -186,7 +186,7 @@ DEFAULT CONFIGURATION: } func formatBuiltWith() string { - var version = runtime.Version() + version := runtime.Version() if len(MakeVersion) > 0 { version = MakeVersion + ", " + runtime.Version() } diff --git a/models/auth/webauthn.go b/models/auth/webauthn.go index 9e0913466266..e6c446af9424 100644 --- a/models/auth/webauthn.go +++ b/models/auth/webauthn.go @@ -12,9 +12,9 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/timeutil" - "xorm.io/xorm" "github.com/duo-labs/webauthn/webauthn" + "xorm.io/xorm" ) // ErrWebAuthnCredentialNotExist represents a "ErrWebAuthnCRedentialNotExist" kind of error. @@ -30,14 +30,14 @@ func (err ErrWebAuthnCredentialNotExist) Error() string { return fmt.Sprintf("WebAuthn credential does not exist [credential_id: %s]", err.CredentialID) } -//IsErrWebAuthnCredentialNotExist checks if an error is a ErrWebAuthnCredentialNotExist. +// IsErrWebAuthnCredentialNotExist checks if an error is a ErrWebAuthnCredentialNotExist. func IsErrWebAuthnCredentialNotExist(err error) bool { _, ok := err.(ErrWebAuthnCredentialNotExist) return ok } -//WebAuthnCredential represents the WebAuthn credential data for a public-key -//credential conformant to WebAuthn Level 1 +// WebAuthnCredential represents the WebAuthn credential data for a public-key +// credential conformant to WebAuthn Level 1 type WebAuthnCredential struct { ID int64 `xorm:"pk autoincr"` Name string @@ -109,7 +109,7 @@ func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential { return creds } -//GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user +// GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user func GetWebAuthnCredentialsByUID(uid int64) (WebAuthnCredentialList, error) { return getWebAuthnCredentialsByUID(db.DefaultContext, uid) } @@ -119,7 +119,7 @@ func getWebAuthnCredentialsByUID(ctx context.Context, uid int64) (WebAuthnCreden return creds, db.GetEngine(ctx).Where("user_id = ?", uid).Find(&creds) } -//ExistsWebAuthnCredentialsForUID returns if the given user has credentials +// ExistsWebAuthnCredentialsForUID returns if the given user has credentials func ExistsWebAuthnCredentialsForUID(uid int64) (bool, error) { return existsWebAuthnCredentialsByUID(db.DefaultContext, uid) } @@ -211,7 +211,7 @@ func deleteCredential(ctx context.Context, id, userID int64) (bool, error) { return had > 0, err } -//WebAuthnCredentials implementns the webauthn.User interface +// WebAuthnCredentials implementns the webauthn.User interface func WebAuthnCredentials(userID int64) ([]webauthn.Credential, error) { dbCreds, err := GetWebAuthnCredentialsByUID(userID) if err != nil { diff --git a/models/avatars/avatar.go b/models/avatars/avatar.go index 6107856adeed..9f7b0c474ff0 100644 --- a/models/avatars/avatar.go +++ b/models/avatars/avatar.go @@ -175,12 +175,12 @@ func generateEmailAvatarLink(email string, size int, final bool) string { return DefaultAvatarLink() } -//GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}") +// GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}") func GenerateEmailAvatarFastLink(email string, size int) string { return generateEmailAvatarLink(email, size, false) } -//GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow) +// GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow) func GenerateEmailAvatarFinalLink(email string, size int) string { return generateEmailAvatarLink(email, size, true) } diff --git a/models/consistency.go b/models/consistency.go index 0b9d9fd2c340..4a94fe25d41f 100644 --- a/models/consistency.go +++ b/models/consistency.go @@ -240,7 +240,6 @@ func FixIssueLabelWithOutsideLabels() (int64, error) { WHERE (label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id) ) AS il_too )`) - if err != nil { return 0, err } diff --git a/models/db/engine.go b/models/db/engine.go index 665808d70176..0604d939d379 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -121,7 +121,7 @@ func newXORMEngine() (*xorm.Engine, error) { return engine, nil } -//SyncAllTables sync the schemas of all tables, is required by unit test code +// SyncAllTables sync the schemas of all tables, is required by unit test code func SyncAllTables() error { return x.StoreEngine("InnoDB").Sync2(tables...) } diff --git a/models/issue_test.go b/models/issue_test.go index aee9a50184ac..e2759ba38f0f 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -394,7 +394,6 @@ func TestIssue_InsertIssue(t *testing.T) { issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7) _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue)) assert.NoError(t, err) - } func TestIssue_ResolveMentions(t *testing.T) { diff --git a/models/issues/content_history.go b/models/issues/content_history.go index 721ce11f85b4..2d2febfa5cb7 100644 --- a/models/issues/content_history.go +++ b/models/issues/content_history.go @@ -155,7 +155,6 @@ func FetchIssueContentHistoryList(dbCtx context.Context, issueID, commentID int6 Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}). OrderBy("edited_unix DESC"). Find(&res) - if err != nil { log.Error("can not fetch issue content history list. err=%v", err) return nil, err diff --git a/models/lfs.go b/models/lfs.go index cf596f546838..e0c16767f71e 100644 --- a/models/lfs.go +++ b/models/lfs.go @@ -209,7 +209,7 @@ func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int6 func IterateLFS(f func(mo *LFSMetaObject) error) error { var start int const batchSize = 100 - var e = db.GetEngine(db.DefaultContext) + e := db.GetEngine(db.DefaultContext) for { mos := make([]*LFSMetaObject, 0, batchSize) if err := e.Limit(batchSize, start).Find(&mos); err != nil { diff --git a/models/migrate_test.go b/models/migrate_test.go index 09433b6b4175..34183c1854f6 100644 --- a/models/migrate_test.go +++ b/models/migrate_test.go @@ -45,7 +45,7 @@ func assertCreateIssues(t *testing.T, reponame string, isPull bool) { } title := "issuetitle1" - var is = &Issue{ + is := &Issue{ RepoID: repo.ID, MilestoneID: milestone.ID, Repo: repo, @@ -130,7 +130,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}).(*repo_model.Repository) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User) - var i = &Issue{ + i := &Issue{ RepoID: repo.ID, Repo: repo, Title: "title1", @@ -140,7 +140,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) { Poster: owner, } - var p = &PullRequest{ + p := &PullRequest{ Issue: i, } diff --git a/models/migrations/migrations_test.go b/models/migrations/migrations_test.go index 33d589ddb259..f798d501179f 100644 --- a/models/migrations/migrations_test.go +++ b/models/migrations/migrations_test.go @@ -219,10 +219,10 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En assert.NoError(t, err, "unable to read the new repo root: %v\n", err) } for _, repoDir := range repoDirs { - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755) } } diff --git a/models/migrations/testlogger_test.go b/models/migrations/testlogger_test.go index 5e3d880b54e3..01d6b7a0f7d4 100644 --- a/models/migrations/testlogger_test.go +++ b/models/migrations/testlogger_test.go @@ -170,7 +170,7 @@ func (log *TestLogger) Init(config string) error { func (log *TestLogger) Flush() { } -//ReleaseReopen does nothing +// ReleaseReopen does nothing func (log *TestLogger) ReleaseReopen() error { return nil } diff --git a/models/migrations/v176_test.go b/models/migrations/v176_test.go index 2763e4f120e2..bc066c3b3272 100644 --- a/models/migrations/v176_test.go +++ b/models/migrations/v176_test.go @@ -124,5 +124,4 @@ func Test_removeInvalidLabels(t *testing.T) { t.Errorf("IssueLabel[%d] was deleted but should have remained", id) } } - } diff --git a/models/migrations/v177_test.go b/models/migrations/v177_test.go index f5fc793aa423..5a58e2c6146b 100644 --- a/models/migrations/v177_test.go +++ b/models/migrations/v177_test.go @@ -85,5 +85,4 @@ func Test_deleteOrphanedIssueLabels(t *testing.T) { pre := preMigration[id] assert.Equal(t, pre, post, "migration changed issueLabel %d", id) } - } diff --git a/models/migrations/v181_test.go b/models/migrations/v181_test.go index b392a9b71d7b..b9a6c6619b71 100644 --- a/models/migrations/v181_test.go +++ b/models/migrations/v181_test.go @@ -38,7 +38,7 @@ func Test_addPrimaryEmail2EmailAddress(t *testing.T) { IsPrimary bool `xorm:"DEFAULT(false) NOT NULL"` } - var users = make([]User, 0, 20) + users := make([]User, 0, 20) err = x.Find(&users) assert.NoError(t, err) diff --git a/models/migrations/v182_test.go b/models/migrations/v182_test.go index 9fb371e07873..0d3eda9c51a6 100644 --- a/models/migrations/v182_test.go +++ b/models/migrations/v182_test.go @@ -37,10 +37,10 @@ func Test_addIssueResourceIndexTable(t *testing.T) { MaxIndex int64 `xorm:"index"` } - var start = 0 + start := 0 const batchSize = 1000 for { - var indexes = make([]ResourceIndex, 0, batchSize) + indexes := make([]ResourceIndex, 0, batchSize) err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes) assert.NoError(t, err) diff --git a/models/migrations/v189_test.go b/models/migrations/v189_test.go index fcae5dcc7301..4ec3fe8c6007 100644 --- a/models/migrations/v189_test.go +++ b/models/migrations/v189_test.go @@ -26,7 +26,6 @@ func (ls *LoginSourceOriginalV189) TableName() string { } func Test_unwrapLDAPSourceCfg(t *testing.T) { - // Prepare and load the testing database x, deferable := prepareTestEnv(t, 0, new(LoginSourceOriginalV189)) if x == nil || t.Failed() { @@ -80,5 +79,4 @@ func Test_unwrapLDAPSourceCfg(t *testing.T) { assert.EqualValues(t, source.ID%2 == 0, source.IsActive, "unwrapLDAPSourceCfg failed for %d", source.ID) } } - } diff --git a/models/migrations/v191.go b/models/migrations/v191.go index c91990e0f33d..9a688243e19c 100644 --- a/models/migrations/v191.go +++ b/models/migrations/v191.go @@ -11,7 +11,6 @@ import ( ) func alterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error { - sess := x.NewSession() defer sess.Close() if err := sess.Begin(); err != nil { diff --git a/models/migrations/v195_test.go b/models/migrations/v195_test.go index baf9cb61c2a0..05f8469daaf8 100644 --- a/models/migrations/v195_test.go +++ b/models/migrations/v195_test.go @@ -40,10 +40,10 @@ func Test_addTableCommitStatusIndex(t *testing.T) { MaxIndex int64 `xorm:"index"` } - var start = 0 + start := 0 const batchSize = 1000 for { - var indexes = make([]CommitStatusIndex, 0, batchSize) + indexes := make([]CommitStatusIndex, 0, batchSize) err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes) assert.NoError(t, err) diff --git a/models/migrations/v207.go b/models/migrations/v207.go index 82e2e3aa314f..4964a8435ce7 100644 --- a/models/migrations/v207.go +++ b/models/migrations/v207.go @@ -16,7 +16,6 @@ import ( ) func addWebAuthnCred(x *xorm.Engine) error { - // Create webauthnCredential table type webauthnCredential struct { ID int64 `xorm:"pk autoincr"` diff --git a/models/migrations/v208.go b/models/migrations/v208.go index 04bb981a4e41..c1e656b98d84 100644 --- a/models/migrations/v208.go +++ b/models/migrations/v208.go @@ -12,7 +12,6 @@ import ( ) func useBase32HexForCredIDInWebAuthnCredential(x *xorm.Engine) error { - // Create webauthnCredential table type webauthnCredential struct { ID int64 `xorm:"pk autoincr"` diff --git a/models/repo.go b/models/repo.go index 83031c508cdc..2a857c43df07 100644 --- a/models/repo.go +++ b/models/repo.go @@ -718,7 +718,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { if err != nil { return fmt.Errorf("listDeployKeys: %v", err) } - var needRewriteKeysFile = len(deployKeys) > 0 + needRewriteKeysFile := len(deployKeys) > 0 for _, dKey := range deployKeys { if err := DeleteDeployKey(ctx, doer, dKey.ID); err != nil { return fmt.Errorf("deleteDeployKeys: %v", err) @@ -844,7 +844,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { return err } - var lfsPaths = make([]string, 0, len(lfsObjects)) + lfsPaths := make([]string, 0, len(lfsObjects)) for _, v := range lfsObjects { count, err := sess.Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}}) if err != nil { @@ -867,7 +867,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { return err } - var archivePaths = make([]string, 0, len(archives)) + archivePaths := make([]string, 0, len(archives)) for _, v := range archives { p, _ := v.RelativePath() archivePaths = append(archivePaths, p) @@ -893,7 +893,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { return err } - var newAttachmentPaths = make([]string, 0, len(newAttachments)) + newAttachmentPaths := make([]string, 0, len(newAttachments)) for _, attach := range newAttachments { newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath()) } diff --git a/models/repo/archiver.go b/models/repo/archiver.go index c29891397f8d..dc64cce49ba9 100644 --- a/models/repo/archiver.go +++ b/models/repo/archiver.go @@ -90,7 +90,7 @@ type FindRepoArchiversOption struct { } func (opts FindRepoArchiversOption) toConds() builder.Cond { - var cond = builder.NewCond() + cond := builder.NewCond() if opts.OlderThan > 0 { cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-opts.OlderThan).Unix()}) } @@ -99,7 +99,7 @@ func (opts FindRepoArchiversOption) toConds() builder.Cond { // FindRepoArchives find repo archivers func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) { - var archivers = make([]*RepoArchiver, 0, opts.PageSize) + archivers := make([]*RepoArchiver, 0, opts.PageSize) start, limit := opts.GetSkipTake() err := db.GetEngine(db.DefaultContext).Where(opts.toConds()). Asc("created_unix"). diff --git a/models/repo/attachment.go b/models/repo/attachment.go index 3fb331a2023a..f5351578fbc5 100644 --- a/models/repo/attachment.go +++ b/models/repo/attachment.go @@ -241,7 +241,7 @@ func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...str // UpdateAttachmentCtx updates the given attachment in database func UpdateAttachmentCtx(ctx context.Context, atta *Attachment) error { - var sess = db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count") + sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count") if atta.ID != 0 && atta.UUID == "" { sess = sess.ID(atta.ID) } else { diff --git a/models/repo/mirror.go b/models/repo/mirror.go index bdb449af3a76..e73226534ea1 100644 --- a/models/repo/mirror.go +++ b/models/repo/mirror.go @@ -17,10 +17,8 @@ import ( "xorm.io/xorm" ) -var ( - // ErrMirrorNotExist mirror does not exist error - ErrMirrorNotExist = errors.New("Mirror does not exist") -) +// ErrMirrorNotExist mirror does not exist error +var ErrMirrorNotExist = errors.New("Mirror does not exist") // RemoteMirrorer defines base methods for pull/push mirrors. type RemoteMirrorer interface { diff --git a/models/repo/pushmirror.go b/models/repo/pushmirror.go index 0b6216164122..bf39bb1ac072 100644 --- a/models/repo/pushmirror.go +++ b/models/repo/pushmirror.go @@ -15,10 +15,8 @@ import ( "xorm.io/xorm" ) -var ( - // ErrPushMirrorNotExist mirror does not exist error - ErrPushMirrorNotExist = errors.New("PushMirror does not exist") -) +// ErrPushMirrorNotExist mirror does not exist error +var ErrPushMirrorNotExist = errors.New("PushMirror does not exist") // PushMirror represents mirror information of a repository. type PushMirror struct { diff --git a/models/review_test.go b/models/review_test.go index 20810dac4ac2..a4a71cc709dd 100644 --- a/models/review_test.go +++ b/models/review_test.go @@ -199,5 +199,4 @@ func TestDismissReview(t *testing.T) { assert.False(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.True(t, approveReviewExample.Dismissed) - } diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go index 6f3a36ed216f..c904646d2815 100644 --- a/models/unittest/testdb.go +++ b/models/unittest/testdb.go @@ -117,10 +117,10 @@ func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) { fatalTestError("unable to read the new repo root: %v\n", err) } for _, repoDir := range repoDirs { - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755) } } @@ -182,10 +182,10 @@ func PrepareTestEnv(t testing.TB) { repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name())) assert.NoError(t, err) for _, repoDir := range repoDirs { - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755) - _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755) + _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755) } } diff --git a/models/user/email_address.go b/models/user/email_address.go index 0ff62fb6a805..726af7b3b482 100644 --- a/models/user/email_address.go +++ b/models/user/email_address.go @@ -21,10 +21,8 @@ import ( "xorm.io/builder" ) -var ( - // ErrEmailNotActivated e-mail address has not been activated error - ErrEmailNotActivated = errors.New("E-mail address has not been activated") -) +// ErrEmailNotActivated e-mail address has not been activated error +var ErrEmailNotActivated = errors.New("E-mail address has not been activated") // ErrEmailInvalid represents an error where the email address does not comply with RFC 5322 type ErrEmailInvalid struct { diff --git a/modules/activitypub/keypair_test.go b/modules/activitypub/keypair_test.go index 5d876937b142..defe498614f0 100644 --- a/modules/activitypub/keypair_test.go +++ b/modules/activitypub/keypair_test.go @@ -26,7 +26,6 @@ func TestKeygen(t *testing.T) { assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv) assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub) - } func TestSignUsingKeys(t *testing.T) { diff --git a/modules/appstate/db.go b/modules/appstate/db.go index a594b01d850b..2538d1b5c8e1 100644 --- a/modules/appstate/db.go +++ b/modules/appstate/db.go @@ -12,8 +12,7 @@ import ( ) // DBStore can be used to store app state items in local filesystem -type DBStore struct { -} +type DBStore struct{} // Get reads the state item func (f *DBStore) Get(item StateItem) error { diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 931e5c7945e3..28546f603183 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -14,9 +14,11 @@ type testDiscoveredInfo struct{} func (s *testDiscoveredInfo) ClaimedID() string { return "claimedID" } + func (s *testDiscoveredInfo) OpEndpoint() string { return "opEndpoint" } + func (s *testDiscoveredInfo) OpLocalID() string { return "opLocalID" } @@ -25,7 +27,7 @@ func TestTimedDiscoveryCache(t *testing.T) { dc := newTimedDiscoveryCache(1 * time.Second) // Put some initial values - dc.Put("foo", &testDiscoveredInfo{}) //openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) + dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) // Make sure we can retrieve them if di := dc.Get("foo"); di == nil { diff --git a/modules/auth/openid/openid.go b/modules/auth/openid/openid.go index 40f38c2d2e71..8926fc6d7a20 100644 --- a/modules/auth/openid/openid.go +++ b/modules/auth/openid/openid.go @@ -17,8 +17,10 @@ import ( // If you have multiple servers for example, you may need to share at // least // the nonceStore between them. -var nonceStore = openid.NewSimpleNonceStore() -var discoveryCache = newTimedDiscoveryCache(24 * time.Hour) +var ( + nonceStore = openid.NewSimpleNonceStore() + discoveryCache = newTimedDiscoveryCache(24 * time.Hour) +) // Verify handles response from OpenID provider func Verify(fullURL string) (id string, err error) { diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index 73ecae0c2c29..30f13e440bb7 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -27,7 +27,6 @@ func Auth(serviceName, userName, passwd string) (string, error) { } return "", errors.New("Unrecognized PAM message style") }) - if err != nil { return "", err } diff --git a/modules/auth/webauthn/webauthn.go b/modules/auth/webauthn/webauthn.go index 8f380e7c3468..e39b6f46d6b1 100644 --- a/modules/auth/webauthn/webauthn.go +++ b/modules/auth/webauthn/webauthn.go @@ -17,10 +17,10 @@ import ( "github.com/duo-labs/webauthn/webauthn" ) -//WebAuthn represents the global WebAuthn instance +// WebAuthn represents the global WebAuthn instance var WebAuthn *webauthn.WebAuthn -//Init initializes the WebAuthn instance from the config. +// Init initializes the WebAuthn instance from the config. func Init() { gob.Register(&webauthn.SessionData{}) @@ -42,14 +42,14 @@ func Init() { // User represents an implementation of webauthn.User based on User model type User user_model.User -//WebAuthnID implements the webauthn.User interface +// WebAuthnID implements the webauthn.User interface func (u *User) WebAuthnID() []byte { id := make([]byte, 8) binary.PutVarint(id, u.ID) return id } -//WebAuthnName implements the webauthn.User interface +// WebAuthnName implements the webauthn.User interface func (u *User) WebAuthnName() string { if u.LoginName == "" { return u.Name @@ -57,17 +57,17 @@ func (u *User) WebAuthnName() string { return u.LoginName } -//WebAuthnDisplayName implements the webauthn.User interface +// WebAuthnDisplayName implements the webauthn.User interface func (u *User) WebAuthnDisplayName() string { return (*user_model.User)(u).DisplayName() } -//WebAuthnIcon implements the webauthn.User interface +// WebAuthnIcon implements the webauthn.User interface func (u *User) WebAuthnIcon() string { return (*user_model.User)(u).AvatarLink() } -//WebAuthnCredentials implementns the webauthn.User interface +// WebAuthnCredentials implementns the webauthn.User interface func (u *User) WebAuthnCredentials() []webauthn.Credential { dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ID) if err != nil { diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go index b958a9e23670..a2acc5443894 100644 --- a/modules/avatar/avatar_test.go +++ b/modules/avatar/avatar_test.go @@ -61,6 +61,7 @@ func Test_PrepareWithInvalidImage(t *testing.T) { _, err := Prepare([]byte{}) assert.EqualError(t, err, "DecodeConfig: image: unknown format") } + func Test_PrepareWithInvalidImageSize(t *testing.T) { setting.Avatar.MaxWidth = 5 setting.Avatar.MaxHeight = 5 diff --git a/modules/base/tool.go b/modules/base/tool.go index dff0d704209f..bf53a8ea8a8e 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -152,7 +152,7 @@ func PrettyNumber(v int64) string { func Subtract(left, right interface{}) interface{} { var rleft, rright int64 var fleft, fright float64 - var isInt = true + isInt := true switch v := left.(type) { case int: rleft = int64(v) diff --git a/modules/cache/cache.go b/modules/cache/cache.go index e7630638bf87..0198f8da7375 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -16,9 +16,7 @@ import ( _ "gitea.com/go-chi/cache/memcache" // memcache plugin for cache ) -var ( - conn mc.Cache -) +var conn mc.Cache func newCache(cacheConfig setting.Cache) (mc.Cache, error) { return mc.NewCacher(mc.Options{ diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index 92be69252dd5..f418f77e46ea 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -113,6 +113,7 @@ func TestGetInt(t *testing.T) { // TODO: uncommented code works in IDE but not with go test } + func TestGetInt64(t *testing.T) { createTestCache() diff --git a/modules/charset/charset.go b/modules/charset/charset.go index ae5cf5aa1a4e..cf8aa0cb75e6 100644 --- a/modules/charset/charset.go +++ b/modules/charset/charset.go @@ -25,7 +25,7 @@ var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'} // ToUTF8WithFallbackReader detects the encoding of content and coverts to UTF-8 reader if possible func ToUTF8WithFallbackReader(rd io.Reader) io.Reader { - var buf = make([]byte, 2048) + buf := make([]byte, 2048) n, err := util.ReadAtMost(rd, buf) if err != nil { return io.MultiReader(bytes.NewReader(RemoveBOMIfPresent(buf[:n])), rd) diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 8957bf3c1cf6..8376a0698af8 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -56,36 +56,48 @@ func TestToUTF8WithErr(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // "áéíóú" - res, err = ToUTF8WithErr([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, - 0xc3, 0xba}) + res, err = ToUTF8WithErr([]byte{ + 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, + 0xc3, 0xba, + }) assert.NoError(t, err) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) // Japanese (Shift-JIS) // 日属秘ぞしちゅ。 - res, err = ToUTF8WithErr([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, - 0xBF, 0x82, 0xE3, 0x81, 0x42}) + res, err = ToUTF8WithErr([]byte{ + 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, + 0xBF, 0x82, 0xE3, 0x81, 0x42, + }) assert.NoError(t, err) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, []byte(res)) res, err = ToUTF8WithErr([]byte{0x00, 0x00, 0x00, 0x00}) @@ -108,10 +120,14 @@ func TestToUTF8WithFallback(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res) // "Hola, así cómo ños" - res = ToUTF8WithFallback([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73}) - assert.Equal(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, - 0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73}, res) + res = ToUTF8WithFallback([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, + }) + assert.Equal(t, []byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, + 0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73, + }, res) // "Hola, así cómo " minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20} @@ -127,8 +143,10 @@ func TestToUTF8WithFallback(t *testing.T) { // Japanese (Shift-JIS) // "日属秘ぞしちゅ。" res = ToUTF8WithFallback([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, res) res = ToUTF8WithFallback([]byte{0x00, 0x00, 0x00, 0x00}) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res) @@ -148,21 +166,29 @@ func TestToUTF8(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // BOM + "áéíóú" - res = ToUTF8(string([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, - 0xc3, 0xba})) + res = ToUTF8(string([]byte{ + 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, + 0xc3, 0xba, + })) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // Latin1 // Hola, así cómo ños - res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73})) - assert.Equal(t, []byte{0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63, - 0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73}, []byte(res)) + res = ToUTF8(string([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, + })) + assert.Equal(t, []byte{ + 0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63, + 0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73, + }, []byte(res)) // Latin1 // Hola, así cómo \x07ños - res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73})) + res = ToUTF8(string([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, + })) // Hola, bytesMustStartWith(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C}, []byte(res)) @@ -173,10 +199,14 @@ func TestToUTF8(t *testing.T) { // Japanese (Shift-JIS) // 日属秘ぞしちゅ。 - res = ToUTF8(string([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, - 0xBF, 0x82, 0xE3, 0x81, 0x42})) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, + res = ToUTF8(string([]byte{ + 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, + 0xBF, 0x82, 0xE3, 0x81, 0x42, + })) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, []byte(res)) res = ToUTF8("\x00\x00\x00\x00") @@ -216,8 +246,10 @@ func TestToUTF8DropErrors(t *testing.T) { // Japanese (Shift-JIS) // "日属秘ぞしちゅ。" res = ToUTF8DropErrors([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, res) res = ToUTF8DropErrors([]byte{0x00, 0x00, 0x00, 0x00}) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res) diff --git a/modules/context/api.go b/modules/context/api.go index dae6d23989f0..c825e487535f 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -56,29 +56,29 @@ type APIInvalidTopicsError struct { InvalidTopics []string `json:"invalidTopics"` } -//APIEmpty is an empty response +// APIEmpty is an empty response // swagger:response empty type APIEmpty struct{} -//APIForbiddenError is a forbidden error response +// APIForbiddenError is a forbidden error response // swagger:response forbidden type APIForbiddenError struct { APIError } -//APINotFound is a not found empty response +// APINotFound is a not found empty response // swagger:response notFound type APINotFound struct{} -//APIConflict is a conflict empty response +// APIConflict is a conflict empty response // swagger:response conflict type APIConflict struct{} -//APIRedirect is a redirect response +// APIRedirect is a redirect response // swagger:response redirect type APIRedirect struct{} -//APIString is a string response +// APIString is a string response // swagger:response string type APIString string @@ -269,13 +269,12 @@ func APIAuth(authMethod auth_service.Method) func(*APIContext) { // APIContexter returns apicontext as middleware func APIContexter() func(http.Handler) http.Handler { - var csrfOpts = getCsrfOpts() + csrfOpts := getCsrfOpts() return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var locale = middleware.Locale(w, req) - var ctx = APIContext{ + locale := middleware.Locale(w, req) + ctx := APIContext{ Context: &Context{ Resp: NewResponse(w), Data: map[string]interface{}{}, @@ -354,7 +353,7 @@ func ReferencesGitRepo(allowEmpty bool) func(ctx *APIContext) (cancel context.Ca // NotFound handles 404s for APIContext // String will replace message, errors will be added to a slice func (ctx *APIContext) NotFound(objs ...interface{}) { - var message = ctx.Tr("error.not_found") + message := ctx.Tr("error.not_found") var errors []string for _, obj := range objs { // Ignore nil diff --git a/modules/context/api_test.go b/modules/context/api_test.go index e7e3e230afec..323fdbd2cc9b 100644 --- a/modules/context/api_test.go +++ b/modules/context/api_test.go @@ -16,7 +16,7 @@ import ( func TestGenAPILinks(t *testing.T) { setting.AppURL = "http://localhost:3000/" - var kases = map[string][]string{ + kases := map[string][]string{ "api/v1/repos/jerrykan/example-repo/issues?state=all": { `; rel="next"`, `; rel="last"`, diff --git a/modules/context/captcha.go b/modules/context/captcha.go index b8540136a186..6117d3071335 100644 --- a/modules/context/captcha.go +++ b/modules/context/captcha.go @@ -13,8 +13,10 @@ import ( "gitea.com/go-chi/captcha" ) -var imageCaptchaOnce sync.Once -var cpt *captcha.Captcha +var ( + imageCaptchaOnce sync.Once + cpt *captcha.Captcha +) // GetImageCaptcha returns global image captcha func GetImageCaptcha() *captcha.Captcha { diff --git a/modules/context/context.go b/modules/context/context.go index ab83ae4eb51a..998eafe965fc 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -362,7 +362,7 @@ func (ctx *Context) ServeStream(rd io.Reader, name string) { // Error returned an error to web browser func (ctx *Context) Error(status int, contents ...string) { - var v = http.StatusText(status) + v := http.StatusText(status) if len(contents) > 0 { v = contents[0] } @@ -606,16 +606,16 @@ func Auth(authMethod auth.Method) func(*Context) { // Contexter initializes a classic context for a request. func Contexter() func(next http.Handler) http.Handler { - var rnd = templates.HTMLRenderer() - var csrfOpts = getCsrfOpts() + rnd := templates.HTMLRenderer() + csrfOpts := getCsrfOpts() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - var locale = middleware.Locale(resp, req) - var startTime = time.Now() - var link = setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/") + locale := middleware.Locale(resp, req) + startTime := time.Now() + link := setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/") - var ctx = Context{ + ctx := Context{ Resp: NewResponse(resp), Cache: mc.GetCache(), Locale: locale, diff --git a/modules/context/csrf.go b/modules/context/csrf.go index 8d179ca90474..99c223c884da 100644 --- a/modules/context/csrf.go +++ b/modules/context/csrf.go @@ -57,9 +57,9 @@ type csrf struct { Form string // Cookie name value for setting and getting csrf token. Cookie string - //Cookie domain + // Cookie domain CookieDomain string - //Cookie path + // Cookie path CookiePath string // Cookie HttpOnly flag value used for the csrf token. CookieHTTPOnly bool diff --git a/modules/context/private.go b/modules/context/private.go index 3e31a7e7d89f..6e5ef1bd121c 100644 --- a/modules/context/private.go +++ b/modules/context/private.go @@ -44,9 +44,7 @@ func (ctx *PrivateContext) Err() error { return ctx.Req.Context().Err() } -var ( - privateContextKey interface{} = "default_private_context" -) +var privateContextKey interface{} = "default_private_context" // WithPrivateContext set up private context in request func WithPrivateContext(req *http.Request, ctx *PrivateContext) *http.Request { diff --git a/modules/context/repo.go b/modules/context/repo.go index 4acb800b64ff..97b417ffd165 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -111,7 +111,6 @@ type CanCommitToBranchResults struct { // and branch is not protected for push func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error) { protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName) - if err != nil { return CanCommitToBranchResults{}, err } diff --git a/modules/context/response.go b/modules/context/response.go index a20fc63536e0..112964dbe14c 100644 --- a/modules/context/response.go +++ b/modules/context/response.go @@ -17,9 +17,7 @@ type ResponseWriter interface { Size() int } -var ( - _ ResponseWriter = &Response{} -) +var _ ResponseWriter = &Response{} // Response represents a response type Response struct { diff --git a/modules/convert/notification.go b/modules/convert/notification.go index a0bd4cdc2728..f304eadf695c 100644 --- a/modules/convert/notification.go +++ b/modules/convert/notification.go @@ -22,12 +22,12 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread { URL: n.APIURL(), } - //since user only get notifications when he has access to use minimal access mode + // since user only get notifications when he has access to use minimal access mode if n.Repository != nil { result.Repository = ToRepo(n.Repository, perm.AccessModeRead) } - //handle Subject + // handle Subject switch n.Source { case models.NotificationSourceIssue: result.Subject = &api.NotificationSubject{Type: api.NotifySubjectIssue} @@ -83,7 +83,7 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread { // ToNotifications convert list of Notification to api.NotificationThread list func ToNotifications(nl models.NotificationList) []*api.NotificationThread { - var result = make([]*api.NotificationThread, 0, len(nl)) + result := make([]*api.NotificationThread, 0, len(nl)) for _, n := range nl { result = append(result, ToNotificationThread(n)) } diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index 5351b5e17250..8574ccfd26b0 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -18,7 +18,7 @@ import ( ) func TestPullRequest_APIFormat(t *testing.T) { - //with HeadRepo + // with HeadRepo assert.NoError(t, unittest.PrepareTestDatabase()) headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) @@ -34,7 +34,7 @@ func TestPullRequest_APIFormat(t *testing.T) { Repository: ToRepo(headRepo, perm.AccessModeRead), }, apiPullRequest.Head) - //withOut HeadRepo + // withOut HeadRepo pr = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadAttributes()) diff --git a/modules/convert/repository.go b/modules/convert/repository.go index 459f98f396c7..a35692553960 100644 --- a/modules/convert/repository.go +++ b/modules/convert/repository.go @@ -40,7 +40,7 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo } } - //check enabled/disabled units + // check enabled/disabled units hasIssues := false var externalTracker *api.ExternalTracker var internalTracker *api.InternalTracker diff --git a/modules/convert/status.go b/modules/convert/status.go index eb77c14dab33..1ac2a0f3e1a2 100644 --- a/modules/convert/status.go +++ b/modules/convert/status.go @@ -33,7 +33,6 @@ func ToCommitStatus(status *models.CommitStatus) *api.CommitStatus { // ToCombinedStatus converts List of CommitStatus to a CombinedStatus func ToCombinedStatus(statuses []*models.CommitStatus, repo *api.Repository) *api.CombinedStatus { - if len(statuses) == 0 { return nil } diff --git a/modules/csv/csv.go b/modules/csv/csv.go index 47ea62699df7..0dd54271f143 100644 --- a/modules/csv/csv.go +++ b/modules/csv/csv.go @@ -17,8 +17,10 @@ import ( "code.gitea.io/gitea/modules/util" ) -const maxLines = 10 -const guessSampleSize = 1e4 // 10k +const ( + maxLines = 10 + guessSampleSize = 1e4 // 10k +) // CreateReader creates a csv.Reader with the given delimiter. func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader { @@ -35,7 +37,7 @@ func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader { // CreateReaderAndDetermineDelimiter tries to guess the field delimiter from the content and creates a csv.Reader. // Reads at most guessSampleSize bytes. func CreateReaderAndDetermineDelimiter(ctx *markup.RenderContext, rd io.Reader) (*stdcsv.Reader, error) { - var data = make([]byte, guessSampleSize) + data := make([]byte, guessSampleSize) size, err := util.ReadAtMost(rd, data) if err != nil { return nil, err diff --git a/modules/csv/csv_test.go b/modules/csv/csv_test.go index 41c4ddaee22a..b1e928ae99c4 100644 --- a/modules/csv/csv_test.go +++ b/modules/csv/csv_test.go @@ -31,7 +31,7 @@ func decodeSlashes(t *testing.T, s string) string { } func TestCreateReaderAndDetermineDelimiter(t *testing.T) { - var cases = []struct { + cases := []struct { csv string expectedRows [][]string expectedDelimiter rune @@ -135,7 +135,7 @@ func TestDetermineDelimiterReadAllError(t *testing.T) { } func TestDetermineDelimiter(t *testing.T) { - var cases = []struct { + cases := []struct { csv string filename string expectedDelimiter rune @@ -236,7 +236,7 @@ John Doe john@doe.com This,note,had,a,lot,of,commas,to,test,delimiters`, } func TestRemoveQuotedString(t *testing.T) { - var cases = []struct { + cases := []struct { text string expectedText string }{ @@ -301,7 +301,7 @@ abc | |123 } func TestGuessDelimiter(t *testing.T) { - var cases = []struct { + cases := []struct { csv string expectedDelimiter rune }{ @@ -456,7 +456,7 @@ jkl`, } func TestGuessFromBeforeAfterQuotes(t *testing.T) { - var cases = []struct { + cases := []struct { csv string expectedDelimiter rune }{ @@ -562,7 +562,7 @@ func (l mockLocale) TrN(_cnt interface{}, key1, _keyN string, _args ...interface } func TestFormatError(t *testing.T) { - var cases = []struct { + cases := []struct { err error expectedMessage string expectsError bool diff --git a/modules/doctor/fix16961.go b/modules/doctor/fix16961.go index b929616b380f..e24183806842 100644 --- a/modules/doctor/fix16961.go +++ b/modules/doctor/fix16961.go @@ -296,7 +296,6 @@ func fixBrokenRepoUnits16961(ctx context.Context, logger log.Logger, autofix boo return repo_model.UpdateRepoUnit(repoUnit) }, ) - if err != nil { logger.Critical("Unable to iterate across repounits to fix the broken units: Error %v", err) return err diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index cb302c9c5b29..ec2fec20b374 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -119,7 +119,6 @@ func checkEnablePushOptions(ctx context.Context, logger log.Logger, autofix bool logger.Info("Enabled push options for %d repositories.", numRepos) } else { logger.Info("Checked %d repositories, %d need updates.", numRepos, numNeedUpdate) - } return nil diff --git a/modules/doctor/paths.go b/modules/doctor/paths.go index 623df863cb8c..22c095c2279b 100644 --- a/modules/doctor/paths.go +++ b/modules/doctor/paths.go @@ -27,7 +27,7 @@ func checkConfigurationFile(logger log.Logger, autofix bool, fileOpts configurat fi, err := os.Stat(fileOpts.Path) if err != nil { if os.IsNotExist(err) && autofix && fileOpts.IsDirectory { - if err := os.MkdirAll(fileOpts.Path, 0777); err != nil { + if err := os.MkdirAll(fileOpts.Path, 0o777); err != nil { logger.Error(" Directory does not exist and could not be created. ERROR: %v", err) return fmt.Errorf("Configuration directory: \"%q\" does not exist and could not be created. ERROR: %v", fileOpts.Path, err) } diff --git a/modules/emoji/emoji.go b/modules/emoji/emoji.go index 85df2d697307..89a86a7f3e6b 100644 --- a/modules/emoji/emoji.go +++ b/modules/emoji/emoji.go @@ -44,9 +44,7 @@ var ( ) func loadMap() { - once.Do(func() { - // initialize codeMap = make(map[string]int, len(GemojiData)) aliasMap = make(map[string]int, len(GemojiData)) @@ -87,7 +85,6 @@ func loadMap() { codeReplacer = strings.NewReplacer(codePairs...) aliasReplacer = strings.NewReplacer(aliasPairs...) }) - } // FromCode retrieves the emoji data based on the provided unicode code (ie, diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 58d616a0385d..4e257178ef1e 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -14,7 +14,6 @@ import ( ) func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) { - maxLoops := 1000 // 'git --version' does not block so it must be finished before the timeout triggered. @@ -27,7 +26,6 @@ func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) { } func TestRunInDirTimeoutPipelineAlwaysTimeout(t *testing.T) { - maxLoops := 1000 // 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered. diff --git a/modules/git/commit.go b/modules/git/commit.go index 8a7865355300..0ba53897f5d5 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -36,7 +36,7 @@ type Commit struct { // CommitGPGSignature represents a git commit signature part. type CommitGPGSignature struct { Signature string - Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data + Payload string // TODO check if can be reconstruct from the rest of commit information to not have duplicate data } // Message returns the commit message. Same as retrieving CommitMessage directly. diff --git a/modules/git/commit_info_gogit.go b/modules/git/commit_info_gogit.go index ccf90fc8c7ef..ab6e73810367 100644 --- a/modules/git/commit_info_gogit.go +++ b/modules/git/commit_info_gogit.go @@ -158,7 +158,7 @@ func getFileHashes(c cgobject.CommitNode, treePath string, paths []string) (map[ func getLastCommitForPathsByCache(commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*object.Commit, []string, error) { var unHitEntryPaths []string - var results = make(map[string]*object.Commit) + results := make(map[string]*object.Commit) for _, p := range paths { lastCommit, err := cache.Get(commitID, path.Join(treePath, p)) if err != nil { diff --git a/modules/git/commit_info_nogogit.go b/modules/git/commit_info_nogogit.go index b58c1885b692..347ad7d05900 100644 --- a/modules/git/commit_info_nogogit.go +++ b/modules/git/commit_info_nogogit.go @@ -104,7 +104,7 @@ func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath string defer cancel() var unHitEntryPaths []string - var results = make(map[string]*Commit) + results := make(map[string]*Commit) for _, p := range paths { lastCommit, err := cache.Get(commitID, path.Join(treePath, p), wr, rd) if err != nil { diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go index a4c0483004df..4cc207de64e6 100644 --- a/modules/git/commit_info_test.go +++ b/modules/git/commit_info_test.go @@ -16,8 +16,10 @@ import ( "github.com/stretchr/testify/assert" ) -const testReposDir = "tests/repos/" -const benchmarkReposDir = "benchmark/repos/" +const ( + testReposDir = "tests/repos/" + benchmarkReposDir = "benchmark/repos/" +) func cloneRepo(url, dir, name string) (string, error) { repoDir := filepath.Join(dir, name) diff --git a/modules/git/commit_test.go b/modules/git/commit_test.go index 2b3365342d37..6e9dd34ea7fe 100644 --- a/modules/git/commit_test.go +++ b/modules/git/commit_test.go @@ -234,5 +234,4 @@ func TestParseCommitFileStatus(t *testing.T) { assert.Equal(t, kase.removed, fileStatus.Removed) assert.Equal(t, kase.modified, fileStatus.Modified) } - } diff --git a/modules/git/git.go b/modules/git/git.go index cca5ce6714f5..294d33f916bc 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -112,8 +112,8 @@ func SetExecutablePath(path string) error { // VersionInfo returns git version information func VersionInfo() string { - var format = "Git Version: %s" - var args = []interface{}{gitVersion.Original()} + format := "Git Version: %s" + args := []interface{}{gitVersion.Original()} // Since git wire protocol has been released from git v2.18 if setting.Git.EnableAutoGitWireProtocol && CheckGitVersionAtLeast("2.18") == nil { format += ", Wire Protocol %s Enabled" diff --git a/modules/git/hook.go b/modules/git/hook.go index ecd2db3cc3a1..c50f891224c8 100644 --- a/modules/git/hook.go +++ b/modules/git/hook.go @@ -23,10 +23,8 @@ var hookNames = []string{ "post-receive", } -var ( - // ErrNotValidHook error when a git hook is not valid - ErrNotValidHook = errors.New("not a valid Git hook") -) +// ErrNotValidHook error when a git hook is not valid +var ErrNotValidHook = errors.New("not a valid Git hook") // IsValidHookName returns true if given name is a valid Git hook. func IsValidHookName(name string) bool { @@ -142,5 +140,5 @@ func SetUpdateHook(repoPath, content string) (err error) { if err != nil { return err } - return os.WriteFile(hookPath, []byte(content), 0777) + return os.WriteFile(hookPath, []byte(content), 0o777) } diff --git a/modules/git/last_commit_cache_gogit.go b/modules/git/last_commit_cache_gogit.go index b57e9ad11ff0..06e85a6db2a6 100644 --- a/modules/git/last_commit_cache_gogit.go +++ b/modules/git/last_commit_cache_gogit.go @@ -64,7 +64,6 @@ func (c *LastCommitCache) Get(ref, entryPath string) (interface{}, error) { // CacheCommit will cache the commit from the gitRepository func (c *LastCommitCache) CacheCommit(ctx context.Context, commit *Commit) error { - commitNodeIndex, _ := commit.repo.CommitNodeIndex() index, err := commitNodeIndex.Get(commit.ID) diff --git a/modules/git/lfs.go b/modules/git/lfs.go index 79049c98245a..3a809d393d23 100644 --- a/modules/git/lfs.go +++ b/modules/git/lfs.go @@ -16,8 +16,8 @@ var once sync.Once // CheckLFSVersion will check lfs version, if not satisfied, then disable it. func CheckLFSVersion() { if setting.LFS.StartServer { - //Disable LFS client hooks if installed for the current OS user - //Needs at least git v2.1.2 + // Disable LFS client hooks if installed for the current OS user + // Needs at least git v2.1.2 err := LoadGitVersion() if err != nil { diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go index 5f58237de832..d6d6f3868c06 100644 --- a/modules/git/parse_nogogit_test.go +++ b/modules/git/parse_nogogit_test.go @@ -14,7 +14,6 @@ import ( ) func TestParseTreeEntries(t *testing.T) { - testCases := []struct { Input string Expected []*TreeEntry diff --git a/modules/git/repo.go b/modules/git/repo.go index 591ef7362b1d..6368c6459b50 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -146,7 +146,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo opts.Timeout = -1 } - var envs = os.Environ() + envs := os.Environ() u, err := url.Parse(from) if err == nil && (strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")) { if proxy.Match(u.Host) { @@ -154,7 +154,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo } } - var stderr = new(bytes.Buffer) + stderr := new(bytes.Buffer) if err = cmd.RunWithContext(&RunContext{ Timeout: opts.Timeout, Env: envs, diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index 0bb550bb4b89..d12f0b1099f3 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -87,7 +87,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[ return nil, fmt.Errorf("wrong number of fields in return from check-attr") } - var name2attribute2info = make(map[string]map[string]string) + name2attribute2info := make(map[string]map[string]string) for i := 0; i < (len(fields) / 3); i++ { filename := string(fields[3*i]) diff --git a/modules/git/repo_attribute_test.go b/modules/git/repo_attribute_test.go index 92d1a78fa4da..901a0aa2447a 100644 --- a/modules/git/repo_attribute_test.go +++ b/modules/git/repo_attribute_test.go @@ -45,7 +45,7 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) { assert.Fail(t, "took too long to read an attribute from the list") } - //Write a partial attribute + // Write a partial attribute _, err = wr.Write([]byte("incomplete-file")) assert.NoError(t, err) _, err = wr.Write([]byte("name\x00")) @@ -133,7 +133,7 @@ func Test_lineSeparatedAttributeWriter_ReadAttribute(t *testing.T) { assert.Fail(t, "took too long to read an attribute from the list") } - //Write a partial attribute + // Write a partial attribute _, err = wr.Write([]byte("incomplete-file")) assert.NoError(t, err) _, err = wr.Write([]byte("name: ")) diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index ed04ee2f670d..0423f1578623 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -88,7 +88,6 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) { stdout, err := NewCommandContext(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize), "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { return nil, err } diff --git a/modules/git/repo_commit_test.go b/modules/git/repo_commit_test.go index 594333484369..232d6a218c5d 100644 --- a/modules/git/repo_commit_test.go +++ b/modules/git/repo_commit_test.go @@ -90,9 +90,9 @@ func TestRepository_CommitsBetweenIDs(t *testing.T) { NewID string ExpectedCommits int }{ - {"fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", "78a445db1eac62fe15e624e1137965969addf344", 1}, //com1 -> com2 - {"78a445db1eac62fe15e624e1137965969addf344", "fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", 0}, //reset HEAD~, com2 -> com1 - {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, //com2 -> com2_new + {"fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", "78a445db1eac62fe15e624e1137965969addf344", 1}, // com1 -> com2 + {"78a445db1eac62fe15e624e1137965969addf344", "fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", 0}, // reset HEAD~, com2 -> com1 + {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, // com2 -> com2_new } for i, c := range cases { commits, err := bareRepo1.CommitsBetweenIDs(c.NewID, c.OldID) diff --git a/modules/git/repo_language_stats.go b/modules/git/repo_language_stats.go index ac23caa0fc04..daeb4b591f5b 100644 --- a/modules/git/repo_language_stats.go +++ b/modules/git/repo_language_stats.go @@ -4,5 +4,7 @@ package git -const fileSizeLimit int64 = 16 * 1024 // 16 KiB -const bigFileSize int64 = 1024 * 1024 // 1 MiB +const ( + fileSizeLimit int64 = 16 * 1024 // 16 KiB + bigFileSize int64 = 1024 * 1024 // 1 MiB +) diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index 3921e6a1d41c..1d08c6bf79ab 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -46,7 +46,6 @@ func (repo *Repository) hashObject(reader io.Reader) (string, error) { stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) err := cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, reader) - if err != nil { return "", err } diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 6b5dbeef4823..9d1e47a49751 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -174,7 +174,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { tagNames = util.PaginateSlice(tagNames, page, pageSize).([]string) } - var tags = make([]*Tag, 0, len(tagNames)) + tags := make([]*Tag, 0, len(tagNames)) for _, tagName := range tagNames { tagName = strings.TrimSpace(tagName) if len(tagName) == 0 { diff --git a/modules/git/submodule_test.go b/modules/git/submodule_test.go index ff8dc579f6d5..653f0a6f084c 100644 --- a/modules/git/submodule_test.go +++ b/modules/git/submodule_test.go @@ -11,7 +11,7 @@ import ( ) func TestGetRefURL(t *testing.T) { - var kases = []struct { + kases := []struct { refURL string prefixURL string parentPath string diff --git a/modules/git/tag.go b/modules/git/tag.go index 71dd866a18bb..3482f81e900d 100644 --- a/modules/git/tag.go +++ b/modules/git/tag.go @@ -10,8 +10,10 @@ import ( "strings" ) -const beginpgp = "\n-----BEGIN PGP SIGNATURE-----\n" -const endpgp = "\n-----END PGP SIGNATURE-----" +const ( + beginpgp = "\n-----BEGIN PGP SIGNATURE-----\n" + endpgp = "\n-----END PGP SIGNATURE-----" +) // Tag represents a Git tag. type Tag struct { diff --git a/modules/git/tree_blob_gogit.go b/modules/git/tree_blob_gogit.go index a8d619cd18ed..be7cb33d353a 100644 --- a/modules/git/tree_blob_gogit.go +++ b/modules/git/tree_blob_gogit.go @@ -22,7 +22,7 @@ func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { if len(relpath) == 0 { return &TreeEntry{ ID: t.ID, - //Type: ObjectTree, + // Type: ObjectTree, gogitTreeEntry: &object.TreeEntry{ Name: "", Mode: filemode.Dir, diff --git a/modules/git/tree_entry_mode.go b/modules/git/tree_entry_mode.go index b029c6fc476f..d999ccc02a81 100644 --- a/modules/git/tree_entry_mode.go +++ b/modules/git/tree_entry_mode.go @@ -13,15 +13,15 @@ type EntryMode int // one of these. const ( // EntryModeBlob - EntryModeBlob EntryMode = 0100644 + EntryModeBlob EntryMode = 0o100644 // EntryModeExec - EntryModeExec EntryMode = 0100755 + EntryModeExec EntryMode = 0o100755 // EntryModeSymlink - EntryModeSymlink EntryMode = 0120000 + EntryModeSymlink EntryMode = 0o120000 // EntryModeCommit - EntryModeCommit EntryMode = 0160000 + EntryModeCommit EntryMode = 0o160000 // EntryModeTree - EntryModeTree EntryMode = 0040000 + EntryModeTree EntryMode = 0o040000 ) // String converts an EntryMode to a string diff --git a/modules/gitgraph/graph_test.go b/modules/gitgraph/graph_test.go index c805ff464767..e7173b521cc8 100644 --- a/modules/gitgraph/graph_test.go +++ b/modules/gitgraph/graph_test.go @@ -14,7 +14,6 @@ import ( ) func BenchmarkGetCommitGraph(b *testing.B) { - currentRepo, err := git.OpenRepository(".") if err != nil || currentRepo == nil { b.Error("Could not open repository") @@ -255,7 +254,6 @@ func TestCommitStringParsing(t *testing.T) { } for _, test := range tests { - t.Run(test.testName, func(t *testing.T) { testString := fmt.Sprintf("%s%s", dataFirstPart, test.commitMessage) idx := strings.Index(testString, "DATA:") diff --git a/modules/gitgraph/parser.go b/modules/gitgraph/parser.go index 62e05056520f..5432962784f0 100644 --- a/modules/gitgraph/parser.go +++ b/modules/gitgraph/parser.go @@ -144,7 +144,6 @@ func (parser *Parser) releaseUnusedColors() { // ParseGlyphs parses the provided glyphs and sets the internal state func (parser *Parser) ParseGlyphs(glyphs []byte) { - // Clean state for parsing this row parser.glyphs, parser.oldGlyphs = parser.oldGlyphs, parser.glyphs parser.glyphs = parser.glyphs[0:0] diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 8c3b95c4aa74..031c10d41ba4 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -190,6 +190,7 @@ func (g *Manager) RunAtHammer(hammer func()) { hammer() }) } + func (g *Manager) doShutdown() { if !g.setStateTransition(stateRunning, stateShuttingDown) { return diff --git a/modules/highlight/highlight.go b/modules/highlight/highlight.go index 04bd30bcebf5..344be78144ec 100644 --- a/modules/highlight/highlight.go +++ b/modules/highlight/highlight.go @@ -83,7 +83,7 @@ func Code(fileName, language, code string) string { if lexer == nil { if val, ok := highlightMapping[filepath.Ext(fileName)]; ok { - //use mapped value to find lexer + // use mapped value to find lexer lexer = lexers.Get(val) } } @@ -198,7 +198,7 @@ func File(numLines int, fileName, language string, code []byte) []string { m := make([]string, 0, numLines) for _, v := range strings.SplitN(htmlbuf.String(), "\n", numLines) { content := string(v) - //need to keep lines that are only \n so copy/paste works properly in browser + // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } else if content == `` { @@ -220,7 +220,7 @@ func plainText(code string, numLines int) []string { m := make([]string, 0, numLines) for _, v := range strings.SplitN(string(code), "\n", numLines) { content := string(v) - //need to keep lines that are only \n so copy/paste works properly in browser + // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } diff --git a/modules/httpcache/httpcache_test.go b/modules/httpcache/httpcache_test.go index 68ac892c91e7..49e54d147e71 100644 --- a/modules/httpcache/httpcache_test.go +++ b/modules/httpcache/httpcache_test.go @@ -15,8 +15,7 @@ import ( "github.com/stretchr/testify/assert" ) -type mockFileInfo struct { -} +type mockFileInfo struct{} func (m mockFileInfo) Name() string { return "gitea.test" } func (m mockFileInfo) Size() int64 { return int64(10) } diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 64e974dc1850..cfadcfebd8a2 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -38,8 +38,10 @@ import ( "github.com/go-enry/go-enry/v2" ) -const unicodeNormalizeName = "unicodeNormalize" -const maxBatchSize = 16 +const ( + unicodeNormalizeName = "unicodeNormalize" + maxBatchSize = 16 +) // numericEqualityQuery a numeric equality query for the given value and field func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery { @@ -158,9 +160,7 @@ func createBleveIndexer(path string, latestVersion int) (bleve.Index, error) { return indexer, nil } -var ( - _ Indexer = &BleveIndexer{} -) +var _ Indexer = &BleveIndexer{} // BleveIndexer represents a bleve indexer implementation type BleveIndexer struct { @@ -337,7 +337,7 @@ func (b *BleveIndexer) Search(repoIDs []int64, language, keyword string, page, p } if len(repoIDs) > 0 { - var repoQueries = make([]query.Query, 0, len(repoIDs)) + repoQueries := make([]query.Query, 0, len(repoIDs)) for _, repoID := range repoIDs { repoQueries = append(repoQueries, numericEqualityQuery(repoID, "RepoID")) } diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index eb57d4d68a6f..9bd2fa301e87 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -35,9 +35,7 @@ const ( esMultiMatchTypePhrasePrefix = "phrase_prefix" ) -var ( - _ Indexer = &ElasticSearchIndexer{} -) +var _ Indexer = &ElasticSearchIndexer{} // ElasticSearchIndexer implements Indexer interface type ElasticSearchIndexer struct { @@ -131,7 +129,7 @@ func (b *ElasticSearchIndexer) init() (bool, error) { return false, err } if !exists { - var mapping = defaultMapping + mapping := defaultMapping createIndex, err := b.client.CreateIndex(b.realIndexerName()).BodyString(mapping).Do(ctx) if err != nil { @@ -327,7 +325,7 @@ func convertResult(searchResult *elastic.SearchResult, kw string, pageSize int) } repoID, fileName := parseIndexerID(hit.Id) - var res = make(map[string]interface{}) + res := make(map[string]interface{}) if err := json.Unmarshal(hit.Source, &res); err != nil { return 0, nil, nil, err } @@ -378,7 +376,7 @@ func (b *ElasticSearchIndexer) Search(repoIDs []int64, language, keyword string, query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - var repoStrs = make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]interface{}, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 247354054c64..ae73f5690d2a 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -73,7 +73,7 @@ func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) { if err != nil { return nil, err } - var idxCount = 0 + idxCount := 0 updates := make([]fileUpdate, len(entries)) for _, entry := range entries { if isIndexable(entry) { diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index a17484cae576..4c7a1d4f177c 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -78,9 +78,7 @@ type IndexerData struct { RepoID int64 } -var ( - indexerQueue queue.UniqueQueue -) +var indexerQueue queue.UniqueQueue func index(ctx context.Context, indexer Indexer, repoID int64) error { repo, err := repo_model.GetRepositoryByID(repoID) diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 71d58c08c530..0f9915c84b7b 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -25,45 +25,43 @@ func testIndexer(name string, t *testing.T, indexer Indexer) { var repoID int64 = 1 err := index(git.DefaultContext, indexer, repoID) assert.NoError(t, err) - var ( - keywords = []struct { - RepoIDs []int64 - Keyword string - IDs []int64 - Langs int - }{ - { - RepoIDs: nil, - Keyword: "Description", - IDs: []int64{repoID}, - Langs: 1, - }, - { - RepoIDs: []int64{2}, - Keyword: "Description", - IDs: []int64{}, - Langs: 0, - }, - { - RepoIDs: nil, - Keyword: "repo1", - IDs: []int64{repoID}, - Langs: 1, - }, - { - RepoIDs: []int64{2}, - Keyword: "repo1", - IDs: []int64{}, - Langs: 0, - }, - { - RepoIDs: nil, - Keyword: "non-exist", - IDs: []int64{}, - Langs: 0, - }, - } - ) + keywords := []struct { + RepoIDs []int64 + Keyword string + IDs []int64 + Langs int + }{ + { + RepoIDs: nil, + Keyword: "Description", + IDs: []int64{repoID}, + Langs: 1, + }, + { + RepoIDs: []int64{2}, + Keyword: "Description", + IDs: []int64{}, + Langs: 0, + }, + { + RepoIDs: nil, + Keyword: "repo1", + IDs: []int64{repoID}, + Langs: 1, + }, + { + RepoIDs: []int64{2}, + Keyword: "repo1", + IDs: []int64{}, + Langs: 0, + }, + { + RepoIDs: nil, + Keyword: "non-exist", + IDs: []int64{}, + Langs: 0, + }, + } for _, kw := range keywords { t.Run(kw.Keyword, func(t *testing.T) { @@ -72,7 +70,7 @@ func testIndexer(name string, t *testing.T, indexer Indexer) { assert.EqualValues(t, len(kw.IDs), total) assert.Len(t, langs, kw.Langs) - var ids = make([]int64, 0, len(res)) + ids := make([]int64, 0, len(res)) for _, hit := range res { ids = append(ids, hit.RepoID) assert.EqualValues(t, "# repo1\n\nDescription for repo1", hit.Content) diff --git a/modules/indexer/code/wrapped.go b/modules/indexer/code/wrapped.go index e7b5b89eefc7..56baadd6fc6f 100644 --- a/modules/indexer/code/wrapped.go +++ b/modules/indexer/code/wrapped.go @@ -12,9 +12,7 @@ import ( repo_model "code.gitea.io/gitea/models/repo" ) -var ( - indexer = newWrappedIndexer() -) +var indexer = newWrappedIndexer() // ErrWrappedIndexerClosed is the error returned if the indexer was closed before it was ready var ErrWrappedIndexerClosed = fmt.Errorf("Indexer closed before ready") @@ -80,7 +78,6 @@ func (w *wrappedIndexer) Search(repoIDs []int64, language, keyword string, page, return 0, nil, nil, err } return indexer.Search(repoIDs, language, keyword, page, pageSize, isMatch) - } func (w *wrappedIndexer) Close() { diff --git a/modules/indexer/issues/bleve.go b/modules/indexer/issues/bleve.go index db12874e84e5..d986a0e55ef9 100644 --- a/modules/indexer/issues/bleve.go +++ b/modules/indexer/issues/bleve.go @@ -156,9 +156,7 @@ func createIssueIndexer(path string, latestVersion int) (bleve.Index, error) { return index, nil } -var ( - _ Indexer = &BleveIndexer{} -) +var _ Indexer = &BleveIndexer{} // BleveIndexer implements Indexer interface type BleveIndexer struct { @@ -256,7 +254,7 @@ func (b *BleveIndexer) Search(keyword string, repoIDs []int64, limit, start int) return nil, err } - var ret = SearchResult{ + ret := SearchResult{ Hits: make([]Match, 0, len(result.Hits)), } for _, hit := range result.Hits { diff --git a/modules/indexer/issues/bleve_test.go b/modules/indexer/issues/bleve_test.go index 036b318d85c2..df036fb57337 100644 --- a/modules/indexer/issues/bleve_test.go +++ b/modules/indexer/issues/bleve_test.go @@ -53,43 +53,41 @@ func TestBleveIndexAndSearch(t *testing.T) { }) assert.NoError(t, err) - var ( - keywords = []struct { - Keyword string - IDs []int64 - }{ - { - Keyword: "search", - IDs: []int64{1}, - }, - { - Keyword: "test1", - IDs: []int64{1}, - }, - { - Keyword: "test2", - IDs: []int64{1}, - }, - { - Keyword: "support", - IDs: []int64{1, 2}, - }, - { - Keyword: "chinese", - IDs: []int64{1, 2}, - }, - { - Keyword: "help", - IDs: []int64{}, - }, - } - ) + keywords := []struct { + Keyword string + IDs []int64 + }{ + { + Keyword: "search", + IDs: []int64{1}, + }, + { + Keyword: "test1", + IDs: []int64{1}, + }, + { + Keyword: "test2", + IDs: []int64{1}, + }, + { + Keyword: "support", + IDs: []int64{1, 2}, + }, + { + Keyword: "chinese", + IDs: []int64{1, 2}, + }, + { + Keyword: "help", + IDs: []int64{}, + }, + } for _, kw := range keywords { res, err := indexer.Search(kw.Keyword, []int64{2}, 10, 0) assert.NoError(t, err) - var ids = make([]int64, 0, len(res.Hits)) + ids := make([]int64, 0, len(res.Hits)) for _, hit := range res.Hits { ids = append(ids, hit.ID) } diff --git a/modules/indexer/issues/db.go b/modules/indexer/issues/db.go index d0cca4fd1808..f02cbddce8fb 100644 --- a/modules/indexer/issues/db.go +++ b/modules/indexer/issues/db.go @@ -7,8 +7,7 @@ package issues import "code.gitea.io/gitea/models" // DBIndexer implements Indexer interface to use database's like search -type DBIndexer struct { -} +type DBIndexer struct{} // Init dummy function func (db *DBIndexer) Init() (bool, error) { @@ -35,7 +34,7 @@ func (db *DBIndexer) Search(kw string, repoIDs []int64, limit, start int) (*Sear if err != nil { return nil, err } - var result = SearchResult{ + result := SearchResult{ Total: total, Hits: make([]Match, 0, limit), } diff --git a/modules/indexer/issues/elastic_search.go b/modules/indexer/issues/elastic_search.go index 3af64ed30e53..187b69b74946 100644 --- a/modules/indexer/issues/elastic_search.go +++ b/modules/indexer/issues/elastic_search.go @@ -16,9 +16,7 @@ import ( "github.com/olivere/elastic/v7" ) -var ( - _ Indexer = &ElasticSearchIndexer{} -) +var _ Indexer = &ElasticSearchIndexer{} // ElasticSearchIndexer implements Indexer interface type ElasticSearchIndexer struct { @@ -102,7 +100,7 @@ func (b *ElasticSearchIndexer) Init() (bool, error) { } if !exists { - var mapping = defaultMapping + mapping := defaultMapping createIndex, err := b.client.CreateIndex(b.indexerName).BodyString(mapping).Do(ctx) if err != nil { @@ -195,7 +193,7 @@ func (b *ElasticSearchIndexer) Search(keyword string, repoIDs []int64, limit, st query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - var repoStrs = make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]interface{}, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index ba35e37fd872..ee6ebcdd18b9 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -71,7 +71,6 @@ func TestBleveSearchIssues(t *testing.T) { ids, err = SearchIssuesByKeyword([]int64{1}, "good") assert.NoError(t, err) assert.EqualValues(t, []int64{1}, ids) - } func TestDBSearchIssues(t *testing.T) { diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go index 9d2942a266a9..e425b95d2092 100644 --- a/modules/indexer/stats/db.go +++ b/modules/indexer/stats/db.go @@ -15,8 +15,7 @@ import ( ) // DBIndexer implements Indexer interface to use database's like search -type DBIndexer struct { -} +type DBIndexer struct{} // Index repository status function func (db *DBIndexer) Index(id int64) error { diff --git a/modules/lfs/endpoint_test.go b/modules/lfs/endpoint_test.go index a7e8b1bfb7db..69f476865031 100644 --- a/modules/lfs/endpoint_test.go +++ b/modules/lfs/endpoint_test.go @@ -18,7 +18,7 @@ func str2url(raw string) *url.URL { func TestDetermineEndpoint(t *testing.T) { // Test cases - var cases = []struct { + cases := []struct { cloneurl string lfsurl string expected *url.URL diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go index 5b514a1230d7..0ffe663da58e 100644 --- a/modules/lfs/http_client_test.go +++ b/modules/lfs/http_client_test.go @@ -23,8 +23,7 @@ func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req), nil } -type DummyTransferAdapter struct { -} +type DummyTransferAdapter struct{} func (a *DummyTransferAdapter) Name() string { return "dummy" @@ -172,7 +171,7 @@ func TestHTTPClientDownload(t *testing.T) { })} dummy := &DummyTransferAdapter{} - var cases = []struct { + cases := []struct { endpoint string expectederror string }{ @@ -279,7 +278,7 @@ func TestHTTPClientUpload(t *testing.T) { })} dummy := &DummyTransferAdapter{} - var cases = []struct { + cases := []struct { endpoint string expectederror string }{ diff --git a/modules/lfs/pointer_scanner_gogit.go b/modules/lfs/pointer_scanner_gogit.go index 7e8b812f466d..b4ba6fc1335f 100644 --- a/modules/lfs/pointer_scanner_gogit.go +++ b/modules/lfs/pointer_scanner_gogit.go @@ -51,7 +51,6 @@ func SearchPointerBlobs(ctx context.Context, repo *git.Repository, pointerChan c return nil }) }() - if err != nil { select { case <-ctx.Done(): diff --git a/modules/log/colors.go b/modules/log/colors.go index ad3120ee6ccf..15e23a0dac21 100644 --- a/modules/log/colors.go +++ b/modules/log/colors.go @@ -169,10 +169,12 @@ var levelToColor = map[Level][]byte{ NONE: ColorBytes(Reset), } -var resetBytes = ColorBytes(Reset) -var fgCyanBytes = ColorBytes(FgCyan) -var fgGreenBytes = ColorBytes(FgGreen) -var fgBoldBytes = ColorBytes(Bold) +var ( + resetBytes = ColorBytes(Reset) + fgCyanBytes = ColorBytes(FgCyan) + fgGreenBytes = ColorBytes(FgGreen) + fgBoldBytes = ColorBytes(Bold) +) type protectedANSIWriterMode int @@ -335,7 +337,6 @@ func NewColoredValuePointer(value *interface{}, color ...ColorAttribute) *Colore resetBytes: &resetBytes, Value: value, } - } // NewColoredValueBytes creates a value from the provided value with color bytes diff --git a/modules/log/conn_test.go b/modules/log/conn_test.go index 158a8ca6cee6..1d373506a406 100644 --- a/modules/log/conn_test.go +++ b/modules/log/conn_test.go @@ -135,7 +135,7 @@ func TestConnLoggerFailConnect(t *testing.T) { date := time.Date(2019, time.January, 13, 22, 3, 30, 15, location) - //dateString := date.UTC().Format("2006/01/02 15:04:05") + // dateString := date.UTC().Format("2006/01/02 15:04:05") event := Event{ level: INFO, @@ -224,7 +224,6 @@ func TestConnLoggerClose(t *testing.T) { err := logger.LogEvent(&event) assert.NoError(t, err) logger.Close() - }() wg.Wait() logger.Flush() diff --git a/modules/log/file.go b/modules/log/file.go index bc9d7417246c..7dc77c094265 100644 --- a/modules/log/file.go +++ b/modules/log/file.go @@ -76,7 +76,7 @@ func (mw *MuxWriter) SetFd(fd *os.File) { func NewFileLogger() LoggerProvider { log := &FileLogger{ Filename: "", - Maxsize: 1 << 28, //256 MB + Maxsize: 1 << 28, // 256 MB Daily: true, Maxdays: 7, Rotate: true, @@ -137,7 +137,7 @@ func (log *FileLogger) docheck(size int) { func (log *FileLogger) createLogFile() (*os.File, error) { // Open the log file - return os.OpenFile(log.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) + return os.OpenFile(log.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o660) } func (log *FileLogger) initFd() error { @@ -202,7 +202,7 @@ func compressOldLogFile(fname string, compressionLevel int) error { } defer reader.Close() buffer := bufio.NewReader(reader) - fw, err := os.OpenFile(fname+".gz", os.O_WRONLY|os.O_CREATE, 0660) + fw, err := os.OpenFile(fname+".gz", os.O_WRONLY|os.O_CREATE, 0o660) if err != nil { return err } @@ -234,7 +234,6 @@ func (log *FileLogger) deleteOldLog() { if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*log.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(log.Filename)) { - if err := util.Remove(path); err != nil { returnErr = fmt.Errorf("Failed to remove %s: %v", path, err) } diff --git a/modules/log/file_test.go b/modules/log/file_test.go index 09a07b1e2753..c3074b69df9e 100644 --- a/modules/log/file_test.go +++ b/modules/log/file_test.go @@ -27,11 +27,11 @@ func TestFileLoggerFails(t *testing.T) { prefix := "TestPrefix " level := INFO flags := LstdFlags | LUTC | Lfuncname - //filename := filepath.Join(tmpDir, "test.log") + // filename := filepath.Join(tmpDir, "test.log") fileLogger := NewFileLogger() - //realFileLogger, ok := fileLogger.(*FileLogger) - //assert.True(t, ok) + // realFileLogger, ok := fileLogger.(*FileLogger) + // assert.True(t, ok) // Fail if there is bad json err = fileLogger.Init("{") @@ -44,7 +44,6 @@ func TestFileLoggerFails(t *testing.T) { // Fail if the file isn't a filename err = fileLogger.Init(fmt.Sprintf("{\"prefix\":\"%s\",\"level\":\"%s\",\"flags\":%d,\"filename\":\"%s\"}", prefix, level.String(), flags, filepath.ToSlash(tmpDir))) assert.Error(t, err) - } func TestFileLogger(t *testing.T) { @@ -125,7 +124,7 @@ func TestFileLogger(t *testing.T) { assert.Equal(t, expected, string(logData)) for num := 2; num <= 999; num++ { - file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0666) + file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0o666) assert.NoError(t, err) file.Close() } @@ -202,7 +201,7 @@ func TestCompressFileLogger(t *testing.T) { fileLogger.Flush() for num := 2; num <= 999; num++ { - file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d.gz", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0666) + file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d.gz", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0o666) assert.NoError(t, err) file.Close() } @@ -217,9 +216,9 @@ func TestCompressOldFile(t *testing.T) { fname := filepath.Join(tmpDir, "test") nonGzip := filepath.Join(tmpDir, "test-nonGzip") - f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0660) + f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) - ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0660) + ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) for i := 0; i < 999; i++ { diff --git a/modules/log/log_test.go b/modules/log/log_test.go index d14daa5a206d..33f68c8e8e96 100644 --- a/modules/log/log_test.go +++ b/modules/log/log_test.go @@ -136,7 +136,6 @@ func TestNewLogggerRecreate(t *testing.T) { // We should be able to redelete without a problem go DelLogger("console") - } func TestNewNamedLogger(t *testing.T) { diff --git a/modules/log/logger.go b/modules/log/logger.go index 75f361ccdba4..0045d793229d 100644 --- a/modules/log/logger.go +++ b/modules/log/logger.go @@ -65,7 +65,6 @@ func (l *LevelLoggerLogger) IsTrace() bool { // Debug records debug log func (l *LevelLoggerLogger) Debug(format string, v ...interface{}) { l.Log(1, DEBUG, format, v...) - } // IsDebug returns true if the logger is DEBUG diff --git a/modules/log/stack.go b/modules/log/stack.go index 8fc3f35421fe..4b40d81ab721 100644 --- a/modules/log/stack.go +++ b/modules/log/stack.go @@ -11,9 +11,7 @@ import ( "runtime" ) -var ( - unknown = []byte("???") -) +var unknown = []byte("???") // Stack will skip back the provided number of frames and return a stack trace with source code. // Although we could just use debug.Stack(), this routine will return the source code and diff --git a/modules/log/writer.go b/modules/log/writer.go index e8d06b67aba0..1c4f5b4a1951 100644 --- a/modules/log/writer.go +++ b/modules/log/writer.go @@ -189,7 +189,7 @@ func (logger *WriterLogger) createMsg(buf *[]byte, event *Event) { *buf = append(*buf, ' ') } - var msg = []byte(event.msg) + msg := []byte(event.msg) if len(msg) > 0 && msg[len(msg)-1] == '\n' { msg = msg[:len(msg)-1] } diff --git a/modules/markup/common/footnote.go b/modules/markup/common/footnote.go index 92a54101f0c4..7b6c57f927c1 100644 --- a/modules/markup/common/footnote.go +++ b/modules/markup/common/footnote.go @@ -178,8 +178,7 @@ func NewFootnoteList() *FootnoteList { var footnoteListKey = parser.NewContextKey() -type footnoteBlockParser struct { -} +type footnoteBlockParser struct{} var defaultFootnoteBlockParser = &footnoteBlockParser{} @@ -265,8 +264,7 @@ func (b *footnoteBlockParser) CanAcceptIndentedLine() bool { return false } -type footnoteParser struct { -} +type footnoteParser struct{} var defaultFootnoteParser = &footnoteParser{} @@ -337,8 +335,7 @@ func (s *footnoteParser) Parse(parent ast.Node, block text.Reader, pc parser.Con return NewFootnoteLink(index, name) } -type footnoteASTTransformer struct { -} +type footnoteASTTransformer struct{} var defaultFootnoteASTTransformer = &footnoteASTTransformer{} @@ -357,7 +354,7 @@ func (a *footnoteASTTransformer) Transform(node *ast.Document, reader text.Reade } pc.Set(footnoteListKey, nil) for footnote := list.FirstChild(); footnote != nil; { - var container ast.Node = footnote + container := footnote next := footnote.NextSibling() if fc := container.LastChild(); fc != nil && ast.IsParagraph(fc) { container = fc diff --git a/modules/markup/common/html.go b/modules/markup/common/html.go index 3a47686f1ef8..a2328a2288bf 100644 --- a/modules/markup/common/html.go +++ b/modules/markup/common/html.go @@ -8,12 +8,10 @@ import ( "mvdan.cc/xurls/v2" ) -var ( - // NOTE: All below regex matching do not perform any extra validation. - // Thus a link is produced even if the linked entity does not exist. - // While fast, this is also incorrect and lead to false positives. - // TODO: fix invalid linking issue +// NOTE: All below regex matching do not perform any extra validation. +// Thus a link is produced even if the linked entity does not exist. +// While fast, this is also incorrect and lead to false positives. +// TODO: fix invalid linking issue - // LinkRegex is a regexp matching a valid link - LinkRegex, _ = xurls.StrictMatchingScheme("https?://") -) +// LinkRegex is a regexp matching a valid link +var LinkRegex, _ = xurls.StrictMatchingScheme("https?://") diff --git a/modules/markup/common/linkify.go b/modules/markup/common/linkify.go index 8a4b2a898575..2140486a30d2 100644 --- a/modules/markup/common/linkify.go +++ b/modules/markup/common/linkify.go @@ -20,8 +20,7 @@ import ( var wwwURLRegxp = regexp.MustCompile(`^www\.[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}((?:/|[#?])[-a-zA-Z0-9@:%_\+.~#!?&//=\(\);,'">\^{}\[\]` + "`" + `]*)?`) -type linkifyParser struct { -} +type linkifyParser struct{} var defaultLinkifyParser = &linkifyParser{} @@ -36,10 +35,12 @@ func (s *linkifyParser) Trigger() []byte { return []byte{' ', '*', '_', '~', '('} } -var protoHTTP = []byte("http:") -var protoHTTPS = []byte("https:") -var protoFTP = []byte("ftp:") -var domainWWW = []byte("www.") +var ( + protoHTTP = []byte("http:") + protoHTTPS = []byte("https:") + protoFTP = []byte("ftp:") + domainWWW = []byte("www.") +) func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node { if pc.IsInLinkLabel() { @@ -58,7 +59,7 @@ func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Cont var m []int var protocol []byte - var typ ast.AutoLinkType = ast.AutoLinkURL + typ := ast.AutoLinkURL if bytes.HasPrefix(line, protoHTTP) || bytes.HasPrefix(line, protoHTTPS) || bytes.HasPrefix(line, protoFTP) { m = LinkRegex.FindSubmatchIndex(line) } @@ -139,8 +140,7 @@ func (s *linkifyParser) CloseBlock(parent ast.Node, pc parser.Context) { // nothing to do } -type linkify struct { -} +type linkify struct{} // Linkify is an extension that allow you to parse text that seems like a URL. var Linkify = &linkify{} diff --git a/modules/markup/csv/csv.go b/modules/markup/csv/csv.go index c1d9d18b67c0..de32c57a64f1 100644 --- a/modules/markup/csv/csv.go +++ b/modules/markup/csv/csv.go @@ -22,8 +22,7 @@ func init() { } // Renderer implements markup.Renderer for csv files -type Renderer struct { -} +type Renderer struct{} // Name implements markup.Renderer func (Renderer) Name() string { @@ -83,7 +82,7 @@ func writeField(w io.Writer, element, class, field string) error { // Render implements markup.Renderer func (Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error { - var tmpBlock = bufio.NewWriter(output) + tmpBlock := bufio.NewWriter(output) // FIXME: don't read all to memory rawBytes, err := io.ReadAll(input) diff --git a/modules/markup/csv/csv_test.go b/modules/markup/csv/csv_test.go index 613762f86cee..612f78c76cb3 100644 --- a/modules/markup/csv/csv_test.go +++ b/modules/markup/csv/csv_test.go @@ -15,7 +15,7 @@ import ( func TestRenderCSV(t *testing.T) { var render Renderer - var kases = map[string]string{ + kases := map[string]string{ "a": "
1a
", "1,2": "
112
", "1;2\n3;4": "
112
234
", diff --git a/modules/markup/html.go b/modules/markup/html.go index f082b97dbb6d..e28e26c6d16d 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -202,7 +202,7 @@ func RenderCommitMessage( ctx *RenderContext, content string, ) (string, error) { - var procs = commitMessageProcessors + procs := commitMessageProcessors if ctx.DefaultLink != "" { // we don't have to fear data races, because being // commitMessageProcessors of fixed len and cap, every time we append @@ -238,7 +238,7 @@ func RenderCommitMessageSubject( ctx *RenderContext, content string, ) (string, error) { - var procs = commitMessageSubjectProcessors + procs := commitMessageSubjectProcessors if ctx.DefaultLink != "" { // we don't have to fear data races, because being // commitMessageSubjectProcessors of fixed len and cap, every time we @@ -291,8 +291,10 @@ func RenderEmoji( return renderProcessString(&RenderContext{}, emojiProcessors, content) } -var tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`) -var nulCleaner = strings.NewReplacer("\000", "") +var ( + tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`) + nulCleaner = strings.NewReplacer("\000", "") +) func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output io.Writer) error { defer ctx.Cancel() diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go index a79b9824735d..f0eb3253e1bd 100644 --- a/modules/markup/html_internal_test.go +++ b/modules/markup/html_internal_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/assert" ) -const TestAppURL = "http://localhost:3000/" -const TestOrgRepo = "gogits/gogs" -const TestRepoURL = TestAppURL + TestOrgRepo + "/" +const ( + TestAppURL = "http://localhost:3000/" + TestOrgRepo = "gogits/gogs" + TestRepoURL = TestAppURL + TestOrgRepo + "/" +) // alphanumLink an HTML link to an alphanumeric-style issue func alphanumIssueLink(baseURL, class, name string) string { diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go index 2824dca504f4..ee9b17df2ff1 100644 --- a/modules/markup/html_test.go +++ b/modules/markup/html_test.go @@ -38,17 +38,17 @@ func TestRender_Commits(t *testing.T) { assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } - var sha = "65f1bf27bc3bf70f64657658635e66094edbcb4d" - var repo = TestRepoURL - var commit = util.URLJoin(repo, "commit", sha) - var tree = util.URLJoin(repo, "tree", sha, "src") - - var file = util.URLJoin(repo, "commit", sha, "example.txt") - var fileWithExtra = file + ":" - var fileWithHash = file + "#L2" - var fileWithHasExtra = file + "#L2:" - var commitCompare = util.URLJoin(repo, "compare", sha+"..."+sha) - var commitCompareWithHash = commitCompare + "#L2" + sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d" + repo := TestRepoURL + commit := util.URLJoin(repo, "commit", sha) + tree := util.URLJoin(repo, "tree", sha, "src") + + file := util.URLJoin(repo, "commit", sha, "example.txt") + fileWithExtra := file + ":" + fileWithHash := file + "#L2" + fileWithHasExtra := file + "#L2:" + commitCompare := util.URLJoin(repo, "compare", sha+"..."+sha) + commitCompareWithHash := commitCompare + "#L2" test(sha, `

65f1bf27bc

`) test(sha[:7], `

65f1bf2

`) @@ -102,8 +102,8 @@ func TestRender_CrossReferences(t *testing.T) { func TestMisc_IsSameDomain(t *testing.T) { setting.AppURL = TestAppURL - var sha = "b6dd6210eaebc915fd5be5579c58cce4da2e2579" - var commit = util.URLJoin(TestRepoURL, "commit", sha) + sha := "b6dd6210eaebc915fd5be5579c58cce4da2e2579" + commit := util.URLJoin(TestRepoURL, "commit", sha) assert.True(t, IsSameDomain(commit)) assert.False(t, IsSameDomain("http://google.com/ncr")) @@ -291,7 +291,7 @@ func TestRender_emoji(t *testing.T) { `

`+emoji.GemojiData[i].Emoji+`

`) } - //Text that should be turned into or recognized as emoji + // Text that should be turned into or recognized as emoji test( ":gitea:", `

:gitea:

`) @@ -472,7 +472,7 @@ func TestRender_RelativeImages(t *testing.T) { func Test_ParseClusterFuzz(t *testing.T) { setting.AppURL = TestAppURL - var localMetas = map[string]string{ + localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", } @@ -502,7 +502,7 @@ func Test_ParseClusterFuzz(t *testing.T) { func TestIssue16020(t *testing.T) { setting.AppURL = TestAppURL - var localMetas = map[string]string{ + localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", } diff --git a/modules/markup/markdown/goldmark.go b/modules/markup/markdown/goldmark.go index 83afb8b6637d..9b6cd3aaefba 100644 --- a/modules/markup/markdown/goldmark.go +++ b/modules/markup/markdown/goldmark.go @@ -42,7 +42,7 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa metaData := meta.GetItems(pc) firstChild := node.FirstChild() createTOC := false - var toc = []Header{} + toc := []Header{} rc := &RenderConfig{ Meta: "table", Icon: "table", diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index 5ce36a1d162c..b45b9c8b8ae6 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -28,12 +28,16 @@ import ( "github.com/yuin/goldmark/util" ) -var converter goldmark.Markdown -var once = sync.Once{} +var ( + converter goldmark.Markdown + once = sync.Once{} +) -var urlPrefixKey = parser.NewContextKey() -var isWikiKey = parser.NewContextKey() -var renderMetasKey = parser.NewContextKey() +var ( + urlPrefixKey = parser.NewContextKey() + isWikiKey = parser.NewContextKey() + renderMetasKey = parser.NewContextKey() +) type limitWriter struct { w io.Writer @@ -134,7 +138,6 @@ func actualRender(ctx *markup.RenderContext, input io.Reader, output io.Writer) util.Prioritized(NewHTMLRenderer(), 10), ), ) - }) lw := &limitWriter{ @@ -190,10 +193,8 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error return actualRender(ctx, input, output) } -var ( - // MarkupName describes markup's name - MarkupName = "markdown" -) +// MarkupName describes markup's name +var MarkupName = "markdown" func init() { markup.RegisterRenderer(Renderer{}) diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index 84295b3d4eae..54c2ea87d677 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -18,9 +18,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) // these values should match the Repo const above var localMetas = map[string]string{ @@ -120,7 +122,6 @@ func TestRender_Images(t *testing.T) { test( "[!["+title+"]("+url+")]("+href+")", `

`+title+`

`) - } func testAnswers(baseURLContent, baseURLImages string) []string { diff --git a/modules/markup/mdstripper/mdstripper.go b/modules/markup/mdstripper/mdstripper.go index 2977c8197789..64079194fff7 100644 --- a/modules/markup/mdstripper/mdstripper.go +++ b/modules/markup/mdstripper/mdstripper.go @@ -147,8 +147,10 @@ func StripMarkdown(rawBytes []byte) (string, []string) { return string(buf), links } -var stripParser parser.Parser -var once = sync.Once{} +var ( + stripParser parser.Parser + once = sync.Once{} +) // StripMarkdownBytes parses markdown content by removing all markup and code blocks // in order to extract links and other references diff --git a/modules/markup/mdstripper/mdstripper_test.go b/modules/markup/mdstripper/mdstripper_test.go index 13cea0ff72a1..8045c34c079a 100644 --- a/modules/markup/mdstripper/mdstripper_test.go +++ b/modules/markup/mdstripper/mdstripper_test.go @@ -52,7 +52,8 @@ A HIDDEN ` + "`" + `GHOST` + "`" + ` IN THIS LINE. }, []string{ "link", - }}, + }, + }, { "Simply closes: #29 yes", []string{ diff --git a/modules/markup/orgmode/orgmode.go b/modules/markup/orgmode/orgmode.go index b035e04a1fcc..8aa5f45ee244 100644 --- a/modules/markup/orgmode/orgmode.go +++ b/modules/markup/orgmode/orgmode.go @@ -27,8 +27,7 @@ func init() { } // Renderer implements markup.Renderer for orgmode -type Renderer struct { -} +type Renderer struct{} // Name implements markup.Renderer func (Renderer) Name() string { diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index 38c010ef68d9..4fc0a20db2b2 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) func TestRender_StandardLinks(t *testing.T) { setting.AppURL = AppURL diff --git a/modules/markup/sanitizer.go b/modules/markup/sanitizer.go index 92dd19f0a1e5..388af567123d 100644 --- a/modules/markup/sanitizer.go +++ b/modules/markup/sanitizer.go @@ -86,7 +86,8 @@ func createDefaultPolicy() *bluemonday.Policy { policy.AllowAttrs("class").Matching(regexp.MustCompile(`^((icon(\s+[\p{L}\p{N}_-]+)+)|(emoji))$|^([a-z][a-z0-9]{0,2})$|^` + keywordClass + `$`)).OnElements("span") // Allow generally safe attributes - generalSafeAttrs := []string{"abbr", "accept", "accept-charset", + generalSafeAttrs := []string{ + "abbr", "accept", "accept-charset", "accesskey", "action", "align", "alt", "aria-describedby", "aria-hidden", "aria-label", "aria-labelledby", "axis", "border", "cellpadding", "cellspacing", "char", diff --git a/modules/markup/sanitizer_test.go b/modules/markup/sanitizer_test.go index 64189e143523..a0753c4a56cc 100644 --- a/modules/markup/sanitizer_test.go +++ b/modules/markup/sanitizer_test.go @@ -59,5 +59,4 @@ func TestSanitizeNonEscape(t *testing.T) { if strings.Contains(string(output), "